1//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CGCUDARuntime.h"
16#include "CGCXXABI.h"
17#include "CGCall.h"
18#include "CGDebugInfo.h"
19#include "CGObjCRuntime.h"
20#include "CGOpenCLRuntime.h"
21#include "CodeGenFunction.h"
22#include "CodeGenTBAA.h"
23#include "TargetInfo.h"
24#include "clang/AST/ASTContext.h"
25#include "clang/AST/CharUnits.h"
26#include "clang/AST/DeclCXX.h"
27#include "clang/AST/DeclObjC.h"
28#include "clang/AST/DeclTemplate.h"
29#include "clang/AST/Mangle.h"
30#include "clang/AST/RecordLayout.h"
31#include "clang/AST/RecursiveASTVisitor.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/CharInfo.h"
34#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/Module.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/Version.h"
39#include "clang/Frontend/CodeGenOptions.h"
40#include "clang/Sema/SemaDiagnostic.h"
41#include "llvm/ADT/APSInt.h"
42#include "llvm/ADT/Triple.h"
43#include "llvm/IR/CallingConv.h"
44#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/Intrinsics.h"
46#include "llvm/IR/LLVMContext.h"
47#include "llvm/IR/Module.h"
48#include "llvm/Support/CallSite.h"
49#include "llvm/Support/ConvertUTF.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Target/Mangler.h"
52
53using namespace clang;
54using namespace CodeGen;
55
56static const char AnnotationSection[] = "llvm.metadata";
57
58static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
59  switch (CGM.getTarget().getCXXABI().getKind()) {
60  case TargetCXXABI::GenericAArch64:
61  case TargetCXXABI::GenericARM:
62  case TargetCXXABI::iOS:
63  case TargetCXXABI::GenericItanium:
64    return *CreateItaniumCXXABI(CGM);
65  case TargetCXXABI::Microsoft:
66    return *CreateMicrosoftCXXABI(CGM);
67  }
68
69  llvm_unreachable("invalid C++ ABI kind");
70}
71
72CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
73                             llvm::Module &M, const llvm::DataLayout &TD,
74                             DiagnosticsEngine &diags)
75    : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
76      Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
77      ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
78      TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0),
79      OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0),
80      NoObjCARCExceptionsMetadata(0), RRData(0), CFConstantStringClassRef(0),
81      ConstantStringClassRef(0), NSConstantStringType(0),
82      NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0),
83      BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0),
84      LifetimeStartFn(0), LifetimeEndFn(0),
85      SanitizerBlacklist(
86          llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
87      SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
88                                          : LangOpts.Sanitize) {
89
90  // Initialize the type cache.
91  llvm::LLVMContext &LLVMContext = M.getContext();
92  VoidTy = llvm::Type::getVoidTy(LLVMContext);
93  Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
94  Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
95  Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
96  Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
97  FloatTy = llvm::Type::getFloatTy(LLVMContext);
98  DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
99  PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
100  PointerAlignInBytes =
101  C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
102  IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
103  IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
104  Int8PtrTy = Int8Ty->getPointerTo(0);
105  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
106
107  RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
108
109  if (LangOpts.ObjC1)
110    createObjCRuntime();
111  if (LangOpts.OpenCL)
112    createOpenCLRuntime();
113  if (LangOpts.CUDA)
114    createCUDARuntime();
115
116  // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
117  if (SanOpts.Thread ||
118      (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
119    TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
120                           ABI.getMangleContext());
121
122  // If debug info or coverage generation is enabled, create the CGDebugInfo
123  // object.
124  if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
125      CodeGenOpts.EmitGcovArcs ||
126      CodeGenOpts.EmitGcovNotes)
127    DebugInfo = new CGDebugInfo(*this);
128
129  Block.GlobalUniqueCount = 0;
130
131  if (C.getLangOpts().ObjCAutoRefCount)
132    ARCData = new ARCEntrypoints();
133  RRData = new RREntrypoints();
134}
135
136CodeGenModule::~CodeGenModule() {
137  delete ObjCRuntime;
138  delete OpenCLRuntime;
139  delete CUDARuntime;
140  delete TheTargetCodeGenInfo;
141  delete &ABI;
142  delete TBAA;
143  delete DebugInfo;
144  delete ARCData;
145  delete RRData;
146}
147
148void CodeGenModule::createObjCRuntime() {
149  // This is just isGNUFamily(), but we want to force implementors of
150  // new ABIs to decide how best to do this.
151  switch (LangOpts.ObjCRuntime.getKind()) {
152  case ObjCRuntime::GNUstep:
153  case ObjCRuntime::GCC:
154  case ObjCRuntime::ObjFW:
155    ObjCRuntime = CreateGNUObjCRuntime(*this);
156    return;
157
158  case ObjCRuntime::FragileMacOSX:
159  case ObjCRuntime::MacOSX:
160  case ObjCRuntime::iOS:
161    ObjCRuntime = CreateMacObjCRuntime(*this);
162    return;
163  }
164  llvm_unreachable("bad runtime kind");
165}
166
167void CodeGenModule::createOpenCLRuntime() {
168  OpenCLRuntime = new CGOpenCLRuntime(*this);
169}
170
171void CodeGenModule::createCUDARuntime() {
172  CUDARuntime = CreateNVCUDARuntime(*this);
173}
174
175void CodeGenModule::applyReplacements() {
176  for (ReplacementsTy::iterator I = Replacements.begin(),
177                                E = Replacements.end();
178       I != E; ++I) {
179    StringRef MangledName = I->first();
180    llvm::Constant *Replacement = I->second;
181    llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
182    if (!Entry)
183      continue;
184    llvm::Function *OldF = cast<llvm::Function>(Entry);
185    llvm::Function *NewF = dyn_cast<llvm::Function>(Replacement);
186    if (!NewF) {
187      llvm::ConstantExpr *CE = cast<llvm::ConstantExpr>(Replacement);
188      assert(CE->getOpcode() == llvm::Instruction::BitCast ||
189             CE->getOpcode() == llvm::Instruction::GetElementPtr);
190      NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
191    }
192
193    // Replace old with new, but keep the old order.
194    OldF->replaceAllUsesWith(Replacement);
195    if (NewF) {
196      NewF->removeFromParent();
197      OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
198    }
199    OldF->eraseFromParent();
200  }
201}
202
203void CodeGenModule::checkAliases() {
204  bool Error = false;
205  for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
206         E = Aliases.end(); I != E; ++I) {
207    const GlobalDecl &GD = *I;
208    const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
209    const AliasAttr *AA = D->getAttr<AliasAttr>();
210    StringRef MangledName = getMangledName(GD);
211    llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
212    llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
213    llvm::GlobalValue *GV = Alias->getAliasedGlobal();
214    if (GV->isDeclaration()) {
215      Error = true;
216      getDiags().Report(AA->getLocation(), diag::err_alias_to_undefined);
217    } else if (!Alias->resolveAliasedGlobal(/*stopOnWeak*/ false)) {
218      Error = true;
219      getDiags().Report(AA->getLocation(), diag::err_cyclic_alias);
220    }
221  }
222  if (!Error)
223    return;
224
225  for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
226         E = Aliases.end(); I != E; ++I) {
227    const GlobalDecl &GD = *I;
228    StringRef MangledName = getMangledName(GD);
229    llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
230    llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
231    Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
232    Alias->eraseFromParent();
233  }
234}
235
236void CodeGenModule::Release() {
237  EmitDeferred();
238  applyReplacements();
239  checkAliases();
240  EmitCXXGlobalInitFunc();
241  EmitCXXGlobalDtorFunc();
242  EmitCXXThreadLocalInitFunc();
243  if (ObjCRuntime)
244    if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
245      AddGlobalCtor(ObjCInitFunction);
246  EmitCtorList(GlobalCtors, "llvm.global_ctors");
247  EmitCtorList(GlobalDtors, "llvm.global_dtors");
248  EmitGlobalAnnotations();
249  EmitStaticExternCAliases();
250  EmitLLVMUsed();
251
252  if (CodeGenOpts.Autolink &&
253      (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
254    EmitModuleLinkOptions();
255  }
256  if (CodeGenOpts.DwarfVersion)
257    // We actually want the latest version when there are conflicts.
258    // We can change from Warning to Latest if such mode is supported.
259    getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
260                              CodeGenOpts.DwarfVersion);
261  if (DebugInfo)
262    // We support a single version in the linked module: error out when
263    // modules do not have the same version. We are going to implement dropping
264    // debug info when the version number is not up-to-date. Once that is
265    // done, the bitcode linker is not going to see modules with different
266    // version numbers.
267    getModule().addModuleFlag(llvm::Module::Error, "Debug Info Version",
268                              llvm::DEBUG_METADATA_VERSION);
269
270  SimplifyPersonality();
271
272  if (getCodeGenOpts().EmitDeclMetadata)
273    EmitDeclMetadata();
274
275  if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
276    EmitCoverageFile();
277
278  if (DebugInfo)
279    DebugInfo->finalize();
280
281  EmitVersionIdentMetadata();
282}
283
284void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
285  // Make sure that this type is translated.
286  Types.UpdateCompletedType(TD);
287}
288
289llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
290  if (!TBAA)
291    return 0;
292  return TBAA->getTBAAInfo(QTy);
293}
294
295llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
296  if (!TBAA)
297    return 0;
298  return TBAA->getTBAAInfoForVTablePtr();
299}
300
301llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
302  if (!TBAA)
303    return 0;
304  return TBAA->getTBAAStructInfo(QTy);
305}
306
307llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
308  if (!TBAA)
309    return 0;
310  return TBAA->getTBAAStructTypeInfo(QTy);
311}
312
313llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
314                                                  llvm::MDNode *AccessN,
315                                                  uint64_t O) {
316  if (!TBAA)
317    return 0;
318  return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
319}
320
321/// Decorate the instruction with a TBAA tag. For both scalar TBAA
322/// and struct-path aware TBAA, the tag has the same format:
323/// base type, access type and offset.
324/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
325void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
326                                        llvm::MDNode *TBAAInfo,
327                                        bool ConvertTypeToTag) {
328  if (ConvertTypeToTag && TBAA)
329    Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
330                      TBAA->getTBAAScalarTagInfo(TBAAInfo));
331  else
332    Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
333}
334
335void CodeGenModule::Error(SourceLocation loc, StringRef error) {
336  unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
337  getDiags().Report(Context.getFullLoc(loc), diagID);
338}
339
340/// ErrorUnsupported - Print out an error that codegen doesn't support the
341/// specified stmt yet.
342void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
343  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
344                                               "cannot compile this %0 yet");
345  std::string Msg = Type;
346  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
347    << Msg << S->getSourceRange();
348}
349
350/// ErrorUnsupported - Print out an error that codegen doesn't support the
351/// specified decl yet.
352void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
353  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
354                                               "cannot compile this %0 yet");
355  std::string Msg = Type;
356  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
357}
358
359llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
360  return llvm::ConstantInt::get(SizeTy, size.getQuantity());
361}
362
363void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
364                                        const NamedDecl *D) const {
365  // Internal definitions always have default visibility.
366  if (GV->hasLocalLinkage()) {
367    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
368    return;
369  }
370
371  // Set visibility for definitions.
372  LinkageInfo LV = D->getLinkageAndVisibility();
373  if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
374    GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
375}
376
377static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
378  return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
379      .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
380      .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
381      .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
382      .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
383}
384
385static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
386    CodeGenOptions::TLSModel M) {
387  switch (M) {
388  case CodeGenOptions::GeneralDynamicTLSModel:
389    return llvm::GlobalVariable::GeneralDynamicTLSModel;
390  case CodeGenOptions::LocalDynamicTLSModel:
391    return llvm::GlobalVariable::LocalDynamicTLSModel;
392  case CodeGenOptions::InitialExecTLSModel:
393    return llvm::GlobalVariable::InitialExecTLSModel;
394  case CodeGenOptions::LocalExecTLSModel:
395    return llvm::GlobalVariable::LocalExecTLSModel;
396  }
397  llvm_unreachable("Invalid TLS model!");
398}
399
400void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
401                               const VarDecl &D) const {
402  assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
403
404  llvm::GlobalVariable::ThreadLocalMode TLM;
405  TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
406
407  // Override the TLS model if it is explicitly specified.
408  if (D.hasAttr<TLSModelAttr>()) {
409    const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
410    TLM = GetLLVMTLSModel(Attr->getModel());
411  }
412
413  GV->setThreadLocalMode(TLM);
414}
415
416/// Set the symbol visibility of type information (vtable and RTTI)
417/// associated with the given type.
418void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
419                                      const CXXRecordDecl *RD,
420                                      TypeVisibilityKind TVK) const {
421  setGlobalVisibility(GV, RD);
422
423  if (!CodeGenOpts.HiddenWeakVTables)
424    return;
425
426  // We never want to drop the visibility for RTTI names.
427  if (TVK == TVK_ForRTTIName)
428    return;
429
430  // We want to drop the visibility to hidden for weak type symbols.
431  // This isn't possible if there might be unresolved references
432  // elsewhere that rely on this symbol being visible.
433
434  // This should be kept roughly in sync with setThunkVisibility
435  // in CGVTables.cpp.
436
437  // Preconditions.
438  if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
439      GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
440    return;
441
442  // Don't override an explicit visibility attribute.
443  if (RD->getExplicitVisibility(NamedDecl::VisibilityForType))
444    return;
445
446  switch (RD->getTemplateSpecializationKind()) {
447  // We have to disable the optimization if this is an EI definition
448  // because there might be EI declarations in other shared objects.
449  case TSK_ExplicitInstantiationDefinition:
450  case TSK_ExplicitInstantiationDeclaration:
451    return;
452
453  // Every use of a non-template class's type information has to emit it.
454  case TSK_Undeclared:
455    break;
456
457  // In theory, implicit instantiations can ignore the possibility of
458  // an explicit instantiation declaration because there necessarily
459  // must be an EI definition somewhere with default visibility.  In
460  // practice, it's possible to have an explicit instantiation for
461  // an arbitrary template class, and linkers aren't necessarily able
462  // to deal with mixed-visibility symbols.
463  case TSK_ExplicitSpecialization:
464  case TSK_ImplicitInstantiation:
465    return;
466  }
467
468  // If there's a key function, there may be translation units
469  // that don't have the key function's definition.  But ignore
470  // this if we're emitting RTTI under -fno-rtti.
471  if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
472    // FIXME: what should we do if we "lose" the key function during
473    // the emission of the file?
474    if (Context.getCurrentKeyFunction(RD))
475      return;
476  }
477
478  // Otherwise, drop the visibility to hidden.
479  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
480  GV->setUnnamedAddr(true);
481}
482
483StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
484  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
485
486  StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
487  if (!Str.empty())
488    return Str;
489
490  if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
491    IdentifierInfo *II = ND->getIdentifier();
492    assert(II && "Attempt to mangle unnamed decl.");
493
494    Str = II->getName();
495    return Str;
496  }
497
498  SmallString<256> Buffer;
499  llvm::raw_svector_ostream Out(Buffer);
500  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
501    getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
502  else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
503    getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
504  else
505    getCXXABI().getMangleContext().mangleName(ND, Out);
506
507  // Allocate space for the mangled name.
508  Out.flush();
509  size_t Length = Buffer.size();
510  char *Name = MangledNamesAllocator.Allocate<char>(Length);
511  std::copy(Buffer.begin(), Buffer.end(), Name);
512
513  Str = StringRef(Name, Length);
514
515  return Str;
516}
517
518void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
519                                        const BlockDecl *BD) {
520  MangleContext &MangleCtx = getCXXABI().getMangleContext();
521  const Decl *D = GD.getDecl();
522  llvm::raw_svector_ostream Out(Buffer.getBuffer());
523  if (D == 0)
524    MangleCtx.mangleGlobalBlock(BD,
525      dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
526  else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
527    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
528  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
529    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
530  else
531    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
532}
533
534llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
535  return getModule().getNamedValue(Name);
536}
537
538/// AddGlobalCtor - Add a function to the list that will be called before
539/// main() runs.
540void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
541  // FIXME: Type coercion of void()* types.
542  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
543}
544
545/// AddGlobalDtor - Add a function to the list that will be called
546/// when the module is unloaded.
547void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
548  // FIXME: Type coercion of void()* types.
549  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
550}
551
552void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
553  // Ctor function type is void()*.
554  llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
555  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
556
557  // Get the type of a ctor entry, { i32, void ()* }.
558  llvm::StructType *CtorStructTy =
559    llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
560
561  // Construct the constructor and destructor arrays.
562  SmallVector<llvm::Constant*, 8> Ctors;
563  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
564    llvm::Constant *S[] = {
565      llvm::ConstantInt::get(Int32Ty, I->second, false),
566      llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
567    };
568    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
569  }
570
571  if (!Ctors.empty()) {
572    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
573    new llvm::GlobalVariable(TheModule, AT, false,
574                             llvm::GlobalValue::AppendingLinkage,
575                             llvm::ConstantArray::get(AT, Ctors),
576                             GlobalName);
577  }
578}
579
580llvm::GlobalValue::LinkageTypes
581CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
582  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
583
584  if (isa<CXXDestructorDecl>(D) &&
585      getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
586                                         GD.getDtorType()))
587    return llvm::Function::LinkOnceODRLinkage;
588
589  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
590
591  if (Linkage == GVA_Internal)
592    return llvm::Function::InternalLinkage;
593
594  if (D->hasAttr<DLLExportAttr>())
595    return llvm::Function::DLLExportLinkage;
596
597  if (D->hasAttr<WeakAttr>())
598    return llvm::Function::WeakAnyLinkage;
599
600  // In C99 mode, 'inline' functions are guaranteed to have a strong
601  // definition somewhere else, so we can use available_externally linkage.
602  if (Linkage == GVA_C99Inline)
603    return llvm::Function::AvailableExternallyLinkage;
604
605  // Note that Apple's kernel linker doesn't support symbol
606  // coalescing, so we need to avoid linkonce and weak linkages there.
607  // Normally, this means we just map to internal, but for explicit
608  // instantiations we'll map to external.
609
610  // In C++, the compiler has to emit a definition in every translation unit
611  // that references the function.  We should use linkonce_odr because
612  // a) if all references in this translation unit are optimized away, we
613  // don't need to codegen it.  b) if the function persists, it needs to be
614  // merged with other definitions. c) C++ has the ODR, so we know the
615  // definition is dependable.
616  if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
617    return !Context.getLangOpts().AppleKext
618             ? llvm::Function::LinkOnceODRLinkage
619             : llvm::Function::InternalLinkage;
620
621  // An explicit instantiation of a template has weak linkage, since
622  // explicit instantiations can occur in multiple translation units
623  // and must all be equivalent. However, we are not allowed to
624  // throw away these explicit instantiations.
625  if (Linkage == GVA_ExplicitTemplateInstantiation)
626    return !Context.getLangOpts().AppleKext
627             ? llvm::Function::WeakODRLinkage
628             : llvm::Function::ExternalLinkage;
629
630  // Otherwise, we have strong external linkage.
631  assert(Linkage == GVA_StrongExternal);
632  return llvm::Function::ExternalLinkage;
633}
634
635
636/// SetFunctionDefinitionAttributes - Set attributes for a global.
637///
638/// FIXME: This is currently only done for aliases and functions, but not for
639/// variables (these details are set in EmitGlobalVarDefinition for variables).
640void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
641                                                    llvm::GlobalValue *GV) {
642  SetCommonAttributes(D, GV);
643}
644
645void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
646                                              const CGFunctionInfo &Info,
647                                              llvm::Function *F) {
648  unsigned CallingConv;
649  AttributeListType AttributeList;
650  ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
651  F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
652  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
653}
654
655/// Determines whether the language options require us to model
656/// unwind exceptions.  We treat -fexceptions as mandating this
657/// except under the fragile ObjC ABI with only ObjC exceptions
658/// enabled.  This means, for example, that C with -fexceptions
659/// enables this.
660static bool hasUnwindExceptions(const LangOptions &LangOpts) {
661  // If exceptions are completely disabled, obviously this is false.
662  if (!LangOpts.Exceptions) return false;
663
664  // If C++ exceptions are enabled, this is true.
665  if (LangOpts.CXXExceptions) return true;
666
667  // If ObjC exceptions are enabled, this depends on the ABI.
668  if (LangOpts.ObjCExceptions) {
669    return LangOpts.ObjCRuntime.hasUnwindExceptions();
670  }
671
672  return true;
673}
674
675void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
676                                                           llvm::Function *F) {
677  llvm::AttrBuilder B;
678
679  if (CodeGenOpts.UnwindTables)
680    B.addAttribute(llvm::Attribute::UWTable);
681
682  if (!hasUnwindExceptions(LangOpts))
683    B.addAttribute(llvm::Attribute::NoUnwind);
684
685  if (D->hasAttr<NakedAttr>()) {
686    // Naked implies noinline: we should not be inlining such functions.
687    B.addAttribute(llvm::Attribute::Naked);
688    B.addAttribute(llvm::Attribute::NoInline);
689  } else if (D->hasAttr<NoInlineAttr>()) {
690    B.addAttribute(llvm::Attribute::NoInline);
691  } else if ((D->hasAttr<AlwaysInlineAttr>() ||
692              D->hasAttr<ForceInlineAttr>()) &&
693             !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
694                                              llvm::Attribute::NoInline)) {
695    // (noinline wins over always_inline, and we can't specify both in IR)
696    B.addAttribute(llvm::Attribute::AlwaysInline);
697  }
698
699  if (D->hasAttr<ColdAttr>()) {
700    B.addAttribute(llvm::Attribute::OptimizeForSize);
701    B.addAttribute(llvm::Attribute::Cold);
702  }
703
704  if (D->hasAttr<MinSizeAttr>())
705    B.addAttribute(llvm::Attribute::MinSize);
706
707  if (LangOpts.getStackProtector() == LangOptions::SSPOn)
708    B.addAttribute(llvm::Attribute::StackProtect);
709  else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
710    B.addAttribute(llvm::Attribute::StackProtectReq);
711
712  // Add sanitizer attributes if function is not blacklisted.
713  if (!SanitizerBlacklist->isIn(*F)) {
714    // When AddressSanitizer is enabled, set SanitizeAddress attribute
715    // unless __attribute__((no_sanitize_address)) is used.
716    if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
717      B.addAttribute(llvm::Attribute::SanitizeAddress);
718    // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
719    if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
720      B.addAttribute(llvm::Attribute::SanitizeThread);
721    }
722    // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
723    if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
724      B.addAttribute(llvm::Attribute::SanitizeMemory);
725  }
726
727  F->addAttributes(llvm::AttributeSet::FunctionIndex,
728                   llvm::AttributeSet::get(
729                       F->getContext(), llvm::AttributeSet::FunctionIndex, B));
730
731  if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
732    F->setUnnamedAddr(true);
733  else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
734    if (MD->isVirtual())
735      F->setUnnamedAddr(true);
736
737  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
738  if (alignment)
739    F->setAlignment(alignment);
740
741  // C++ ABI requires 2-byte alignment for member functions.
742  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
743    F->setAlignment(2);
744}
745
746void CodeGenModule::SetCommonAttributes(const Decl *D,
747                                        llvm::GlobalValue *GV) {
748  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
749    setGlobalVisibility(GV, ND);
750  else
751    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
752
753  if (D->hasAttr<UsedAttr>())
754    AddUsedGlobal(GV);
755
756  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
757    GV->setSection(SA->getName());
758
759  // Alias cannot have attributes. Filter them here.
760  if (!isa<llvm::GlobalAlias>(GV))
761    getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
762}
763
764void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
765                                                  llvm::Function *F,
766                                                  const CGFunctionInfo &FI) {
767  SetLLVMFunctionAttributes(D, FI, F);
768  SetLLVMFunctionAttributesForDefinition(D, F);
769
770  F->setLinkage(llvm::Function::InternalLinkage);
771
772  SetCommonAttributes(D, F);
773}
774
775void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
776                                          llvm::Function *F,
777                                          bool IsIncompleteFunction) {
778  if (unsigned IID = F->getIntrinsicID()) {
779    // If this is an intrinsic function, set the function's attributes
780    // to the intrinsic's attributes.
781    F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
782                                                    (llvm::Intrinsic::ID)IID));
783    return;
784  }
785
786  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
787
788  if (!IsIncompleteFunction)
789    SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
790
791  if (getCXXABI().HasThisReturn(GD)) {
792    assert(!F->arg_empty() &&
793           F->arg_begin()->getType()
794             ->canLosslesslyBitCastTo(F->getReturnType()) &&
795           "unexpected this return");
796    F->addAttribute(1, llvm::Attribute::Returned);
797  }
798
799  // Only a few attributes are set on declarations; these may later be
800  // overridden by a definition.
801
802  if (FD->hasAttr<DLLImportAttr>()) {
803    F->setLinkage(llvm::Function::DLLImportLinkage);
804  } else if (FD->hasAttr<WeakAttr>() ||
805             FD->isWeakImported()) {
806    // "extern_weak" is overloaded in LLVM; we probably should have
807    // separate linkage types for this.
808    F->setLinkage(llvm::Function::ExternalWeakLinkage);
809  } else {
810    F->setLinkage(llvm::Function::ExternalLinkage);
811
812    LinkageInfo LV = FD->getLinkageAndVisibility();
813    if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
814      F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
815    }
816  }
817
818  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
819    F->setSection(SA->getName());
820
821  // A replaceable global allocation function does not act like a builtin by
822  // default, only if it is invoked by a new-expression or delete-expression.
823  if (FD->isReplaceableGlobalAllocationFunction())
824    F->addAttribute(llvm::AttributeSet::FunctionIndex,
825                    llvm::Attribute::NoBuiltin);
826}
827
828void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
829  assert(!GV->isDeclaration() &&
830         "Only globals with definition can force usage.");
831  LLVMUsed.push_back(GV);
832}
833
834void CodeGenModule::EmitLLVMUsed() {
835  // Don't create llvm.used if there is no need.
836  if (LLVMUsed.empty())
837    return;
838
839  // Convert LLVMUsed to what ConstantArray needs.
840  SmallVector<llvm::Constant*, 8> UsedArray;
841  UsedArray.resize(LLVMUsed.size());
842  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
843    UsedArray[i] =
844     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
845                                    Int8PtrTy);
846  }
847
848  if (UsedArray.empty())
849    return;
850  llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
851
852  llvm::GlobalVariable *GV =
853    new llvm::GlobalVariable(getModule(), ATy, false,
854                             llvm::GlobalValue::AppendingLinkage,
855                             llvm::ConstantArray::get(ATy, UsedArray),
856                             "llvm.used");
857
858  GV->setSection("llvm.metadata");
859}
860
861void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
862  llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
863  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
864}
865
866void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
867  llvm::SmallString<32> Opt;
868  getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
869  llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
870  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
871}
872
873void CodeGenModule::AddDependentLib(StringRef Lib) {
874  llvm::SmallString<24> Opt;
875  getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
876  llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
877  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
878}
879
880/// \brief Add link options implied by the given module, including modules
881/// it depends on, using a postorder walk.
882static void addLinkOptionsPostorder(CodeGenModule &CGM,
883                                    Module *Mod,
884                                    SmallVectorImpl<llvm::Value *> &Metadata,
885                                    llvm::SmallPtrSet<Module *, 16> &Visited) {
886  // Import this module's parent.
887  if (Mod->Parent && Visited.insert(Mod->Parent)) {
888    addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
889  }
890
891  // Import this module's dependencies.
892  for (unsigned I = Mod->Imports.size(); I > 0; --I) {
893    if (Visited.insert(Mod->Imports[I-1]))
894      addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
895  }
896
897  // Add linker options to link against the libraries/frameworks
898  // described by this module.
899  llvm::LLVMContext &Context = CGM.getLLVMContext();
900  for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
901    // Link against a framework.  Frameworks are currently Darwin only, so we
902    // don't to ask TargetCodeGenInfo for the spelling of the linker option.
903    if (Mod->LinkLibraries[I-1].IsFramework) {
904      llvm::Value *Args[2] = {
905        llvm::MDString::get(Context, "-framework"),
906        llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
907      };
908
909      Metadata.push_back(llvm::MDNode::get(Context, Args));
910      continue;
911    }
912
913    // Link against a library.
914    llvm::SmallString<24> Opt;
915    CGM.getTargetCodeGenInfo().getDependentLibraryOption(
916      Mod->LinkLibraries[I-1].Library, Opt);
917    llvm::Value *OptString = llvm::MDString::get(Context, Opt);
918    Metadata.push_back(llvm::MDNode::get(Context, OptString));
919  }
920}
921
922void CodeGenModule::EmitModuleLinkOptions() {
923  // Collect the set of all of the modules we want to visit to emit link
924  // options, which is essentially the imported modules and all of their
925  // non-explicit child modules.
926  llvm::SetVector<clang::Module *> LinkModules;
927  llvm::SmallPtrSet<clang::Module *, 16> Visited;
928  SmallVector<clang::Module *, 16> Stack;
929
930  // Seed the stack with imported modules.
931  for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
932                                               MEnd = ImportedModules.end();
933       M != MEnd; ++M) {
934    if (Visited.insert(*M))
935      Stack.push_back(*M);
936  }
937
938  // Find all of the modules to import, making a little effort to prune
939  // non-leaf modules.
940  while (!Stack.empty()) {
941    clang::Module *Mod = Stack.pop_back_val();
942
943    bool AnyChildren = false;
944
945    // Visit the submodules of this module.
946    for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
947                                        SubEnd = Mod->submodule_end();
948         Sub != SubEnd; ++Sub) {
949      // Skip explicit children; they need to be explicitly imported to be
950      // linked against.
951      if ((*Sub)->IsExplicit)
952        continue;
953
954      if (Visited.insert(*Sub)) {
955        Stack.push_back(*Sub);
956        AnyChildren = true;
957      }
958    }
959
960    // We didn't find any children, so add this module to the list of
961    // modules to link against.
962    if (!AnyChildren) {
963      LinkModules.insert(Mod);
964    }
965  }
966
967  // Add link options for all of the imported modules in reverse topological
968  // order.  We don't do anything to try to order import link flags with respect
969  // to linker options inserted by things like #pragma comment().
970  SmallVector<llvm::Value *, 16> MetadataArgs;
971  Visited.clear();
972  for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
973                                               MEnd = LinkModules.end();
974       M != MEnd; ++M) {
975    if (Visited.insert(*M))
976      addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
977  }
978  std::reverse(MetadataArgs.begin(), MetadataArgs.end());
979  LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
980
981  // Add the linker options metadata flag.
982  getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
983                            llvm::MDNode::get(getLLVMContext(),
984                                              LinkerOptionsMetadata));
985}
986
987void CodeGenModule::EmitDeferred() {
988  // Emit code for any potentially referenced deferred decls.  Since a
989  // previously unused static decl may become used during the generation of code
990  // for a static function, iterate until no changes are made.
991
992  while (true) {
993    if (!DeferredVTables.empty()) {
994      EmitDeferredVTables();
995
996      // Emitting a v-table doesn't directly cause more v-tables to
997      // become deferred, although it can cause functions to be
998      // emitted that then need those v-tables.
999      assert(DeferredVTables.empty());
1000    }
1001
1002    // Stop if we're out of both deferred v-tables and deferred declarations.
1003    if (DeferredDeclsToEmit.empty()) break;
1004
1005    GlobalDecl D = DeferredDeclsToEmit.back();
1006    DeferredDeclsToEmit.pop_back();
1007
1008    // Check to see if we've already emitted this.  This is necessary
1009    // for a couple of reasons: first, decls can end up in the
1010    // deferred-decls queue multiple times, and second, decls can end
1011    // up with definitions in unusual ways (e.g. by an extern inline
1012    // function acquiring a strong function redefinition).  Just
1013    // ignore these cases.
1014    //
1015    // TODO: That said, looking this up multiple times is very wasteful.
1016    StringRef Name = getMangledName(D);
1017    llvm::GlobalValue *CGRef = GetGlobalValue(Name);
1018    assert(CGRef && "Deferred decl wasn't referenced?");
1019
1020    if (!CGRef->isDeclaration())
1021      continue;
1022
1023    // GlobalAlias::isDeclaration() defers to the aliasee, but for our
1024    // purposes an alias counts as a definition.
1025    if (isa<llvm::GlobalAlias>(CGRef))
1026      continue;
1027
1028    // Otherwise, emit the definition and move on to the next one.
1029    EmitGlobalDefinition(D);
1030  }
1031}
1032
1033void CodeGenModule::EmitGlobalAnnotations() {
1034  if (Annotations.empty())
1035    return;
1036
1037  // Create a new global variable for the ConstantStruct in the Module.
1038  llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1039    Annotations[0]->getType(), Annotations.size()), Annotations);
1040  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
1041    Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
1042    "llvm.global.annotations");
1043  gv->setSection(AnnotationSection);
1044}
1045
1046llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1047  llvm::Constant *&AStr = AnnotationStrings[Str];
1048  if (AStr)
1049    return AStr;
1050
1051  // Not found yet, create a new global.
1052  llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1053  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
1054    true, llvm::GlobalValue::PrivateLinkage, s, ".str");
1055  gv->setSection(AnnotationSection);
1056  gv->setUnnamedAddr(true);
1057  AStr = gv;
1058  return gv;
1059}
1060
1061llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1062  SourceManager &SM = getContext().getSourceManager();
1063  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1064  if (PLoc.isValid())
1065    return EmitAnnotationString(PLoc.getFilename());
1066  return EmitAnnotationString(SM.getBufferName(Loc));
1067}
1068
1069llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1070  SourceManager &SM = getContext().getSourceManager();
1071  PresumedLoc PLoc = SM.getPresumedLoc(L);
1072  unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1073    SM.getExpansionLineNumber(L);
1074  return llvm::ConstantInt::get(Int32Ty, LineNo);
1075}
1076
1077llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1078                                                const AnnotateAttr *AA,
1079                                                SourceLocation L) {
1080  // Get the globals for file name, annotation, and the line number.
1081  llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1082                 *UnitGV = EmitAnnotationUnit(L),
1083                 *LineNoCst = EmitAnnotationLineNo(L);
1084
1085  // Create the ConstantStruct for the global annotation.
1086  llvm::Constant *Fields[4] = {
1087    llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1088    llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1089    llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1090    LineNoCst
1091  };
1092  return llvm::ConstantStruct::getAnon(Fields);
1093}
1094
1095void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1096                                         llvm::GlobalValue *GV) {
1097  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1098  // Get the struct elements for these annotations.
1099  for (specific_attr_iterator<AnnotateAttr>
1100       ai = D->specific_attr_begin<AnnotateAttr>(),
1101       ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
1102    Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
1103}
1104
1105bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
1106  // Never defer when EmitAllDecls is specified.
1107  if (LangOpts.EmitAllDecls)
1108    return false;
1109
1110  return !getContext().DeclMustBeEmitted(Global);
1111}
1112
1113llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1114    const CXXUuidofExpr* E) {
1115  // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1116  // well-formed.
1117  StringRef Uuid = E->getUuidAsStringRef(Context);
1118  std::string Name = "_GUID_" + Uuid.lower();
1119  std::replace(Name.begin(), Name.end(), '-', '_');
1120
1121  // Look for an existing global.
1122  if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1123    return GV;
1124
1125  llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1126  assert(Init && "failed to initialize as constant");
1127
1128  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1129      getModule(), Init->getType(),
1130      /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1131  return GV;
1132}
1133
1134llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1135  const AliasAttr *AA = VD->getAttr<AliasAttr>();
1136  assert(AA && "No alias?");
1137
1138  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1139
1140  // See if there is already something with the target's name in the module.
1141  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1142  if (Entry) {
1143    unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1144    return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1145  }
1146
1147  llvm::Constant *Aliasee;
1148  if (isa<llvm::FunctionType>(DeclTy))
1149    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1150                                      GlobalDecl(cast<FunctionDecl>(VD)),
1151                                      /*ForVTable=*/false);
1152  else
1153    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1154                                    llvm::PointerType::getUnqual(DeclTy), 0);
1155
1156  llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1157  F->setLinkage(llvm::Function::ExternalWeakLinkage);
1158  WeakRefReferences.insert(F);
1159
1160  return Aliasee;
1161}
1162
1163void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1164  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
1165
1166  // Weak references don't produce any output by themselves.
1167  if (Global->hasAttr<WeakRefAttr>())
1168    return;
1169
1170  // If this is an alias definition (which otherwise looks like a declaration)
1171  // emit it now.
1172  if (Global->hasAttr<AliasAttr>())
1173    return EmitAliasDefinition(GD);
1174
1175  // If this is CUDA, be selective about which declarations we emit.
1176  if (LangOpts.CUDA) {
1177    if (CodeGenOpts.CUDAIsDevice) {
1178      if (!Global->hasAttr<CUDADeviceAttr>() &&
1179          !Global->hasAttr<CUDAGlobalAttr>() &&
1180          !Global->hasAttr<CUDAConstantAttr>() &&
1181          !Global->hasAttr<CUDASharedAttr>())
1182        return;
1183    } else {
1184      if (!Global->hasAttr<CUDAHostAttr>() && (
1185            Global->hasAttr<CUDADeviceAttr>() ||
1186            Global->hasAttr<CUDAConstantAttr>() ||
1187            Global->hasAttr<CUDASharedAttr>()))
1188        return;
1189    }
1190  }
1191
1192  // Ignore declarations, they will be emitted on their first use.
1193  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
1194    // Forward declarations are emitted lazily on first use.
1195    if (!FD->doesThisDeclarationHaveABody()) {
1196      if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1197        return;
1198
1199      const FunctionDecl *InlineDefinition = 0;
1200      FD->getBody(InlineDefinition);
1201
1202      StringRef MangledName = getMangledName(GD);
1203      DeferredDecls.erase(MangledName);
1204      EmitGlobalDefinition(InlineDefinition);
1205      return;
1206    }
1207  } else {
1208    const VarDecl *VD = cast<VarDecl>(Global);
1209    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1210
1211    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
1212      return;
1213  }
1214
1215  // Defer code generation when possible if this is a static definition, inline
1216  // function etc.  These we only want to emit if they are used.
1217  if (!MayDeferGeneration(Global)) {
1218    // Emit the definition if it can't be deferred.
1219    EmitGlobalDefinition(GD);
1220    return;
1221  }
1222
1223  // If we're deferring emission of a C++ variable with an
1224  // initializer, remember the order in which it appeared in the file.
1225  if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1226      cast<VarDecl>(Global)->hasInit()) {
1227    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1228    CXXGlobalInits.push_back(0);
1229  }
1230
1231  // If the value has already been used, add it directly to the
1232  // DeferredDeclsToEmit list.
1233  StringRef MangledName = getMangledName(GD);
1234  if (GetGlobalValue(MangledName))
1235    DeferredDeclsToEmit.push_back(GD);
1236  else {
1237    // Otherwise, remember that we saw a deferred decl with this name.  The
1238    // first use of the mangled name will cause it to move into
1239    // DeferredDeclsToEmit.
1240    DeferredDecls[MangledName] = GD;
1241  }
1242}
1243
1244namespace {
1245  struct FunctionIsDirectlyRecursive :
1246    public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1247    const StringRef Name;
1248    const Builtin::Context &BI;
1249    bool Result;
1250    FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1251      Name(N), BI(C), Result(false) {
1252    }
1253    typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1254
1255    bool TraverseCallExpr(CallExpr *E) {
1256      const FunctionDecl *FD = E->getDirectCallee();
1257      if (!FD)
1258        return true;
1259      AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1260      if (Attr && Name == Attr->getLabel()) {
1261        Result = true;
1262        return false;
1263      }
1264      unsigned BuiltinID = FD->getBuiltinID();
1265      if (!BuiltinID)
1266        return true;
1267      StringRef BuiltinName = BI.GetName(BuiltinID);
1268      if (BuiltinName.startswith("__builtin_") &&
1269          Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1270        Result = true;
1271        return false;
1272      }
1273      return true;
1274    }
1275  };
1276}
1277
1278// isTriviallyRecursive - Check if this function calls another
1279// decl that, because of the asm attribute or the other decl being a builtin,
1280// ends up pointing to itself.
1281bool
1282CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1283  StringRef Name;
1284  if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1285    // asm labels are a special kind of mangling we have to support.
1286    AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1287    if (!Attr)
1288      return false;
1289    Name = Attr->getLabel();
1290  } else {
1291    Name = FD->getName();
1292  }
1293
1294  FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1295  Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1296  return Walker.Result;
1297}
1298
1299bool
1300CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1301  if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1302    return true;
1303  const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
1304  if (CodeGenOpts.OptimizationLevel == 0 &&
1305      !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
1306    return false;
1307  // PR9614. Avoid cases where the source code is lying to us. An available
1308  // externally function should have an equivalent function somewhere else,
1309  // but a function that calls itself is clearly not equivalent to the real
1310  // implementation.
1311  // This happens in glibc's btowc and in some configure checks.
1312  return !isTriviallyRecursive(F);
1313}
1314
1315/// If the type for the method's class was generated by
1316/// CGDebugInfo::createContextChain(), the cache contains only a
1317/// limited DIType without any declarations. Since EmitFunctionStart()
1318/// needs to find the canonical declaration for each method, we need
1319/// to construct the complete type prior to emitting the method.
1320void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1321  if (!D->isInstance())
1322    return;
1323
1324  if (CGDebugInfo *DI = getModuleDebugInfo())
1325    if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1326      const PointerType *ThisPtr =
1327        cast<PointerType>(D->getThisType(getContext()));
1328      DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1329    }
1330}
1331
1332void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
1333  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1334
1335  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1336                                 Context.getSourceManager(),
1337                                 "Generating code for declaration");
1338
1339  if (isa<FunctionDecl>(D)) {
1340    // At -O0, don't generate IR for functions with available_externally
1341    // linkage.
1342    if (!shouldEmitFunction(GD))
1343      return;
1344
1345    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1346      CompleteDIClassType(Method);
1347      // Make sure to emit the definition(s) before we emit the thunks.
1348      // This is necessary for the generation of certain thunks.
1349      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1350        EmitCXXConstructor(CD, GD.getCtorType());
1351      else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1352        EmitCXXDestructor(DD, GD.getDtorType());
1353      else
1354        EmitGlobalFunctionDefinition(GD);
1355
1356      if (Method->isVirtual())
1357        getVTables().EmitThunks(GD);
1358
1359      return;
1360    }
1361
1362    return EmitGlobalFunctionDefinition(GD);
1363  }
1364
1365  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1366    return EmitGlobalVarDefinition(VD);
1367
1368  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1369}
1370
1371/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1372/// module, create and return an llvm Function with the specified type. If there
1373/// is something in the module with the specified name, return it potentially
1374/// bitcasted to the right type.
1375///
1376/// If D is non-null, it specifies a decl that correspond to this.  This is used
1377/// to set the attributes on the function when it is first created.
1378llvm::Constant *
1379CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1380                                       llvm::Type *Ty,
1381                                       GlobalDecl GD, bool ForVTable,
1382                                       llvm::AttributeSet ExtraAttrs) {
1383  const Decl *D = GD.getDecl();
1384
1385  // Lookup the entry, lazily creating it if necessary.
1386  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1387  if (Entry) {
1388    if (WeakRefReferences.erase(Entry)) {
1389      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1390      if (FD && !FD->hasAttr<WeakAttr>())
1391        Entry->setLinkage(llvm::Function::ExternalLinkage);
1392    }
1393
1394    if (Entry->getType()->getElementType() == Ty)
1395      return Entry;
1396
1397    // Make sure the result is of the correct type.
1398    return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1399  }
1400
1401  // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1402  // each other bottoming out with the base dtor.  Therefore we emit non-base
1403  // dtors on usage, even if there is no dtor definition in the TU.
1404  if (D && isa<CXXDestructorDecl>(D) &&
1405      getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1406                                         GD.getDtorType()))
1407    DeferredDeclsToEmit.push_back(GD);
1408
1409  // This function doesn't have a complete type (for example, the return
1410  // type is an incomplete struct). Use a fake type instead, and make
1411  // sure not to try to set attributes.
1412  bool IsIncompleteFunction = false;
1413
1414  llvm::FunctionType *FTy;
1415  if (isa<llvm::FunctionType>(Ty)) {
1416    FTy = cast<llvm::FunctionType>(Ty);
1417  } else {
1418    FTy = llvm::FunctionType::get(VoidTy, false);
1419    IsIncompleteFunction = true;
1420  }
1421
1422  llvm::Function *F = llvm::Function::Create(FTy,
1423                                             llvm::Function::ExternalLinkage,
1424                                             MangledName, &getModule());
1425  assert(F->getName() == MangledName && "name was uniqued!");
1426  if (D)
1427    SetFunctionAttributes(GD, F, IsIncompleteFunction);
1428  if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1429    llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1430    F->addAttributes(llvm::AttributeSet::FunctionIndex,
1431                     llvm::AttributeSet::get(VMContext,
1432                                             llvm::AttributeSet::FunctionIndex,
1433                                             B));
1434  }
1435
1436  // This is the first use or definition of a mangled name.  If there is a
1437  // deferred decl with this name, remember that we need to emit it at the end
1438  // of the file.
1439  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1440  if (DDI != DeferredDecls.end()) {
1441    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1442    // list, and remove it from DeferredDecls (since we don't need it anymore).
1443    DeferredDeclsToEmit.push_back(DDI->second);
1444    DeferredDecls.erase(DDI);
1445
1446  // Otherwise, if this is a sized deallocation function, emit a weak definition
1447  // for it at the end of the translation unit.
1448  } else if (D && cast<FunctionDecl>(D)
1449                      ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
1450    DeferredDeclsToEmit.push_back(GD);
1451
1452  // Otherwise, there are cases we have to worry about where we're
1453  // using a declaration for which we must emit a definition but where
1454  // we might not find a top-level definition:
1455  //   - member functions defined inline in their classes
1456  //   - friend functions defined inline in some class
1457  //   - special member functions with implicit definitions
1458  // If we ever change our AST traversal to walk into class methods,
1459  // this will be unnecessary.
1460  //
1461  // We also don't emit a definition for a function if it's going to be an entry
1462  // in a vtable, unless it's already marked as used.
1463  } else if (getLangOpts().CPlusPlus && D) {
1464    // Look for a declaration that's lexically in a record.
1465    const FunctionDecl *FD = cast<FunctionDecl>(D);
1466    FD = FD->getMostRecentDecl();
1467    do {
1468      if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1469        if (FD->isImplicit() && !ForVTable) {
1470          assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1471          DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
1472          break;
1473        } else if (FD->doesThisDeclarationHaveABody()) {
1474          DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
1475          break;
1476        }
1477      }
1478      FD = FD->getPreviousDecl();
1479    } while (FD);
1480  }
1481
1482  // Make sure the result is of the requested type.
1483  if (!IsIncompleteFunction) {
1484    assert(F->getType()->getElementType() == Ty);
1485    return F;
1486  }
1487
1488  llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1489  return llvm::ConstantExpr::getBitCast(F, PTy);
1490}
1491
1492/// GetAddrOfFunction - Return the address of the given function.  If Ty is
1493/// non-null, then this function will use the specified type if it has to
1494/// create it (this occurs when we see a definition of the function).
1495llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1496                                                 llvm::Type *Ty,
1497                                                 bool ForVTable) {
1498  // If there was no specific requested type, just convert it now.
1499  if (!Ty)
1500    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1501
1502  StringRef MangledName = getMangledName(GD);
1503  return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1504}
1505
1506/// CreateRuntimeFunction - Create a new runtime function with the specified
1507/// type and name.
1508llvm::Constant *
1509CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1510                                     StringRef Name,
1511                                     llvm::AttributeSet ExtraAttrs) {
1512  llvm::Constant *C
1513    = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1514                              ExtraAttrs);
1515  if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1516    if (F->empty())
1517      F->setCallingConv(getRuntimeCC());
1518  return C;
1519}
1520
1521/// isTypeConstant - Determine whether an object of this type can be emitted
1522/// as a constant.
1523///
1524/// If ExcludeCtor is true, the duration when the object's constructor runs
1525/// will not be considered. The caller will need to verify that the object is
1526/// not written to during its construction.
1527bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1528  if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1529    return false;
1530
1531  if (Context.getLangOpts().CPlusPlus) {
1532    if (const CXXRecordDecl *Record
1533          = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1534      return ExcludeCtor && !Record->hasMutableFields() &&
1535             Record->hasTrivialDestructor();
1536  }
1537
1538  return true;
1539}
1540
1541/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1542/// create and return an llvm GlobalVariable with the specified type.  If there
1543/// is something in the module with the specified name, return it potentially
1544/// bitcasted to the right type.
1545///
1546/// If D is non-null, it specifies a decl that correspond to this.  This is used
1547/// to set the attributes on the global when it is first created.
1548llvm::Constant *
1549CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1550                                     llvm::PointerType *Ty,
1551                                     const VarDecl *D,
1552                                     bool UnnamedAddr) {
1553  // Lookup the entry, lazily creating it if necessary.
1554  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1555  if (Entry) {
1556    if (WeakRefReferences.erase(Entry)) {
1557      if (D && !D->hasAttr<WeakAttr>())
1558        Entry->setLinkage(llvm::Function::ExternalLinkage);
1559    }
1560
1561    if (UnnamedAddr)
1562      Entry->setUnnamedAddr(true);
1563
1564    if (Entry->getType() == Ty)
1565      return Entry;
1566
1567    // Make sure the result is of the correct type.
1568    if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1569      return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1570
1571    return llvm::ConstantExpr::getBitCast(Entry, Ty);
1572  }
1573
1574  // This is the first use or definition of a mangled name.  If there is a
1575  // deferred decl with this name, remember that we need to emit it at the end
1576  // of the file.
1577  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1578  if (DDI != DeferredDecls.end()) {
1579    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1580    // list, and remove it from DeferredDecls (since we don't need it anymore).
1581    DeferredDeclsToEmit.push_back(DDI->second);
1582    DeferredDecls.erase(DDI);
1583  }
1584
1585  unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1586  llvm::GlobalVariable *GV =
1587    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1588                             llvm::GlobalValue::ExternalLinkage,
1589                             0, MangledName, 0,
1590                             llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1591
1592  // Handle things which are present even on external declarations.
1593  if (D) {
1594    // FIXME: This code is overly simple and should be merged with other global
1595    // handling.
1596    GV->setConstant(isTypeConstant(D->getType(), false));
1597
1598    // Set linkage and visibility in case we never see a definition.
1599    LinkageInfo LV = D->getLinkageAndVisibility();
1600    if (LV.getLinkage() != ExternalLinkage) {
1601      // Don't set internal linkage on declarations.
1602    } else {
1603      if (D->hasAttr<DLLImportAttr>())
1604        GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1605      else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1606        GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1607
1608      // Set visibility on a declaration only if it's explicit.
1609      if (LV.isVisibilityExplicit())
1610        GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1611    }
1612
1613    if (D->getTLSKind()) {
1614      if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1615        CXXThreadLocals.push_back(std::make_pair(D, GV));
1616      setTLSMode(GV, *D);
1617    }
1618
1619    // If required by the ABI, treat declarations of static data members with
1620    // inline initializers as definitions.
1621    if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1622        D->isStaticDataMember() && D->hasInit() &&
1623        !D->isThisDeclarationADefinition())
1624      EmitGlobalVarDefinition(D);
1625  }
1626
1627  if (AddrSpace != Ty->getAddressSpace())
1628    return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1629
1630  return GV;
1631}
1632
1633
1634llvm::GlobalVariable *
1635CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1636                                      llvm::Type *Ty,
1637                                      llvm::GlobalValue::LinkageTypes Linkage) {
1638  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1639  llvm::GlobalVariable *OldGV = 0;
1640
1641
1642  if (GV) {
1643    // Check if the variable has the right type.
1644    if (GV->getType()->getElementType() == Ty)
1645      return GV;
1646
1647    // Because C++ name mangling, the only way we can end up with an already
1648    // existing global with the same name is if it has been declared extern "C".
1649    assert(GV->isDeclaration() && "Declaration has wrong type!");
1650    OldGV = GV;
1651  }
1652
1653  // Create a new variable.
1654  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1655                                Linkage, 0, Name);
1656
1657  if (OldGV) {
1658    // Replace occurrences of the old variable if needed.
1659    GV->takeName(OldGV);
1660
1661    if (!OldGV->use_empty()) {
1662      llvm::Constant *NewPtrForOldDecl =
1663      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1664      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1665    }
1666
1667    OldGV->eraseFromParent();
1668  }
1669
1670  return GV;
1671}
1672
1673/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1674/// given global variable.  If Ty is non-null and if the global doesn't exist,
1675/// then it will be created with the specified type instead of whatever the
1676/// normal requested type would be.
1677llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1678                                                  llvm::Type *Ty) {
1679  assert(D->hasGlobalStorage() && "Not a global variable");
1680  QualType ASTTy = D->getType();
1681  if (Ty == 0)
1682    Ty = getTypes().ConvertTypeForMem(ASTTy);
1683
1684  llvm::PointerType *PTy =
1685    llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1686
1687  StringRef MangledName = getMangledName(D);
1688  return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1689}
1690
1691/// CreateRuntimeVariable - Create a new runtime global variable with the
1692/// specified type and name.
1693llvm::Constant *
1694CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1695                                     StringRef Name) {
1696  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1697                               true);
1698}
1699
1700void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1701  assert(!D->getInit() && "Cannot emit definite definitions here!");
1702
1703  if (MayDeferGeneration(D)) {
1704    // If we have not seen a reference to this variable yet, place it
1705    // into the deferred declarations table to be emitted if needed
1706    // later.
1707    StringRef MangledName = getMangledName(D);
1708    if (!GetGlobalValue(MangledName)) {
1709      DeferredDecls[MangledName] = D;
1710      return;
1711    }
1712  }
1713
1714  // The tentative definition is the only definition.
1715  EmitGlobalVarDefinition(D);
1716}
1717
1718CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1719    return Context.toCharUnitsFromBits(
1720      TheDataLayout.getTypeStoreSizeInBits(Ty));
1721}
1722
1723unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1724                                                 unsigned AddrSpace) {
1725  if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1726    if (D->hasAttr<CUDAConstantAttr>())
1727      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1728    else if (D->hasAttr<CUDASharedAttr>())
1729      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1730    else
1731      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1732  }
1733
1734  return AddrSpace;
1735}
1736
1737template<typename SomeDecl>
1738void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1739                                               llvm::GlobalValue *GV) {
1740  if (!getLangOpts().CPlusPlus)
1741    return;
1742
1743  // Must have 'used' attribute, or else inline assembly can't rely on
1744  // the name existing.
1745  if (!D->template hasAttr<UsedAttr>())
1746    return;
1747
1748  // Must have internal linkage and an ordinary name.
1749  if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1750    return;
1751
1752  // Must be in an extern "C" context. Entities declared directly within
1753  // a record are not extern "C" even if the record is in such a context.
1754  const SomeDecl *First = D->getFirstDecl();
1755  if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1756    return;
1757
1758  // OK, this is an internal linkage entity inside an extern "C" linkage
1759  // specification. Make a note of that so we can give it the "expected"
1760  // mangled name if nothing else is using that name.
1761  std::pair<StaticExternCMap::iterator, bool> R =
1762      StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1763
1764  // If we have multiple internal linkage entities with the same name
1765  // in extern "C" regions, none of them gets that name.
1766  if (!R.second)
1767    R.first->second = 0;
1768}
1769
1770void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1771  llvm::Constant *Init = 0;
1772  QualType ASTTy = D->getType();
1773  CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1774  bool NeedsGlobalCtor = false;
1775  bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1776
1777  const VarDecl *InitDecl;
1778  const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1779
1780  if (!InitExpr) {
1781    // This is a tentative definition; tentative definitions are
1782    // implicitly initialized with { 0 }.
1783    //
1784    // Note that tentative definitions are only emitted at the end of
1785    // a translation unit, so they should never have incomplete
1786    // type. In addition, EmitTentativeDefinition makes sure that we
1787    // never attempt to emit a tentative definition if a real one
1788    // exists. A use may still exists, however, so we still may need
1789    // to do a RAUW.
1790    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1791    Init = EmitNullConstant(D->getType());
1792  } else {
1793    initializedGlobalDecl = GlobalDecl(D);
1794    Init = EmitConstantInit(*InitDecl);
1795
1796    if (!Init) {
1797      QualType T = InitExpr->getType();
1798      if (D->getType()->isReferenceType())
1799        T = D->getType();
1800
1801      if (getLangOpts().CPlusPlus) {
1802        Init = EmitNullConstant(T);
1803        NeedsGlobalCtor = true;
1804      } else {
1805        ErrorUnsupported(D, "static initializer");
1806        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1807      }
1808    } else {
1809      // We don't need an initializer, so remove the entry for the delayed
1810      // initializer position (just in case this entry was delayed) if we
1811      // also don't need to register a destructor.
1812      if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1813        DelayedCXXInitPosition.erase(D);
1814    }
1815  }
1816
1817  llvm::Type* InitType = Init->getType();
1818  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1819
1820  // Strip off a bitcast if we got one back.
1821  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1822    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1823           CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1824           // All zero index gep.
1825           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1826    Entry = CE->getOperand(0);
1827  }
1828
1829  // Entry is now either a Function or GlobalVariable.
1830  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1831
1832  // We have a definition after a declaration with the wrong type.
1833  // We must make a new GlobalVariable* and update everything that used OldGV
1834  // (a declaration or tentative definition) with the new GlobalVariable*
1835  // (which will be a definition).
1836  //
1837  // This happens if there is a prototype for a global (e.g.
1838  // "extern int x[];") and then a definition of a different type (e.g.
1839  // "int x[10];"). This also happens when an initializer has a different type
1840  // from the type of the global (this happens with unions).
1841  if (GV == 0 ||
1842      GV->getType()->getElementType() != InitType ||
1843      GV->getType()->getAddressSpace() !=
1844       GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1845
1846    // Move the old entry aside so that we'll create a new one.
1847    Entry->setName(StringRef());
1848
1849    // Make a new global with the correct type, this is now guaranteed to work.
1850    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1851
1852    // Replace all uses of the old global with the new global
1853    llvm::Constant *NewPtrForOldDecl =
1854        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1855    Entry->replaceAllUsesWith(NewPtrForOldDecl);
1856
1857    // Erase the old global, since it is no longer used.
1858    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1859  }
1860
1861  MaybeHandleStaticInExternC(D, GV);
1862
1863  if (D->hasAttr<AnnotateAttr>())
1864    AddGlobalAnnotations(D, GV);
1865
1866  GV->setInitializer(Init);
1867
1868  // If it is safe to mark the global 'constant', do so now.
1869  GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1870                  isTypeConstant(D->getType(), true));
1871
1872  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1873
1874  // Set the llvm linkage type as appropriate.
1875  llvm::GlobalValue::LinkageTypes Linkage =
1876    GetLLVMLinkageVarDefinition(D, GV->isConstant());
1877  GV->setLinkage(Linkage);
1878
1879  // If required by the ABI, give definitions of static data members with inline
1880  // initializers linkonce_odr linkage.
1881  if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1882      D->isStaticDataMember() && InitExpr &&
1883      !InitDecl->isThisDeclarationADefinition())
1884    GV->setLinkage(llvm::GlobalVariable::LinkOnceODRLinkage);
1885
1886  if (Linkage == llvm::GlobalVariable::CommonLinkage)
1887    // common vars aren't constant even if declared const.
1888    GV->setConstant(false);
1889
1890  SetCommonAttributes(D, GV);
1891
1892  // Emit the initializer function if necessary.
1893  if (NeedsGlobalCtor || NeedsGlobalDtor)
1894    EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1895
1896  // If we are compiling with ASan, add metadata indicating dynamically
1897  // initialized globals.
1898  if (SanOpts.Address && NeedsGlobalCtor) {
1899    llvm::Module &M = getModule();
1900
1901    llvm::NamedMDNode *DynamicInitializers =
1902        M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1903    llvm::Value *GlobalToAdd[] = { GV };
1904    llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1905    DynamicInitializers->addOperand(ThisGlobal);
1906  }
1907
1908  // Emit global variable debug information.
1909  if (CGDebugInfo *DI = getModuleDebugInfo())
1910    if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1911      DI->EmitGlobalVariable(GV, D);
1912}
1913
1914llvm::GlobalValue::LinkageTypes
1915CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) {
1916  GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1917  if (Linkage == GVA_Internal)
1918    return llvm::Function::InternalLinkage;
1919  else if (D->hasAttr<DLLImportAttr>())
1920    return llvm::Function::DLLImportLinkage;
1921  else if (D->hasAttr<DLLExportAttr>())
1922    return llvm::Function::DLLExportLinkage;
1923  else if (D->hasAttr<SelectAnyAttr>()) {
1924    // selectany symbols are externally visible, so use weak instead of
1925    // linkonce.  MSVC optimizes away references to const selectany globals, so
1926    // all definitions should be the same and ODR linkage should be used.
1927    // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
1928    return llvm::GlobalVariable::WeakODRLinkage;
1929  } else if (D->hasAttr<WeakAttr>()) {
1930    if (isConstant)
1931      return llvm::GlobalVariable::WeakODRLinkage;
1932    else
1933      return llvm::GlobalVariable::WeakAnyLinkage;
1934  } else if (Linkage == GVA_TemplateInstantiation ||
1935             Linkage == GVA_ExplicitTemplateInstantiation)
1936    return llvm::GlobalVariable::WeakODRLinkage;
1937  else if (!getLangOpts().CPlusPlus &&
1938           ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1939             D->getAttr<CommonAttr>()) &&
1940           !D->hasExternalStorage() && !D->getInit() &&
1941           !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
1942           !D->getAttr<WeakImportAttr>()) {
1943    // Thread local vars aren't considered common linkage.
1944    return llvm::GlobalVariable::CommonLinkage;
1945  } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1946             getTarget().getTriple().isMacOSX())
1947    // On Darwin, the backing variable for a C++11 thread_local variable always
1948    // has internal linkage; all accesses should just be calls to the
1949    // Itanium-specified entry point, which has the normal linkage of the
1950    // variable.
1951    return llvm::GlobalValue::InternalLinkage;
1952  return llvm::GlobalVariable::ExternalLinkage;
1953}
1954
1955/// Replace the uses of a function that was declared with a non-proto type.
1956/// We want to silently drop extra arguments from call sites
1957static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1958                                          llvm::Function *newFn) {
1959  // Fast path.
1960  if (old->use_empty()) return;
1961
1962  llvm::Type *newRetTy = newFn->getReturnType();
1963  SmallVector<llvm::Value*, 4> newArgs;
1964
1965  for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1966         ui != ue; ) {
1967    llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1968    llvm::User *user = *use;
1969
1970    // Recognize and replace uses of bitcasts.  Most calls to
1971    // unprototyped functions will use bitcasts.
1972    if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1973      if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1974        replaceUsesOfNonProtoConstant(bitcast, newFn);
1975      continue;
1976    }
1977
1978    // Recognize calls to the function.
1979    llvm::CallSite callSite(user);
1980    if (!callSite) continue;
1981    if (!callSite.isCallee(use)) continue;
1982
1983    // If the return types don't match exactly, then we can't
1984    // transform this call unless it's dead.
1985    if (callSite->getType() != newRetTy && !callSite->use_empty())
1986      continue;
1987
1988    // Get the call site's attribute list.
1989    SmallVector<llvm::AttributeSet, 8> newAttrs;
1990    llvm::AttributeSet oldAttrs = callSite.getAttributes();
1991
1992    // Collect any return attributes from the call.
1993    if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
1994      newAttrs.push_back(
1995        llvm::AttributeSet::get(newFn->getContext(),
1996                                oldAttrs.getRetAttributes()));
1997
1998    // If the function was passed too few arguments, don't transform.
1999    unsigned newNumArgs = newFn->arg_size();
2000    if (callSite.arg_size() < newNumArgs) continue;
2001
2002    // If extra arguments were passed, we silently drop them.
2003    // If any of the types mismatch, we don't transform.
2004    unsigned argNo = 0;
2005    bool dontTransform = false;
2006    for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2007           ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2008      if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2009        dontTransform = true;
2010        break;
2011      }
2012
2013      // Add any parameter attributes.
2014      if (oldAttrs.hasAttributes(argNo + 1))
2015        newAttrs.
2016          push_back(llvm::
2017                    AttributeSet::get(newFn->getContext(),
2018                                      oldAttrs.getParamAttributes(argNo + 1)));
2019    }
2020    if (dontTransform)
2021      continue;
2022
2023    if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2024      newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2025                                                 oldAttrs.getFnAttributes()));
2026
2027    // Okay, we can transform this.  Create the new call instruction and copy
2028    // over the required information.
2029    newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2030
2031    llvm::CallSite newCall;
2032    if (callSite.isCall()) {
2033      newCall = llvm::CallInst::Create(newFn, newArgs, "",
2034                                       callSite.getInstruction());
2035    } else {
2036      llvm::InvokeInst *oldInvoke =
2037        cast<llvm::InvokeInst>(callSite.getInstruction());
2038      newCall = llvm::InvokeInst::Create(newFn,
2039                                         oldInvoke->getNormalDest(),
2040                                         oldInvoke->getUnwindDest(),
2041                                         newArgs, "",
2042                                         callSite.getInstruction());
2043    }
2044    newArgs.clear(); // for the next iteration
2045
2046    if (!newCall->getType()->isVoidTy())
2047      newCall->takeName(callSite.getInstruction());
2048    newCall.setAttributes(
2049                     llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2050    newCall.setCallingConv(callSite.getCallingConv());
2051
2052    // Finally, remove the old call, replacing any uses with the new one.
2053    if (!callSite->use_empty())
2054      callSite->replaceAllUsesWith(newCall.getInstruction());
2055
2056    // Copy debug location attached to CI.
2057    if (!callSite->getDebugLoc().isUnknown())
2058      newCall->setDebugLoc(callSite->getDebugLoc());
2059    callSite->eraseFromParent();
2060  }
2061}
2062
2063/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2064/// implement a function with no prototype, e.g. "int foo() {}".  If there are
2065/// existing call uses of the old function in the module, this adjusts them to
2066/// call the new function directly.
2067///
2068/// This is not just a cleanup: the always_inline pass requires direct calls to
2069/// functions to be able to inline them.  If there is a bitcast in the way, it
2070/// won't inline them.  Instcombine normally deletes these calls, but it isn't
2071/// run at -O0.
2072static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2073                                                      llvm::Function *NewFn) {
2074  // If we're redefining a global as a function, don't transform it.
2075  if (!isa<llvm::Function>(Old)) return;
2076
2077  replaceUsesOfNonProtoConstant(Old, NewFn);
2078}
2079
2080void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2081  TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2082  // If we have a definition, this might be a deferred decl. If the
2083  // instantiation is explicit, make sure we emit it at the end.
2084  if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2085    GetAddrOfGlobalVar(VD);
2086
2087  EmitTopLevelDecl(VD);
2088}
2089
2090void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
2091  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2092
2093  // Compute the function info and LLVM type.
2094  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2095  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2096
2097  // Get or create the prototype for the function.
2098  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
2099
2100  // Strip off a bitcast if we got one back.
2101  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2102    assert(CE->getOpcode() == llvm::Instruction::BitCast);
2103    Entry = CE->getOperand(0);
2104  }
2105
2106  if (!cast<llvm::GlobalValue>(Entry)->isDeclaration()) {
2107    getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2108    return;
2109  }
2110
2111  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2112    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
2113
2114    // If the types mismatch then we have to rewrite the definition.
2115    assert(OldFn->isDeclaration() &&
2116           "Shouldn't replace non-declaration");
2117
2118    // F is the Function* for the one with the wrong type, we must make a new
2119    // Function* and update everything that used F (a declaration) with the new
2120    // Function* (which will be a definition).
2121    //
2122    // This happens if there is a prototype for a function
2123    // (e.g. "int f()") and then a definition of a different type
2124    // (e.g. "int f(int x)").  Move the old function aside so that it
2125    // doesn't interfere with GetAddrOfFunction.
2126    OldFn->setName(StringRef());
2127    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2128
2129    // This might be an implementation of a function without a
2130    // prototype, in which case, try to do special replacement of
2131    // calls which match the new prototype.  The really key thing here
2132    // is that we also potentially drop arguments from the call site
2133    // so as to make a direct call, which makes the inliner happier
2134    // and suppresses a number of optimizer warnings (!) about
2135    // dropping arguments.
2136    if (!OldFn->use_empty()) {
2137      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
2138      OldFn->removeDeadConstantUsers();
2139    }
2140
2141    // Replace uses of F with the Function we will endow with a body.
2142    if (!Entry->use_empty()) {
2143      llvm::Constant *NewPtrForOldDecl =
2144        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2145      Entry->replaceAllUsesWith(NewPtrForOldDecl);
2146    }
2147
2148    // Ok, delete the old function now, which is dead.
2149    OldFn->eraseFromParent();
2150
2151    Entry = NewFn;
2152  }
2153
2154  // We need to set linkage and visibility on the function before
2155  // generating code for it because various parts of IR generation
2156  // want to propagate this information down (e.g. to local static
2157  // declarations).
2158  llvm::Function *Fn = cast<llvm::Function>(Entry);
2159  setFunctionLinkage(GD, Fn);
2160
2161  // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
2162  setGlobalVisibility(Fn, D);
2163
2164  MaybeHandleStaticInExternC(D, Fn);
2165
2166  CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2167
2168  SetFunctionDefinitionAttributes(D, Fn);
2169  SetLLVMFunctionAttributesForDefinition(D, Fn);
2170
2171  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2172    AddGlobalCtor(Fn, CA->getPriority());
2173  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2174    AddGlobalDtor(Fn, DA->getPriority());
2175  if (D->hasAttr<AnnotateAttr>())
2176    AddGlobalAnnotations(D, Fn);
2177}
2178
2179void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2180  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
2181  const AliasAttr *AA = D->getAttr<AliasAttr>();
2182  assert(AA && "Not an alias?");
2183
2184  StringRef MangledName = getMangledName(GD);
2185
2186  // If there is a definition in the module, then it wins over the alias.
2187  // This is dubious, but allow it to be safe.  Just ignore the alias.
2188  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2189  if (Entry && !Entry->isDeclaration())
2190    return;
2191
2192  Aliases.push_back(GD);
2193
2194  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2195
2196  // Create a reference to the named value.  This ensures that it is emitted
2197  // if a deferred decl.
2198  llvm::Constant *Aliasee;
2199  if (isa<llvm::FunctionType>(DeclTy))
2200    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2201                                      /*ForVTable=*/false);
2202  else
2203    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2204                                    llvm::PointerType::getUnqual(DeclTy), 0);
2205
2206  // Create the new alias itself, but don't set a name yet.
2207  llvm::GlobalValue *GA =
2208    new llvm::GlobalAlias(Aliasee->getType(),
2209                          llvm::Function::ExternalLinkage,
2210                          "", Aliasee, &getModule());
2211
2212  if (Entry) {
2213    assert(Entry->isDeclaration());
2214
2215    // If there is a declaration in the module, then we had an extern followed
2216    // by the alias, as in:
2217    //   extern int test6();
2218    //   ...
2219    //   int test6() __attribute__((alias("test7")));
2220    //
2221    // Remove it and replace uses of it with the alias.
2222    GA->takeName(Entry);
2223
2224    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2225                                                          Entry->getType()));
2226    Entry->eraseFromParent();
2227  } else {
2228    GA->setName(MangledName);
2229  }
2230
2231  // Set attributes which are particular to an alias; this is a
2232  // specialization of the attributes which may be set on a global
2233  // variable/function.
2234  if (D->hasAttr<DLLExportAttr>()) {
2235    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2236      // The dllexport attribute is ignored for undefined symbols.
2237      if (FD->hasBody())
2238        GA->setLinkage(llvm::Function::DLLExportLinkage);
2239    } else {
2240      GA->setLinkage(llvm::Function::DLLExportLinkage);
2241    }
2242  } else if (D->hasAttr<WeakAttr>() ||
2243             D->hasAttr<WeakRefAttr>() ||
2244             D->isWeakImported()) {
2245    GA->setLinkage(llvm::Function::WeakAnyLinkage);
2246  }
2247
2248  SetCommonAttributes(D, GA);
2249}
2250
2251llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2252                                            ArrayRef<llvm::Type*> Tys) {
2253  return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2254                                         Tys);
2255}
2256
2257static llvm::StringMapEntry<llvm::Constant*> &
2258GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2259                         const StringLiteral *Literal,
2260                         bool TargetIsLSB,
2261                         bool &IsUTF16,
2262                         unsigned &StringLength) {
2263  StringRef String = Literal->getString();
2264  unsigned NumBytes = String.size();
2265
2266  // Check for simple case.
2267  if (!Literal->containsNonAsciiOrNull()) {
2268    StringLength = NumBytes;
2269    return Map.GetOrCreateValue(String);
2270  }
2271
2272  // Otherwise, convert the UTF8 literals into a string of shorts.
2273  IsUTF16 = true;
2274
2275  SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2276  const UTF8 *FromPtr = (const UTF8 *)String.data();
2277  UTF16 *ToPtr = &ToBuf[0];
2278
2279  (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2280                           &ToPtr, ToPtr + NumBytes,
2281                           strictConversion);
2282
2283  // ConvertUTF8toUTF16 returns the length in ToPtr.
2284  StringLength = ToPtr - &ToBuf[0];
2285
2286  // Add an explicit null.
2287  *ToPtr = 0;
2288  return Map.
2289    GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2290                               (StringLength + 1) * 2));
2291}
2292
2293static llvm::StringMapEntry<llvm::Constant*> &
2294GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2295                       const StringLiteral *Literal,
2296                       unsigned &StringLength) {
2297  StringRef String = Literal->getString();
2298  StringLength = String.size();
2299  return Map.GetOrCreateValue(String);
2300}
2301
2302llvm::Constant *
2303CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2304  unsigned StringLength = 0;
2305  bool isUTF16 = false;
2306  llvm::StringMapEntry<llvm::Constant*> &Entry =
2307    GetConstantCFStringEntry(CFConstantStringMap, Literal,
2308                             getDataLayout().isLittleEndian(),
2309                             isUTF16, StringLength);
2310
2311  if (llvm::Constant *C = Entry.getValue())
2312    return C;
2313
2314  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2315  llvm::Constant *Zeros[] = { Zero, Zero };
2316  llvm::Value *V;
2317
2318  // If we don't already have it, get __CFConstantStringClassReference.
2319  if (!CFConstantStringClassRef) {
2320    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2321    Ty = llvm::ArrayType::get(Ty, 0);
2322    llvm::Constant *GV = CreateRuntimeVariable(Ty,
2323                                           "__CFConstantStringClassReference");
2324    // Decay array -> ptr
2325    V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2326    CFConstantStringClassRef = V;
2327  }
2328  else
2329    V = CFConstantStringClassRef;
2330
2331  QualType CFTy = getContext().getCFConstantStringType();
2332
2333  llvm::StructType *STy =
2334    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2335
2336  llvm::Constant *Fields[4];
2337
2338  // Class pointer.
2339  Fields[0] = cast<llvm::ConstantExpr>(V);
2340
2341  // Flags.
2342  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2343  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2344    llvm::ConstantInt::get(Ty, 0x07C8);
2345
2346  // String pointer.
2347  llvm::Constant *C = 0;
2348  if (isUTF16) {
2349    ArrayRef<uint16_t> Arr =
2350      llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2351                                     const_cast<char *>(Entry.getKey().data())),
2352                                   Entry.getKey().size() / 2);
2353    C = llvm::ConstantDataArray::get(VMContext, Arr);
2354  } else {
2355    C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2356  }
2357
2358  llvm::GlobalValue::LinkageTypes Linkage;
2359  if (isUTF16)
2360    // FIXME: why do utf strings get "_" labels instead of "L" labels?
2361    Linkage = llvm::GlobalValue::InternalLinkage;
2362  else
2363    // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2364    // when using private linkage. It is not clear if this is a bug in ld
2365    // or a reasonable new restriction.
2366    Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2367
2368  // Note: -fwritable-strings doesn't make the backing store strings of
2369  // CFStrings writable. (See <rdar://problem/10657500>)
2370  llvm::GlobalVariable *GV =
2371    new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2372                             Linkage, C, ".str");
2373  GV->setUnnamedAddr(true);
2374  // Don't enforce the target's minimum global alignment, since the only use
2375  // of the string is via this class initializer.
2376  if (isUTF16) {
2377    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2378    GV->setAlignment(Align.getQuantity());
2379  } else {
2380    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2381    GV->setAlignment(Align.getQuantity());
2382  }
2383
2384  // String.
2385  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2386
2387  if (isUTF16)
2388    // Cast the UTF16 string to the correct type.
2389    Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2390
2391  // String length.
2392  Ty = getTypes().ConvertType(getContext().LongTy);
2393  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2394
2395  // The struct.
2396  C = llvm::ConstantStruct::get(STy, Fields);
2397  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2398                                llvm::GlobalVariable::PrivateLinkage, C,
2399                                "_unnamed_cfstring_");
2400  if (const char *Sect = getTarget().getCFStringSection())
2401    GV->setSection(Sect);
2402  Entry.setValue(GV);
2403
2404  return GV;
2405}
2406
2407static RecordDecl *
2408CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2409                 DeclContext *DC, IdentifierInfo *Id) {
2410  SourceLocation Loc;
2411  if (Ctx.getLangOpts().CPlusPlus)
2412    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2413  else
2414    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2415}
2416
2417llvm::Constant *
2418CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2419  unsigned StringLength = 0;
2420  llvm::StringMapEntry<llvm::Constant*> &Entry =
2421    GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2422
2423  if (llvm::Constant *C = Entry.getValue())
2424    return C;
2425
2426  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2427  llvm::Constant *Zeros[] = { Zero, Zero };
2428  llvm::Value *V;
2429  // If we don't already have it, get _NSConstantStringClassReference.
2430  if (!ConstantStringClassRef) {
2431    std::string StringClass(getLangOpts().ObjCConstantStringClass);
2432    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2433    llvm::Constant *GV;
2434    if (LangOpts.ObjCRuntime.isNonFragile()) {
2435      std::string str =
2436        StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2437                            : "OBJC_CLASS_$_" + StringClass;
2438      GV = getObjCRuntime().GetClassGlobal(str);
2439      // Make sure the result is of the correct type.
2440      llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2441      V = llvm::ConstantExpr::getBitCast(GV, PTy);
2442      ConstantStringClassRef = V;
2443    } else {
2444      std::string str =
2445        StringClass.empty() ? "_NSConstantStringClassReference"
2446                            : "_" + StringClass + "ClassReference";
2447      llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2448      GV = CreateRuntimeVariable(PTy, str);
2449      // Decay array -> ptr
2450      V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2451      ConstantStringClassRef = V;
2452    }
2453  }
2454  else
2455    V = ConstantStringClassRef;
2456
2457  if (!NSConstantStringType) {
2458    // Construct the type for a constant NSString.
2459    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2460                                     Context.getTranslationUnitDecl(),
2461                                   &Context.Idents.get("__builtin_NSString"));
2462    D->startDefinition();
2463
2464    QualType FieldTypes[3];
2465
2466    // const int *isa;
2467    FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2468    // const char *str;
2469    FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2470    // unsigned int length;
2471    FieldTypes[2] = Context.UnsignedIntTy;
2472
2473    // Create fields
2474    for (unsigned i = 0; i < 3; ++i) {
2475      FieldDecl *Field = FieldDecl::Create(Context, D,
2476                                           SourceLocation(),
2477                                           SourceLocation(), 0,
2478                                           FieldTypes[i], /*TInfo=*/0,
2479                                           /*BitWidth=*/0,
2480                                           /*Mutable=*/false,
2481                                           ICIS_NoInit);
2482      Field->setAccess(AS_public);
2483      D->addDecl(Field);
2484    }
2485
2486    D->completeDefinition();
2487    QualType NSTy = Context.getTagDeclType(D);
2488    NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2489  }
2490
2491  llvm::Constant *Fields[3];
2492
2493  // Class pointer.
2494  Fields[0] = cast<llvm::ConstantExpr>(V);
2495
2496  // String pointer.
2497  llvm::Constant *C =
2498    llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2499
2500  llvm::GlobalValue::LinkageTypes Linkage;
2501  bool isConstant;
2502  Linkage = llvm::GlobalValue::PrivateLinkage;
2503  isConstant = !LangOpts.WritableStrings;
2504
2505  llvm::GlobalVariable *GV =
2506  new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2507                           ".str");
2508  GV->setUnnamedAddr(true);
2509  // Don't enforce the target's minimum global alignment, since the only use
2510  // of the string is via this class initializer.
2511  CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2512  GV->setAlignment(Align.getQuantity());
2513  Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2514
2515  // String length.
2516  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2517  Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2518
2519  // The struct.
2520  C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2521  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2522                                llvm::GlobalVariable::PrivateLinkage, C,
2523                                "_unnamed_nsstring_");
2524  // FIXME. Fix section.
2525  if (const char *Sect =
2526        LangOpts.ObjCRuntime.isNonFragile()
2527          ? getTarget().getNSStringNonFragileABISection()
2528          : getTarget().getNSStringSection())
2529    GV->setSection(Sect);
2530  Entry.setValue(GV);
2531
2532  return GV;
2533}
2534
2535QualType CodeGenModule::getObjCFastEnumerationStateType() {
2536  if (ObjCFastEnumerationStateType.isNull()) {
2537    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2538                                     Context.getTranslationUnitDecl(),
2539                      &Context.Idents.get("__objcFastEnumerationState"));
2540    D->startDefinition();
2541
2542    QualType FieldTypes[] = {
2543      Context.UnsignedLongTy,
2544      Context.getPointerType(Context.getObjCIdType()),
2545      Context.getPointerType(Context.UnsignedLongTy),
2546      Context.getConstantArrayType(Context.UnsignedLongTy,
2547                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2548    };
2549
2550    for (size_t i = 0; i < 4; ++i) {
2551      FieldDecl *Field = FieldDecl::Create(Context,
2552                                           D,
2553                                           SourceLocation(),
2554                                           SourceLocation(), 0,
2555                                           FieldTypes[i], /*TInfo=*/0,
2556                                           /*BitWidth=*/0,
2557                                           /*Mutable=*/false,
2558                                           ICIS_NoInit);
2559      Field->setAccess(AS_public);
2560      D->addDecl(Field);
2561    }
2562
2563    D->completeDefinition();
2564    ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2565  }
2566
2567  return ObjCFastEnumerationStateType;
2568}
2569
2570llvm::Constant *
2571CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2572  assert(!E->getType()->isPointerType() && "Strings are always arrays");
2573
2574  // Don't emit it as the address of the string, emit the string data itself
2575  // as an inline array.
2576  if (E->getCharByteWidth() == 1) {
2577    SmallString<64> Str(E->getString());
2578
2579    // Resize the string to the right size, which is indicated by its type.
2580    const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2581    Str.resize(CAT->getSize().getZExtValue());
2582    return llvm::ConstantDataArray::getString(VMContext, Str, false);
2583  }
2584
2585  llvm::ArrayType *AType =
2586    cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2587  llvm::Type *ElemTy = AType->getElementType();
2588  unsigned NumElements = AType->getNumElements();
2589
2590  // Wide strings have either 2-byte or 4-byte elements.
2591  if (ElemTy->getPrimitiveSizeInBits() == 16) {
2592    SmallVector<uint16_t, 32> Elements;
2593    Elements.reserve(NumElements);
2594
2595    for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2596      Elements.push_back(E->getCodeUnit(i));
2597    Elements.resize(NumElements);
2598    return llvm::ConstantDataArray::get(VMContext, Elements);
2599  }
2600
2601  assert(ElemTy->getPrimitiveSizeInBits() == 32);
2602  SmallVector<uint32_t, 32> Elements;
2603  Elements.reserve(NumElements);
2604
2605  for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2606    Elements.push_back(E->getCodeUnit(i));
2607  Elements.resize(NumElements);
2608  return llvm::ConstantDataArray::get(VMContext, Elements);
2609}
2610
2611/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2612/// constant array for the given string literal.
2613llvm::Constant *
2614CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2615  CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
2616  if (S->isAscii() || S->isUTF8()) {
2617    SmallString<64> Str(S->getString());
2618
2619    // Resize the string to the right size, which is indicated by its type.
2620    const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2621    Str.resize(CAT->getSize().getZExtValue());
2622    return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2623  }
2624
2625  // FIXME: the following does not memoize wide strings.
2626  llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2627  llvm::GlobalVariable *GV =
2628    new llvm::GlobalVariable(getModule(),C->getType(),
2629                             !LangOpts.WritableStrings,
2630                             llvm::GlobalValue::PrivateLinkage,
2631                             C,".str");
2632
2633  GV->setAlignment(Align.getQuantity());
2634  GV->setUnnamedAddr(true);
2635  return GV;
2636}
2637
2638/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2639/// array for the given ObjCEncodeExpr node.
2640llvm::Constant *
2641CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2642  std::string Str;
2643  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2644
2645  return GetAddrOfConstantCString(Str);
2646}
2647
2648
2649/// GenerateWritableString -- Creates storage for a string literal.
2650static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2651                                             bool constant,
2652                                             CodeGenModule &CGM,
2653                                             const char *GlobalName,
2654                                             unsigned Alignment) {
2655  // Create Constant for this string literal. Don't add a '\0'.
2656  llvm::Constant *C =
2657      llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2658
2659  // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
2660  unsigned AddrSpace = 0;
2661  if (CGM.getLangOpts().OpenCL)
2662    AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2663
2664  // Create a global variable for this string
2665  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2666      CGM.getModule(), C->getType(), constant,
2667      llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0,
2668      llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2669  GV->setAlignment(Alignment);
2670  GV->setUnnamedAddr(true);
2671  return GV;
2672}
2673
2674/// GetAddrOfConstantString - Returns a pointer to a character array
2675/// containing the literal. This contents are exactly that of the
2676/// given string, i.e. it will not be null terminated automatically;
2677/// see GetAddrOfConstantCString. Note that whether the result is
2678/// actually a pointer to an LLVM constant depends on
2679/// Feature.WriteableStrings.
2680///
2681/// The result has pointer to array type.
2682llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2683                                                       const char *GlobalName,
2684                                                       unsigned Alignment) {
2685  // Get the default prefix if a name wasn't specified.
2686  if (!GlobalName)
2687    GlobalName = ".str";
2688
2689  if (Alignment == 0)
2690    Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2691      .getQuantity();
2692
2693  // Don't share any string literals if strings aren't constant.
2694  if (LangOpts.WritableStrings)
2695    return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2696
2697  llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2698    ConstantStringMap.GetOrCreateValue(Str);
2699
2700  if (llvm::GlobalVariable *GV = Entry.getValue()) {
2701    if (Alignment > GV->getAlignment()) {
2702      GV->setAlignment(Alignment);
2703    }
2704    return GV;
2705  }
2706
2707  // Create a global variable for this.
2708  llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2709                                                   Alignment);
2710  Entry.setValue(GV);
2711  return GV;
2712}
2713
2714/// GetAddrOfConstantCString - Returns a pointer to a character
2715/// array containing the literal and a terminating '\0'
2716/// character. The result has pointer to array type.
2717llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2718                                                        const char *GlobalName,
2719                                                        unsigned Alignment) {
2720  StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2721  return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2722}
2723
2724llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
2725    const MaterializeTemporaryExpr *E, const Expr *Init) {
2726  assert((E->getStorageDuration() == SD_Static ||
2727          E->getStorageDuration() == SD_Thread) && "not a global temporary");
2728  const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
2729
2730  // If we're not materializing a subobject of the temporary, keep the
2731  // cv-qualifiers from the type of the MaterializeTemporaryExpr.
2732  QualType MaterializedType = Init->getType();
2733  if (Init == E->GetTemporaryExpr())
2734    MaterializedType = E->getType();
2735
2736  llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2737  if (Slot)
2738    return Slot;
2739
2740  // FIXME: If an externally-visible declaration extends multiple temporaries,
2741  // we need to give each temporary the same name in every translation unit (and
2742  // we also need to make the temporaries externally-visible).
2743  SmallString<256> Name;
2744  llvm::raw_svector_ostream Out(Name);
2745  getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
2746  Out.flush();
2747
2748  APValue *Value = 0;
2749  if (E->getStorageDuration() == SD_Static) {
2750    // We might have a cached constant initializer for this temporary. Note
2751    // that this might have a different value from the value computed by
2752    // evaluating the initializer if the surrounding constant expression
2753    // modifies the temporary.
2754    Value = getContext().getMaterializedTemporaryValue(E, false);
2755    if (Value && Value->isUninit())
2756      Value = 0;
2757  }
2758
2759  // Try evaluating it now, it might have a constant initializer.
2760  Expr::EvalResult EvalResult;
2761  if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2762      !EvalResult.hasSideEffects())
2763    Value = &EvalResult.Val;
2764
2765  llvm::Constant *InitialValue = 0;
2766  bool Constant = false;
2767  llvm::Type *Type;
2768  if (Value) {
2769    // The temporary has a constant initializer, use it.
2770    InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
2771    Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2772    Type = InitialValue->getType();
2773  } else {
2774    // No initializer, the initialization will be provided when we
2775    // initialize the declaration which performed lifetime extension.
2776    Type = getTypes().ConvertTypeForMem(MaterializedType);
2777  }
2778
2779  // Create a global variable for this lifetime-extended temporary.
2780  llvm::GlobalVariable *GV =
2781    new llvm::GlobalVariable(getModule(), Type, Constant,
2782                             llvm::GlobalValue::PrivateLinkage,
2783                             InitialValue, Name.c_str());
2784  GV->setAlignment(
2785      getContext().getTypeAlignInChars(MaterializedType).getQuantity());
2786  if (VD->getTLSKind())
2787    setTLSMode(GV, *VD);
2788  Slot = GV;
2789  return GV;
2790}
2791
2792/// EmitObjCPropertyImplementations - Emit information for synthesized
2793/// properties for an implementation.
2794void CodeGenModule::EmitObjCPropertyImplementations(const
2795                                                    ObjCImplementationDecl *D) {
2796  for (ObjCImplementationDecl::propimpl_iterator
2797         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2798    ObjCPropertyImplDecl *PID = *i;
2799
2800    // Dynamic is just for type-checking.
2801    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2802      ObjCPropertyDecl *PD = PID->getPropertyDecl();
2803
2804      // Determine which methods need to be implemented, some may have
2805      // been overridden. Note that ::isPropertyAccessor is not the method
2806      // we want, that just indicates if the decl came from a
2807      // property. What we want to know is if the method is defined in
2808      // this implementation.
2809      if (!D->getInstanceMethod(PD->getGetterName()))
2810        CodeGenFunction(*this).GenerateObjCGetter(
2811                                 const_cast<ObjCImplementationDecl *>(D), PID);
2812      if (!PD->isReadOnly() &&
2813          !D->getInstanceMethod(PD->getSetterName()))
2814        CodeGenFunction(*this).GenerateObjCSetter(
2815                                 const_cast<ObjCImplementationDecl *>(D), PID);
2816    }
2817  }
2818}
2819
2820static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2821  const ObjCInterfaceDecl *iface = impl->getClassInterface();
2822  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2823       ivar; ivar = ivar->getNextIvar())
2824    if (ivar->getType().isDestructedType())
2825      return true;
2826
2827  return false;
2828}
2829
2830/// EmitObjCIvarInitializations - Emit information for ivar initialization
2831/// for an implementation.
2832void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2833  // We might need a .cxx_destruct even if we don't have any ivar initializers.
2834  if (needsDestructMethod(D)) {
2835    IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2836    Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2837    ObjCMethodDecl *DTORMethod =
2838      ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2839                             cxxSelector, getContext().VoidTy, 0, D,
2840                             /*isInstance=*/true, /*isVariadic=*/false,
2841                          /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2842                             /*isDefined=*/false, ObjCMethodDecl::Required);
2843    D->addInstanceMethod(DTORMethod);
2844    CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2845    D->setHasDestructors(true);
2846  }
2847
2848  // If the implementation doesn't have any ivar initializers, we don't need
2849  // a .cxx_construct.
2850  if (D->getNumIvarInitializers() == 0)
2851    return;
2852
2853  IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2854  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2855  // The constructor returns 'self'.
2856  ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2857                                                D->getLocation(),
2858                                                D->getLocation(),
2859                                                cxxSelector,
2860                                                getContext().getObjCIdType(), 0,
2861                                                D, /*isInstance=*/true,
2862                                                /*isVariadic=*/false,
2863                                                /*isPropertyAccessor=*/true,
2864                                                /*isImplicitlyDeclared=*/true,
2865                                                /*isDefined=*/false,
2866                                                ObjCMethodDecl::Required);
2867  D->addInstanceMethod(CTORMethod);
2868  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2869  D->setHasNonZeroConstructors(true);
2870}
2871
2872/// EmitNamespace - Emit all declarations in a namespace.
2873void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2874  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2875       I != E; ++I) {
2876    if (const VarDecl *VD = dyn_cast<VarDecl>(*I))
2877      if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2878          VD->getTemplateSpecializationKind() != TSK_Undeclared)
2879        continue;
2880    EmitTopLevelDecl(*I);
2881  }
2882}
2883
2884// EmitLinkageSpec - Emit all declarations in a linkage spec.
2885void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2886  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2887      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2888    ErrorUnsupported(LSD, "linkage spec");
2889    return;
2890  }
2891
2892  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2893       I != E; ++I) {
2894    // Meta-data for ObjC class includes references to implemented methods.
2895    // Generate class's method definitions first.
2896    if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2897      for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2898           MEnd = OID->meth_end();
2899           M != MEnd; ++M)
2900        EmitTopLevelDecl(*M);
2901    }
2902    EmitTopLevelDecl(*I);
2903  }
2904}
2905
2906/// EmitTopLevelDecl - Emit code for a single top level declaration.
2907void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2908  // Ignore dependent declarations.
2909  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2910    return;
2911
2912  switch (D->getKind()) {
2913  case Decl::CXXConversion:
2914  case Decl::CXXMethod:
2915  case Decl::Function:
2916    // Skip function templates
2917    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2918        cast<FunctionDecl>(D)->isLateTemplateParsed())
2919      return;
2920
2921    EmitGlobal(cast<FunctionDecl>(D));
2922    break;
2923
2924  case Decl::Var:
2925    // Skip variable templates
2926    if (cast<VarDecl>(D)->getDescribedVarTemplate())
2927      return;
2928  case Decl::VarTemplateSpecialization:
2929    EmitGlobal(cast<VarDecl>(D));
2930    break;
2931
2932  // Indirect fields from global anonymous structs and unions can be
2933  // ignored; only the actual variable requires IR gen support.
2934  case Decl::IndirectField:
2935    break;
2936
2937  // C++ Decls
2938  case Decl::Namespace:
2939    EmitNamespace(cast<NamespaceDecl>(D));
2940    break;
2941    // No code generation needed.
2942  case Decl::UsingShadow:
2943  case Decl::Using:
2944  case Decl::ClassTemplate:
2945  case Decl::VarTemplate:
2946  case Decl::VarTemplatePartialSpecialization:
2947  case Decl::FunctionTemplate:
2948  case Decl::TypeAliasTemplate:
2949  case Decl::Block:
2950  case Decl::Empty:
2951    break;
2952  case Decl::NamespaceAlias:
2953    if (CGDebugInfo *DI = getModuleDebugInfo())
2954        DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
2955    return;
2956  case Decl::UsingDirective: // using namespace X; [C++]
2957    if (CGDebugInfo *DI = getModuleDebugInfo())
2958      DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2959    return;
2960  case Decl::CXXConstructor:
2961    // Skip function templates
2962    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2963        cast<FunctionDecl>(D)->isLateTemplateParsed())
2964      return;
2965
2966    getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2967    break;
2968  case Decl::CXXDestructor:
2969    if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2970      return;
2971    getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2972    break;
2973
2974  case Decl::StaticAssert:
2975    // Nothing to do.
2976    break;
2977
2978  // Objective-C Decls
2979
2980  // Forward declarations, no (immediate) code generation.
2981  case Decl::ObjCInterface:
2982  case Decl::ObjCCategory:
2983    break;
2984
2985  case Decl::ObjCProtocol: {
2986    ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2987    if (Proto->isThisDeclarationADefinition())
2988      ObjCRuntime->GenerateProtocol(Proto);
2989    break;
2990  }
2991
2992  case Decl::ObjCCategoryImpl:
2993    // Categories have properties but don't support synthesize so we
2994    // can ignore them here.
2995    ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2996    break;
2997
2998  case Decl::ObjCImplementation: {
2999    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
3000    EmitObjCPropertyImplementations(OMD);
3001    EmitObjCIvarInitializations(OMD);
3002    ObjCRuntime->GenerateClass(OMD);
3003    // Emit global variable debug information.
3004    if (CGDebugInfo *DI = getModuleDebugInfo())
3005      if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3006        DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3007            OMD->getClassInterface()), OMD->getLocation());
3008    break;
3009  }
3010  case Decl::ObjCMethod: {
3011    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
3012    // If this is not a prototype, emit the body.
3013    if (OMD->getBody())
3014      CodeGenFunction(*this).GenerateObjCMethod(OMD);
3015    break;
3016  }
3017  case Decl::ObjCCompatibleAlias:
3018    ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3019    break;
3020
3021  case Decl::LinkageSpec:
3022    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3023    break;
3024
3025  case Decl::FileScopeAsm: {
3026    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
3027    StringRef AsmString = AD->getAsmString()->getString();
3028
3029    const std::string &S = getModule().getModuleInlineAsm();
3030    if (S.empty())
3031      getModule().setModuleInlineAsm(AsmString);
3032    else if (S.end()[-1] == '\n')
3033      getModule().setModuleInlineAsm(S + AsmString.str());
3034    else
3035      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
3036    break;
3037  }
3038
3039  case Decl::Import: {
3040    ImportDecl *Import = cast<ImportDecl>(D);
3041
3042    // Ignore import declarations that come from imported modules.
3043    if (clang::Module *Owner = Import->getOwningModule()) {
3044      if (getLangOpts().CurrentModule.empty() ||
3045          Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3046        break;
3047    }
3048
3049    ImportedModules.insert(Import->getImportedModule());
3050    break;
3051 }
3052
3053  default:
3054    // Make sure we handled everything we should, every other kind is a
3055    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3056    // function. Need to recode Decl::Kind to do that easily.
3057    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3058  }
3059}
3060
3061/// Turns the given pointer into a constant.
3062static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3063                                          const void *Ptr) {
3064  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3065  llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3066  return llvm::ConstantInt::get(i64, PtrInt);
3067}
3068
3069static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3070                                   llvm::NamedMDNode *&GlobalMetadata,
3071                                   GlobalDecl D,
3072                                   llvm::GlobalValue *Addr) {
3073  if (!GlobalMetadata)
3074    GlobalMetadata =
3075      CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3076
3077  // TODO: should we report variant information for ctors/dtors?
3078  llvm::Value *Ops[] = {
3079    Addr,
3080    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3081  };
3082  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3083}
3084
3085/// For each function which is declared within an extern "C" region and marked
3086/// as 'used', but has internal linkage, create an alias from the unmangled
3087/// name to the mangled name if possible. People expect to be able to refer
3088/// to such functions with an unmangled name from inline assembly within the
3089/// same translation unit.
3090void CodeGenModule::EmitStaticExternCAliases() {
3091  for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3092                                  E = StaticExternCValues.end();
3093       I != E; ++I) {
3094    IdentifierInfo *Name = I->first;
3095    llvm::GlobalValue *Val = I->second;
3096    if (Val && !getModule().getNamedValue(Name->getName()))
3097      AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
3098                                          Name->getName(), Val, &getModule()));
3099  }
3100}
3101
3102/// Emits metadata nodes associating all the global values in the
3103/// current module with the Decls they came from.  This is useful for
3104/// projects using IR gen as a subroutine.
3105///
3106/// Since there's currently no way to associate an MDNode directly
3107/// with an llvm::GlobalValue, we create a global named metadata
3108/// with the name 'clang.global.decl.ptrs'.
3109void CodeGenModule::EmitDeclMetadata() {
3110  llvm::NamedMDNode *GlobalMetadata = 0;
3111
3112  // StaticLocalDeclMap
3113  for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
3114         I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3115       I != E; ++I) {
3116    llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3117    EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3118  }
3119}
3120
3121/// Emits metadata nodes for all the local variables in the current
3122/// function.
3123void CodeGenFunction::EmitDeclMetadata() {
3124  if (LocalDeclMap.empty()) return;
3125
3126  llvm::LLVMContext &Context = getLLVMContext();
3127
3128  // Find the unique metadata ID for this name.
3129  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3130
3131  llvm::NamedMDNode *GlobalMetadata = 0;
3132
3133  for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3134         I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3135    const Decl *D = I->first;
3136    llvm::Value *Addr = I->second;
3137
3138    if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3139      llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3140      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3141    } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3142      GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3143      EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3144    }
3145  }
3146}
3147
3148void CodeGenModule::EmitVersionIdentMetadata() {
3149  llvm::NamedMDNode *IdentMetadata =
3150    TheModule.getOrInsertNamedMetadata("llvm.ident");
3151  std::string Version = getClangFullVersion();
3152  llvm::LLVMContext &Ctx = TheModule.getContext();
3153
3154  llvm::Value *IdentNode[] = {
3155    llvm::MDString::get(Ctx, Version)
3156  };
3157  IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3158}
3159
3160void CodeGenModule::EmitCoverageFile() {
3161  if (!getCodeGenOpts().CoverageFile.empty()) {
3162    if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3163      llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3164      llvm::LLVMContext &Ctx = TheModule.getContext();
3165      llvm::MDString *CoverageFile =
3166          llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3167      for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3168        llvm::MDNode *CU = CUNode->getOperand(i);
3169        llvm::Value *node[] = { CoverageFile, CU };
3170        llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3171        GCov->addOperand(N);
3172      }
3173    }
3174  }
3175}
3176
3177llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3178                                                     QualType GuidType) {
3179  // Sema has checked that all uuid strings are of the form
3180  // "12345678-1234-1234-1234-1234567890ab".
3181  assert(Uuid.size() == 36);
3182  for (unsigned i = 0; i < 36; ++i) {
3183    if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3184    else                                         assert(isHexDigit(Uuid[i]));
3185  }
3186
3187  const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3188
3189  llvm::Constant *Field3[8];
3190  for (unsigned Idx = 0; Idx < 8; ++Idx)
3191    Field3[Idx] = llvm::ConstantInt::get(
3192        Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3193
3194  llvm::Constant *Fields[4] = {
3195    llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3196    llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3197    llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3198    llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3199  };
3200
3201  return llvm::ConstantStruct::getAnon(Fields);
3202}
3203