xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision b80bacc89a4d0ede87ed350e8bbeb748b96cae64)
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 
53 using namespace clang;
54 using namespace CodeGen;
55 
56 static const char AnnotationSection[] = "llvm.metadata";
57 
58 static 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 
72 CodeGenModule::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 
136 CodeGenModule::~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 
148 void 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 
167 void CodeGenModule::createOpenCLRuntime() {
168   OpenCLRuntime = new CGOpenCLRuntime(*this);
169 }
170 
171 void CodeGenModule::createCUDARuntime() {
172   CUDARuntime = CreateNVCUDARuntime(*this);
173 }
174 
175 void 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 
203 void 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 
236 void 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 
284 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
285   // Make sure that this type is translated.
286   Types.UpdateCompletedType(TD);
287 }
288 
289 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
290   if (!TBAA)
291     return 0;
292   return TBAA->getTBAAInfo(QTy);
293 }
294 
295 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
296   if (!TBAA)
297     return 0;
298   return TBAA->getTBAAInfoForVTablePtr();
299 }
300 
301 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
302   if (!TBAA)
303     return 0;
304   return TBAA->getTBAAStructInfo(QTy);
305 }
306 
307 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
308   if (!TBAA)
309     return 0;
310   return TBAA->getTBAAStructTypeInfo(QTy);
311 }
312 
313 llvm::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.
325 void 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 
335 void 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.
342 void 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.
352 void 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 
359 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
360   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
361 }
362 
363 void 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 
377 static 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 
385 static 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 
400 void 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.
418 void 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 
483 StringRef 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 
518 void 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 
534 llvm::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.
540 void 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.
547 void 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 
552 void 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 
580 llvm::GlobalValue::LinkageTypes
581 CodeGenModule::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).
640 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
641                                                     llvm::GlobalValue *GV) {
642   SetCommonAttributes(D, GV);
643 }
644 
645 void 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.
660 static 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 
675 void 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 
746 void 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 
764 void 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 
775 void 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 
828 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
829   assert(!GV->isDeclaration() &&
830          "Only globals with definition can force usage.");
831   LLVMUsed.push_back(GV);
832 }
833 
834 void 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 
861 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
862   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
863   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
864 }
865 
866 void 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 
873 void 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.
882 static 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 
922 void 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 
987 void 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     // Otherwise, emit the definition and move on to the next one.
1024     EmitGlobalDefinition(D);
1025   }
1026 }
1027 
1028 void CodeGenModule::EmitGlobalAnnotations() {
1029   if (Annotations.empty())
1030     return;
1031 
1032   // Create a new global variable for the ConstantStruct in the Module.
1033   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1034     Annotations[0]->getType(), Annotations.size()), Annotations);
1035   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
1036     Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
1037     "llvm.global.annotations");
1038   gv->setSection(AnnotationSection);
1039 }
1040 
1041 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1042   llvm::Constant *&AStr = AnnotationStrings[Str];
1043   if (AStr)
1044     return AStr;
1045 
1046   // Not found yet, create a new global.
1047   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1048   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
1049     true, llvm::GlobalValue::PrivateLinkage, s, ".str");
1050   gv->setSection(AnnotationSection);
1051   gv->setUnnamedAddr(true);
1052   AStr = gv;
1053   return gv;
1054 }
1055 
1056 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1057   SourceManager &SM = getContext().getSourceManager();
1058   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1059   if (PLoc.isValid())
1060     return EmitAnnotationString(PLoc.getFilename());
1061   return EmitAnnotationString(SM.getBufferName(Loc));
1062 }
1063 
1064 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1065   SourceManager &SM = getContext().getSourceManager();
1066   PresumedLoc PLoc = SM.getPresumedLoc(L);
1067   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1068     SM.getExpansionLineNumber(L);
1069   return llvm::ConstantInt::get(Int32Ty, LineNo);
1070 }
1071 
1072 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1073                                                 const AnnotateAttr *AA,
1074                                                 SourceLocation L) {
1075   // Get the globals for file name, annotation, and the line number.
1076   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1077                  *UnitGV = EmitAnnotationUnit(L),
1078                  *LineNoCst = EmitAnnotationLineNo(L);
1079 
1080   // Create the ConstantStruct for the global annotation.
1081   llvm::Constant *Fields[4] = {
1082     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1083     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1084     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1085     LineNoCst
1086   };
1087   return llvm::ConstantStruct::getAnon(Fields);
1088 }
1089 
1090 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1091                                          llvm::GlobalValue *GV) {
1092   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1093   // Get the struct elements for these annotations.
1094   for (specific_attr_iterator<AnnotateAttr>
1095        ai = D->specific_attr_begin<AnnotateAttr>(),
1096        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
1097     Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
1098 }
1099 
1100 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
1101   // Never defer when EmitAllDecls is specified.
1102   if (LangOpts.EmitAllDecls)
1103     return false;
1104 
1105   return !getContext().DeclMustBeEmitted(Global);
1106 }
1107 
1108 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1109     const CXXUuidofExpr* E) {
1110   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1111   // well-formed.
1112   StringRef Uuid = E->getUuidAsStringRef(Context);
1113   std::string Name = "_GUID_" + Uuid.lower();
1114   std::replace(Name.begin(), Name.end(), '-', '_');
1115 
1116   // Look for an existing global.
1117   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1118     return GV;
1119 
1120   llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1121   assert(Init && "failed to initialize as constant");
1122 
1123   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1124       getModule(), Init->getType(),
1125       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1126   return GV;
1127 }
1128 
1129 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1130   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1131   assert(AA && "No alias?");
1132 
1133   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1134 
1135   // See if there is already something with the target's name in the module.
1136   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1137   if (Entry) {
1138     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1139     return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1140   }
1141 
1142   llvm::Constant *Aliasee;
1143   if (isa<llvm::FunctionType>(DeclTy))
1144     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1145                                       GlobalDecl(cast<FunctionDecl>(VD)),
1146                                       /*ForVTable=*/false);
1147   else
1148     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1149                                     llvm::PointerType::getUnqual(DeclTy), 0);
1150 
1151   llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1152   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1153   WeakRefReferences.insert(F);
1154 
1155   return Aliasee;
1156 }
1157 
1158 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1159   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
1160 
1161   // Weak references don't produce any output by themselves.
1162   if (Global->hasAttr<WeakRefAttr>())
1163     return;
1164 
1165   // If this is an alias definition (which otherwise looks like a declaration)
1166   // emit it now.
1167   if (Global->hasAttr<AliasAttr>())
1168     return EmitAliasDefinition(GD);
1169 
1170   // If this is CUDA, be selective about which declarations we emit.
1171   if (LangOpts.CUDA) {
1172     if (CodeGenOpts.CUDAIsDevice) {
1173       if (!Global->hasAttr<CUDADeviceAttr>() &&
1174           !Global->hasAttr<CUDAGlobalAttr>() &&
1175           !Global->hasAttr<CUDAConstantAttr>() &&
1176           !Global->hasAttr<CUDASharedAttr>())
1177         return;
1178     } else {
1179       if (!Global->hasAttr<CUDAHostAttr>() && (
1180             Global->hasAttr<CUDADeviceAttr>() ||
1181             Global->hasAttr<CUDAConstantAttr>() ||
1182             Global->hasAttr<CUDASharedAttr>()))
1183         return;
1184     }
1185   }
1186 
1187   // Ignore declarations, they will be emitted on their first use.
1188   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
1189     // Forward declarations are emitted lazily on first use.
1190     if (!FD->doesThisDeclarationHaveABody()) {
1191       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1192         return;
1193 
1194       const FunctionDecl *InlineDefinition = 0;
1195       FD->getBody(InlineDefinition);
1196 
1197       StringRef MangledName = getMangledName(GD);
1198       DeferredDecls.erase(MangledName);
1199       EmitGlobalDefinition(InlineDefinition);
1200       return;
1201     }
1202   } else {
1203     const VarDecl *VD = cast<VarDecl>(Global);
1204     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1205 
1206     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
1207       return;
1208   }
1209 
1210   // Defer code generation when possible if this is a static definition, inline
1211   // function etc.  These we only want to emit if they are used.
1212   if (!MayDeferGeneration(Global)) {
1213     // Emit the definition if it can't be deferred.
1214     EmitGlobalDefinition(GD);
1215     return;
1216   }
1217 
1218   // If we're deferring emission of a C++ variable with an
1219   // initializer, remember the order in which it appeared in the file.
1220   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1221       cast<VarDecl>(Global)->hasInit()) {
1222     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1223     CXXGlobalInits.push_back(0);
1224   }
1225 
1226   // If the value has already been used, add it directly to the
1227   // DeferredDeclsToEmit list.
1228   StringRef MangledName = getMangledName(GD);
1229   if (GetGlobalValue(MangledName))
1230     DeferredDeclsToEmit.push_back(GD);
1231   else {
1232     // Otherwise, remember that we saw a deferred decl with this name.  The
1233     // first use of the mangled name will cause it to move into
1234     // DeferredDeclsToEmit.
1235     DeferredDecls[MangledName] = GD;
1236   }
1237 }
1238 
1239 namespace {
1240   struct FunctionIsDirectlyRecursive :
1241     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1242     const StringRef Name;
1243     const Builtin::Context &BI;
1244     bool Result;
1245     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1246       Name(N), BI(C), Result(false) {
1247     }
1248     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1249 
1250     bool TraverseCallExpr(CallExpr *E) {
1251       const FunctionDecl *FD = E->getDirectCallee();
1252       if (!FD)
1253         return true;
1254       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1255       if (Attr && Name == Attr->getLabel()) {
1256         Result = true;
1257         return false;
1258       }
1259       unsigned BuiltinID = FD->getBuiltinID();
1260       if (!BuiltinID)
1261         return true;
1262       StringRef BuiltinName = BI.GetName(BuiltinID);
1263       if (BuiltinName.startswith("__builtin_") &&
1264           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1265         Result = true;
1266         return false;
1267       }
1268       return true;
1269     }
1270   };
1271 }
1272 
1273 // isTriviallyRecursive - Check if this function calls another
1274 // decl that, because of the asm attribute or the other decl being a builtin,
1275 // ends up pointing to itself.
1276 bool
1277 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1278   StringRef Name;
1279   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1280     // asm labels are a special kind of mangling we have to support.
1281     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1282     if (!Attr)
1283       return false;
1284     Name = Attr->getLabel();
1285   } else {
1286     Name = FD->getName();
1287   }
1288 
1289   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1290   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1291   return Walker.Result;
1292 }
1293 
1294 bool
1295 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1296   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1297     return true;
1298   const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
1299   if (CodeGenOpts.OptimizationLevel == 0 &&
1300       !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
1301     return false;
1302   // PR9614. Avoid cases where the source code is lying to us. An available
1303   // externally function should have an equivalent function somewhere else,
1304   // but a function that calls itself is clearly not equivalent to the real
1305   // implementation.
1306   // This happens in glibc's btowc and in some configure checks.
1307   return !isTriviallyRecursive(F);
1308 }
1309 
1310 /// If the type for the method's class was generated by
1311 /// CGDebugInfo::createContextChain(), the cache contains only a
1312 /// limited DIType without any declarations. Since EmitFunctionStart()
1313 /// needs to find the canonical declaration for each method, we need
1314 /// to construct the complete type prior to emitting the method.
1315 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1316   if (!D->isInstance())
1317     return;
1318 
1319   if (CGDebugInfo *DI = getModuleDebugInfo())
1320     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1321       const PointerType *ThisPtr =
1322         cast<PointerType>(D->getThisType(getContext()));
1323       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1324     }
1325 }
1326 
1327 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
1328   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1329 
1330   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1331                                  Context.getSourceManager(),
1332                                  "Generating code for declaration");
1333 
1334   if (isa<FunctionDecl>(D)) {
1335     // At -O0, don't generate IR for functions with available_externally
1336     // linkage.
1337     if (!shouldEmitFunction(GD))
1338       return;
1339 
1340     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1341       CompleteDIClassType(Method);
1342       // Make sure to emit the definition(s) before we emit the thunks.
1343       // This is necessary for the generation of certain thunks.
1344       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1345         EmitCXXConstructor(CD, GD.getCtorType());
1346       else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1347         EmitCXXDestructor(DD, GD.getDtorType());
1348       else
1349         EmitGlobalFunctionDefinition(GD);
1350 
1351       if (Method->isVirtual())
1352         getVTables().EmitThunks(GD);
1353 
1354       return;
1355     }
1356 
1357     return EmitGlobalFunctionDefinition(GD);
1358   }
1359 
1360   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1361     return EmitGlobalVarDefinition(VD);
1362 
1363   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1364 }
1365 
1366 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1367 /// module, create and return an llvm Function with the specified type. If there
1368 /// is something in the module with the specified name, return it potentially
1369 /// bitcasted to the right type.
1370 ///
1371 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1372 /// to set the attributes on the function when it is first created.
1373 llvm::Constant *
1374 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1375                                        llvm::Type *Ty,
1376                                        GlobalDecl GD, bool ForVTable,
1377                                        llvm::AttributeSet ExtraAttrs) {
1378   const Decl *D = GD.getDecl();
1379 
1380   // Lookup the entry, lazily creating it if necessary.
1381   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1382   if (Entry) {
1383     if (WeakRefReferences.erase(Entry)) {
1384       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1385       if (FD && !FD->hasAttr<WeakAttr>())
1386         Entry->setLinkage(llvm::Function::ExternalLinkage);
1387     }
1388 
1389     if (Entry->getType()->getElementType() == Ty)
1390       return Entry;
1391 
1392     // Make sure the result is of the correct type.
1393     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1394   }
1395 
1396   // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1397   // each other bottoming out with the base dtor.  Therefore we emit non-base
1398   // dtors on usage, even if there is no dtor definition in the TU.
1399   if (D && isa<CXXDestructorDecl>(D) &&
1400       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1401                                          GD.getDtorType()))
1402     DeferredDeclsToEmit.push_back(GD);
1403 
1404   // This function doesn't have a complete type (for example, the return
1405   // type is an incomplete struct). Use a fake type instead, and make
1406   // sure not to try to set attributes.
1407   bool IsIncompleteFunction = false;
1408 
1409   llvm::FunctionType *FTy;
1410   if (isa<llvm::FunctionType>(Ty)) {
1411     FTy = cast<llvm::FunctionType>(Ty);
1412   } else {
1413     FTy = llvm::FunctionType::get(VoidTy, false);
1414     IsIncompleteFunction = true;
1415   }
1416 
1417   llvm::Function *F = llvm::Function::Create(FTy,
1418                                              llvm::Function::ExternalLinkage,
1419                                              MangledName, &getModule());
1420   assert(F->getName() == MangledName && "name was uniqued!");
1421   if (D)
1422     SetFunctionAttributes(GD, F, IsIncompleteFunction);
1423   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1424     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1425     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1426                      llvm::AttributeSet::get(VMContext,
1427                                              llvm::AttributeSet::FunctionIndex,
1428                                              B));
1429   }
1430 
1431   // This is the first use or definition of a mangled name.  If there is a
1432   // deferred decl with this name, remember that we need to emit it at the end
1433   // of the file.
1434   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1435   if (DDI != DeferredDecls.end()) {
1436     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1437     // list, and remove it from DeferredDecls (since we don't need it anymore).
1438     DeferredDeclsToEmit.push_back(DDI->second);
1439     DeferredDecls.erase(DDI);
1440 
1441   // Otherwise, if this is a sized deallocation function, emit a weak definition
1442   // for it at the end of the translation unit.
1443   } else if (D && cast<FunctionDecl>(D)
1444                       ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
1445     DeferredDeclsToEmit.push_back(GD);
1446 
1447   // Otherwise, there are cases we have to worry about where we're
1448   // using a declaration for which we must emit a definition but where
1449   // we might not find a top-level definition:
1450   //   - member functions defined inline in their classes
1451   //   - friend functions defined inline in some class
1452   //   - special member functions with implicit definitions
1453   // If we ever change our AST traversal to walk into class methods,
1454   // this will be unnecessary.
1455   //
1456   // We also don't emit a definition for a function if it's going to be an entry
1457   // in a vtable, unless it's already marked as used.
1458   } else if (getLangOpts().CPlusPlus && D) {
1459     // Look for a declaration that's lexically in a record.
1460     const FunctionDecl *FD = cast<FunctionDecl>(D);
1461     FD = FD->getMostRecentDecl();
1462     do {
1463       if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1464         if (FD->isImplicit() && !ForVTable) {
1465           assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1466           DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
1467           break;
1468         } else if (FD->doesThisDeclarationHaveABody()) {
1469           DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
1470           break;
1471         }
1472       }
1473       FD = FD->getPreviousDecl();
1474     } while (FD);
1475   }
1476 
1477   // Make sure the result is of the requested type.
1478   if (!IsIncompleteFunction) {
1479     assert(F->getType()->getElementType() == Ty);
1480     return F;
1481   }
1482 
1483   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1484   return llvm::ConstantExpr::getBitCast(F, PTy);
1485 }
1486 
1487 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1488 /// non-null, then this function will use the specified type if it has to
1489 /// create it (this occurs when we see a definition of the function).
1490 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1491                                                  llvm::Type *Ty,
1492                                                  bool ForVTable) {
1493   // If there was no specific requested type, just convert it now.
1494   if (!Ty)
1495     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1496 
1497   StringRef MangledName = getMangledName(GD);
1498   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1499 }
1500 
1501 /// CreateRuntimeFunction - Create a new runtime function with the specified
1502 /// type and name.
1503 llvm::Constant *
1504 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1505                                      StringRef Name,
1506                                      llvm::AttributeSet ExtraAttrs) {
1507   llvm::Constant *C
1508     = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1509                               ExtraAttrs);
1510   if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1511     if (F->empty())
1512       F->setCallingConv(getRuntimeCC());
1513   return C;
1514 }
1515 
1516 /// isTypeConstant - Determine whether an object of this type can be emitted
1517 /// as a constant.
1518 ///
1519 /// If ExcludeCtor is true, the duration when the object's constructor runs
1520 /// will not be considered. The caller will need to verify that the object is
1521 /// not written to during its construction.
1522 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1523   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1524     return false;
1525 
1526   if (Context.getLangOpts().CPlusPlus) {
1527     if (const CXXRecordDecl *Record
1528           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1529       return ExcludeCtor && !Record->hasMutableFields() &&
1530              Record->hasTrivialDestructor();
1531   }
1532 
1533   return true;
1534 }
1535 
1536 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1537 /// create and return an llvm GlobalVariable with the specified type.  If there
1538 /// is something in the module with the specified name, return it potentially
1539 /// bitcasted to the right type.
1540 ///
1541 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1542 /// to set the attributes on the global when it is first created.
1543 llvm::Constant *
1544 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1545                                      llvm::PointerType *Ty,
1546                                      const VarDecl *D,
1547                                      bool UnnamedAddr) {
1548   // Lookup the entry, lazily creating it if necessary.
1549   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1550   if (Entry) {
1551     if (WeakRefReferences.erase(Entry)) {
1552       if (D && !D->hasAttr<WeakAttr>())
1553         Entry->setLinkage(llvm::Function::ExternalLinkage);
1554     }
1555 
1556     if (UnnamedAddr)
1557       Entry->setUnnamedAddr(true);
1558 
1559     if (Entry->getType() == Ty)
1560       return Entry;
1561 
1562     // Make sure the result is of the correct type.
1563     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1564       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1565 
1566     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1567   }
1568 
1569   // This is the first use or definition of a mangled name.  If there is a
1570   // deferred decl with this name, remember that we need to emit it at the end
1571   // of the file.
1572   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1573   if (DDI != DeferredDecls.end()) {
1574     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1575     // list, and remove it from DeferredDecls (since we don't need it anymore).
1576     DeferredDeclsToEmit.push_back(DDI->second);
1577     DeferredDecls.erase(DDI);
1578   }
1579 
1580   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1581   llvm::GlobalVariable *GV =
1582     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1583                              llvm::GlobalValue::ExternalLinkage,
1584                              0, MangledName, 0,
1585                              llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1586 
1587   // Handle things which are present even on external declarations.
1588   if (D) {
1589     // FIXME: This code is overly simple and should be merged with other global
1590     // handling.
1591     GV->setConstant(isTypeConstant(D->getType(), false));
1592 
1593     // Set linkage and visibility in case we never see a definition.
1594     LinkageInfo LV = D->getLinkageAndVisibility();
1595     if (LV.getLinkage() != ExternalLinkage) {
1596       // Don't set internal linkage on declarations.
1597     } else {
1598       if (D->hasAttr<DLLImportAttr>())
1599         GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1600       else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1601         GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1602 
1603       // Set visibility on a declaration only if it's explicit.
1604       if (LV.isVisibilityExplicit())
1605         GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1606     }
1607 
1608     if (D->getTLSKind()) {
1609       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1610         CXXThreadLocals.push_back(std::make_pair(D, GV));
1611       setTLSMode(GV, *D);
1612     }
1613 
1614     // If required by the ABI, treat declarations of static data members with
1615     // inline initializers as definitions.
1616     if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1617         D->isStaticDataMember() && D->hasInit() &&
1618         !D->isThisDeclarationADefinition())
1619       EmitGlobalVarDefinition(D);
1620   }
1621 
1622   if (AddrSpace != Ty->getAddressSpace())
1623     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1624 
1625   return GV;
1626 }
1627 
1628 
1629 llvm::GlobalVariable *
1630 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1631                                       llvm::Type *Ty,
1632                                       llvm::GlobalValue::LinkageTypes Linkage) {
1633   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1634   llvm::GlobalVariable *OldGV = 0;
1635 
1636 
1637   if (GV) {
1638     // Check if the variable has the right type.
1639     if (GV->getType()->getElementType() == Ty)
1640       return GV;
1641 
1642     // Because C++ name mangling, the only way we can end up with an already
1643     // existing global with the same name is if it has been declared extern "C".
1644     assert(GV->isDeclaration() && "Declaration has wrong type!");
1645     OldGV = GV;
1646   }
1647 
1648   // Create a new variable.
1649   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1650                                 Linkage, 0, Name);
1651 
1652   if (OldGV) {
1653     // Replace occurrences of the old variable if needed.
1654     GV->takeName(OldGV);
1655 
1656     if (!OldGV->use_empty()) {
1657       llvm::Constant *NewPtrForOldDecl =
1658       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1659       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1660     }
1661 
1662     OldGV->eraseFromParent();
1663   }
1664 
1665   return GV;
1666 }
1667 
1668 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1669 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1670 /// then it will be created with the specified type instead of whatever the
1671 /// normal requested type would be.
1672 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1673                                                   llvm::Type *Ty) {
1674   assert(D->hasGlobalStorage() && "Not a global variable");
1675   QualType ASTTy = D->getType();
1676   if (Ty == 0)
1677     Ty = getTypes().ConvertTypeForMem(ASTTy);
1678 
1679   llvm::PointerType *PTy =
1680     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1681 
1682   StringRef MangledName = getMangledName(D);
1683   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1684 }
1685 
1686 /// CreateRuntimeVariable - Create a new runtime global variable with the
1687 /// specified type and name.
1688 llvm::Constant *
1689 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1690                                      StringRef Name) {
1691   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1692                                true);
1693 }
1694 
1695 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1696   assert(!D->getInit() && "Cannot emit definite definitions here!");
1697 
1698   if (MayDeferGeneration(D)) {
1699     // If we have not seen a reference to this variable yet, place it
1700     // into the deferred declarations table to be emitted if needed
1701     // later.
1702     StringRef MangledName = getMangledName(D);
1703     if (!GetGlobalValue(MangledName)) {
1704       DeferredDecls[MangledName] = D;
1705       return;
1706     }
1707   }
1708 
1709   // The tentative definition is the only definition.
1710   EmitGlobalVarDefinition(D);
1711 }
1712 
1713 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1714     return Context.toCharUnitsFromBits(
1715       TheDataLayout.getTypeStoreSizeInBits(Ty));
1716 }
1717 
1718 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1719                                                  unsigned AddrSpace) {
1720   if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1721     if (D->hasAttr<CUDAConstantAttr>())
1722       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1723     else if (D->hasAttr<CUDASharedAttr>())
1724       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1725     else
1726       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1727   }
1728 
1729   return AddrSpace;
1730 }
1731 
1732 template<typename SomeDecl>
1733 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1734                                                llvm::GlobalValue *GV) {
1735   if (!getLangOpts().CPlusPlus)
1736     return;
1737 
1738   // Must have 'used' attribute, or else inline assembly can't rely on
1739   // the name existing.
1740   if (!D->template hasAttr<UsedAttr>())
1741     return;
1742 
1743   // Must have internal linkage and an ordinary name.
1744   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1745     return;
1746 
1747   // Must be in an extern "C" context. Entities declared directly within
1748   // a record are not extern "C" even if the record is in such a context.
1749   const SomeDecl *First = D->getFirstDecl();
1750   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1751     return;
1752 
1753   // OK, this is an internal linkage entity inside an extern "C" linkage
1754   // specification. Make a note of that so we can give it the "expected"
1755   // mangled name if nothing else is using that name.
1756   std::pair<StaticExternCMap::iterator, bool> R =
1757       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1758 
1759   // If we have multiple internal linkage entities with the same name
1760   // in extern "C" regions, none of them gets that name.
1761   if (!R.second)
1762     R.first->second = 0;
1763 }
1764 
1765 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1766   llvm::Constant *Init = 0;
1767   QualType ASTTy = D->getType();
1768   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1769   bool NeedsGlobalCtor = false;
1770   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1771 
1772   const VarDecl *InitDecl;
1773   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1774 
1775   if (!InitExpr) {
1776     // This is a tentative definition; tentative definitions are
1777     // implicitly initialized with { 0 }.
1778     //
1779     // Note that tentative definitions are only emitted at the end of
1780     // a translation unit, so they should never have incomplete
1781     // type. In addition, EmitTentativeDefinition makes sure that we
1782     // never attempt to emit a tentative definition if a real one
1783     // exists. A use may still exists, however, so we still may need
1784     // to do a RAUW.
1785     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1786     Init = EmitNullConstant(D->getType());
1787   } else {
1788     initializedGlobalDecl = GlobalDecl(D);
1789     Init = EmitConstantInit(*InitDecl);
1790 
1791     if (!Init) {
1792       QualType T = InitExpr->getType();
1793       if (D->getType()->isReferenceType())
1794         T = D->getType();
1795 
1796       if (getLangOpts().CPlusPlus) {
1797         Init = EmitNullConstant(T);
1798         NeedsGlobalCtor = true;
1799       } else {
1800         ErrorUnsupported(D, "static initializer");
1801         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1802       }
1803     } else {
1804       // We don't need an initializer, so remove the entry for the delayed
1805       // initializer position (just in case this entry was delayed) if we
1806       // also don't need to register a destructor.
1807       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1808         DelayedCXXInitPosition.erase(D);
1809     }
1810   }
1811 
1812   llvm::Type* InitType = Init->getType();
1813   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1814 
1815   // Strip off a bitcast if we got one back.
1816   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1817     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1818            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1819            // All zero index gep.
1820            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1821     Entry = CE->getOperand(0);
1822   }
1823 
1824   // Entry is now either a Function or GlobalVariable.
1825   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1826 
1827   // We have a definition after a declaration with the wrong type.
1828   // We must make a new GlobalVariable* and update everything that used OldGV
1829   // (a declaration or tentative definition) with the new GlobalVariable*
1830   // (which will be a definition).
1831   //
1832   // This happens if there is a prototype for a global (e.g.
1833   // "extern int x[];") and then a definition of a different type (e.g.
1834   // "int x[10];"). This also happens when an initializer has a different type
1835   // from the type of the global (this happens with unions).
1836   if (GV == 0 ||
1837       GV->getType()->getElementType() != InitType ||
1838       GV->getType()->getAddressSpace() !=
1839        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1840 
1841     // Move the old entry aside so that we'll create a new one.
1842     Entry->setName(StringRef());
1843 
1844     // Make a new global with the correct type, this is now guaranteed to work.
1845     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1846 
1847     // Replace all uses of the old global with the new global
1848     llvm::Constant *NewPtrForOldDecl =
1849         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1850     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1851 
1852     // Erase the old global, since it is no longer used.
1853     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1854   }
1855 
1856   MaybeHandleStaticInExternC(D, GV);
1857 
1858   if (D->hasAttr<AnnotateAttr>())
1859     AddGlobalAnnotations(D, GV);
1860 
1861   GV->setInitializer(Init);
1862 
1863   // If it is safe to mark the global 'constant', do so now.
1864   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1865                   isTypeConstant(D->getType(), true));
1866 
1867   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1868 
1869   // Set the llvm linkage type as appropriate.
1870   llvm::GlobalValue::LinkageTypes Linkage =
1871     GetLLVMLinkageVarDefinition(D, GV->isConstant());
1872   GV->setLinkage(Linkage);
1873 
1874   // If required by the ABI, give definitions of static data members with inline
1875   // initializers linkonce_odr linkage.
1876   if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1877       D->isStaticDataMember() && InitExpr &&
1878       !InitDecl->isThisDeclarationADefinition())
1879     GV->setLinkage(llvm::GlobalVariable::LinkOnceODRLinkage);
1880 
1881   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1882     // common vars aren't constant even if declared const.
1883     GV->setConstant(false);
1884 
1885   SetCommonAttributes(D, GV);
1886 
1887   // Emit the initializer function if necessary.
1888   if (NeedsGlobalCtor || NeedsGlobalDtor)
1889     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1890 
1891   // If we are compiling with ASan, add metadata indicating dynamically
1892   // initialized globals.
1893   if (SanOpts.Address && NeedsGlobalCtor) {
1894     llvm::Module &M = getModule();
1895 
1896     llvm::NamedMDNode *DynamicInitializers =
1897         M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1898     llvm::Value *GlobalToAdd[] = { GV };
1899     llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1900     DynamicInitializers->addOperand(ThisGlobal);
1901   }
1902 
1903   // Emit global variable debug information.
1904   if (CGDebugInfo *DI = getModuleDebugInfo())
1905     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1906       DI->EmitGlobalVariable(GV, D);
1907 }
1908 
1909 llvm::GlobalValue::LinkageTypes
1910 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) {
1911   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1912   if (Linkage == GVA_Internal)
1913     return llvm::Function::InternalLinkage;
1914   else if (D->hasAttr<DLLImportAttr>())
1915     return llvm::Function::DLLImportLinkage;
1916   else if (D->hasAttr<DLLExportAttr>())
1917     return llvm::Function::DLLExportLinkage;
1918   else if (D->hasAttr<SelectAnyAttr>()) {
1919     // selectany symbols are externally visible, so use weak instead of
1920     // linkonce.  MSVC optimizes away references to const selectany globals, so
1921     // all definitions should be the same and ODR linkage should be used.
1922     // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
1923     return llvm::GlobalVariable::WeakODRLinkage;
1924   } else if (D->hasAttr<WeakAttr>()) {
1925     if (isConstant)
1926       return llvm::GlobalVariable::WeakODRLinkage;
1927     else
1928       return llvm::GlobalVariable::WeakAnyLinkage;
1929   } else if (Linkage == GVA_TemplateInstantiation ||
1930              Linkage == GVA_ExplicitTemplateInstantiation)
1931     return llvm::GlobalVariable::WeakODRLinkage;
1932   else if (!getLangOpts().CPlusPlus &&
1933            ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1934              D->getAttr<CommonAttr>()) &&
1935            !D->hasExternalStorage() && !D->getInit() &&
1936            !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
1937            !D->getAttr<WeakImportAttr>()) {
1938     // Thread local vars aren't considered common linkage.
1939     return llvm::GlobalVariable::CommonLinkage;
1940   } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1941              getTarget().getTriple().isMacOSX())
1942     // On Darwin, the backing variable for a C++11 thread_local variable always
1943     // has internal linkage; all accesses should just be calls to the
1944     // Itanium-specified entry point, which has the normal linkage of the
1945     // variable.
1946     return llvm::GlobalValue::InternalLinkage;
1947   return llvm::GlobalVariable::ExternalLinkage;
1948 }
1949 
1950 /// Replace the uses of a function that was declared with a non-proto type.
1951 /// We want to silently drop extra arguments from call sites
1952 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1953                                           llvm::Function *newFn) {
1954   // Fast path.
1955   if (old->use_empty()) return;
1956 
1957   llvm::Type *newRetTy = newFn->getReturnType();
1958   SmallVector<llvm::Value*, 4> newArgs;
1959 
1960   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1961          ui != ue; ) {
1962     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1963     llvm::User *user = *use;
1964 
1965     // Recognize and replace uses of bitcasts.  Most calls to
1966     // unprototyped functions will use bitcasts.
1967     if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1968       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1969         replaceUsesOfNonProtoConstant(bitcast, newFn);
1970       continue;
1971     }
1972 
1973     // Recognize calls to the function.
1974     llvm::CallSite callSite(user);
1975     if (!callSite) continue;
1976     if (!callSite.isCallee(use)) continue;
1977 
1978     // If the return types don't match exactly, then we can't
1979     // transform this call unless it's dead.
1980     if (callSite->getType() != newRetTy && !callSite->use_empty())
1981       continue;
1982 
1983     // Get the call site's attribute list.
1984     SmallVector<llvm::AttributeSet, 8> newAttrs;
1985     llvm::AttributeSet oldAttrs = callSite.getAttributes();
1986 
1987     // Collect any return attributes from the call.
1988     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
1989       newAttrs.push_back(
1990         llvm::AttributeSet::get(newFn->getContext(),
1991                                 oldAttrs.getRetAttributes()));
1992 
1993     // If the function was passed too few arguments, don't transform.
1994     unsigned newNumArgs = newFn->arg_size();
1995     if (callSite.arg_size() < newNumArgs) continue;
1996 
1997     // If extra arguments were passed, we silently drop them.
1998     // If any of the types mismatch, we don't transform.
1999     unsigned argNo = 0;
2000     bool dontTransform = false;
2001     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2002            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2003       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2004         dontTransform = true;
2005         break;
2006       }
2007 
2008       // Add any parameter attributes.
2009       if (oldAttrs.hasAttributes(argNo + 1))
2010         newAttrs.
2011           push_back(llvm::
2012                     AttributeSet::get(newFn->getContext(),
2013                                       oldAttrs.getParamAttributes(argNo + 1)));
2014     }
2015     if (dontTransform)
2016       continue;
2017 
2018     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2019       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2020                                                  oldAttrs.getFnAttributes()));
2021 
2022     // Okay, we can transform this.  Create the new call instruction and copy
2023     // over the required information.
2024     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2025 
2026     llvm::CallSite newCall;
2027     if (callSite.isCall()) {
2028       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2029                                        callSite.getInstruction());
2030     } else {
2031       llvm::InvokeInst *oldInvoke =
2032         cast<llvm::InvokeInst>(callSite.getInstruction());
2033       newCall = llvm::InvokeInst::Create(newFn,
2034                                          oldInvoke->getNormalDest(),
2035                                          oldInvoke->getUnwindDest(),
2036                                          newArgs, "",
2037                                          callSite.getInstruction());
2038     }
2039     newArgs.clear(); // for the next iteration
2040 
2041     if (!newCall->getType()->isVoidTy())
2042       newCall->takeName(callSite.getInstruction());
2043     newCall.setAttributes(
2044                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2045     newCall.setCallingConv(callSite.getCallingConv());
2046 
2047     // Finally, remove the old call, replacing any uses with the new one.
2048     if (!callSite->use_empty())
2049       callSite->replaceAllUsesWith(newCall.getInstruction());
2050 
2051     // Copy debug location attached to CI.
2052     if (!callSite->getDebugLoc().isUnknown())
2053       newCall->setDebugLoc(callSite->getDebugLoc());
2054     callSite->eraseFromParent();
2055   }
2056 }
2057 
2058 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2059 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2060 /// existing call uses of the old function in the module, this adjusts them to
2061 /// call the new function directly.
2062 ///
2063 /// This is not just a cleanup: the always_inline pass requires direct calls to
2064 /// functions to be able to inline them.  If there is a bitcast in the way, it
2065 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2066 /// run at -O0.
2067 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2068                                                       llvm::Function *NewFn) {
2069   // If we're redefining a global as a function, don't transform it.
2070   if (!isa<llvm::Function>(Old)) return;
2071 
2072   replaceUsesOfNonProtoConstant(Old, NewFn);
2073 }
2074 
2075 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2076   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2077   // If we have a definition, this might be a deferred decl. If the
2078   // instantiation is explicit, make sure we emit it at the end.
2079   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2080     GetAddrOfGlobalVar(VD);
2081 
2082   EmitTopLevelDecl(VD);
2083 }
2084 
2085 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
2086   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2087 
2088   // Compute the function info and LLVM type.
2089   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2090   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2091 
2092   // Get or create the prototype for the function.
2093   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
2094 
2095   // Strip off a bitcast if we got one back.
2096   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2097     assert(CE->getOpcode() == llvm::Instruction::BitCast);
2098     Entry = CE->getOperand(0);
2099   }
2100 
2101   if (!cast<llvm::GlobalValue>(Entry)->isDeclaration()) {
2102     getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2103     return;
2104   }
2105 
2106   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2107     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
2108 
2109     // If the types mismatch then we have to rewrite the definition.
2110     assert(OldFn->isDeclaration() &&
2111            "Shouldn't replace non-declaration");
2112 
2113     // F is the Function* for the one with the wrong type, we must make a new
2114     // Function* and update everything that used F (a declaration) with the new
2115     // Function* (which will be a definition).
2116     //
2117     // This happens if there is a prototype for a function
2118     // (e.g. "int f()") and then a definition of a different type
2119     // (e.g. "int f(int x)").  Move the old function aside so that it
2120     // doesn't interfere with GetAddrOfFunction.
2121     OldFn->setName(StringRef());
2122     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2123 
2124     // This might be an implementation of a function without a
2125     // prototype, in which case, try to do special replacement of
2126     // calls which match the new prototype.  The really key thing here
2127     // is that we also potentially drop arguments from the call site
2128     // so as to make a direct call, which makes the inliner happier
2129     // and suppresses a number of optimizer warnings (!) about
2130     // dropping arguments.
2131     if (!OldFn->use_empty()) {
2132       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
2133       OldFn->removeDeadConstantUsers();
2134     }
2135 
2136     // Replace uses of F with the Function we will endow with a body.
2137     if (!Entry->use_empty()) {
2138       llvm::Constant *NewPtrForOldDecl =
2139         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2140       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2141     }
2142 
2143     // Ok, delete the old function now, which is dead.
2144     OldFn->eraseFromParent();
2145 
2146     Entry = NewFn;
2147   }
2148 
2149   // We need to set linkage and visibility on the function before
2150   // generating code for it because various parts of IR generation
2151   // want to propagate this information down (e.g. to local static
2152   // declarations).
2153   llvm::Function *Fn = cast<llvm::Function>(Entry);
2154   setFunctionLinkage(GD, Fn);
2155 
2156   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
2157   setGlobalVisibility(Fn, D);
2158 
2159   MaybeHandleStaticInExternC(D, Fn);
2160 
2161   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2162 
2163   SetFunctionDefinitionAttributes(D, Fn);
2164   SetLLVMFunctionAttributesForDefinition(D, Fn);
2165 
2166   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2167     AddGlobalCtor(Fn, CA->getPriority());
2168   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2169     AddGlobalDtor(Fn, DA->getPriority());
2170   if (D->hasAttr<AnnotateAttr>())
2171     AddGlobalAnnotations(D, Fn);
2172 }
2173 
2174 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2175   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
2176   const AliasAttr *AA = D->getAttr<AliasAttr>();
2177   assert(AA && "Not an alias?");
2178 
2179   StringRef MangledName = getMangledName(GD);
2180 
2181   // If there is a definition in the module, then it wins over the alias.
2182   // This is dubious, but allow it to be safe.  Just ignore the alias.
2183   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2184   if (Entry && !Entry->isDeclaration())
2185     return;
2186 
2187   Aliases.push_back(GD);
2188 
2189   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2190 
2191   // Create a reference to the named value.  This ensures that it is emitted
2192   // if a deferred decl.
2193   llvm::Constant *Aliasee;
2194   if (isa<llvm::FunctionType>(DeclTy))
2195     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2196                                       /*ForVTable=*/false);
2197   else
2198     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2199                                     llvm::PointerType::getUnqual(DeclTy), 0);
2200 
2201   // Create the new alias itself, but don't set a name yet.
2202   llvm::GlobalValue *GA =
2203     new llvm::GlobalAlias(Aliasee->getType(),
2204                           llvm::Function::ExternalLinkage,
2205                           "", Aliasee, &getModule());
2206 
2207   if (Entry) {
2208     assert(Entry->isDeclaration());
2209 
2210     // If there is a declaration in the module, then we had an extern followed
2211     // by the alias, as in:
2212     //   extern int test6();
2213     //   ...
2214     //   int test6() __attribute__((alias("test7")));
2215     //
2216     // Remove it and replace uses of it with the alias.
2217     GA->takeName(Entry);
2218 
2219     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2220                                                           Entry->getType()));
2221     Entry->eraseFromParent();
2222   } else {
2223     GA->setName(MangledName);
2224   }
2225 
2226   // Set attributes which are particular to an alias; this is a
2227   // specialization of the attributes which may be set on a global
2228   // variable/function.
2229   if (D->hasAttr<DLLExportAttr>()) {
2230     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2231       // The dllexport attribute is ignored for undefined symbols.
2232       if (FD->hasBody())
2233         GA->setLinkage(llvm::Function::DLLExportLinkage);
2234     } else {
2235       GA->setLinkage(llvm::Function::DLLExportLinkage);
2236     }
2237   } else if (D->hasAttr<WeakAttr>() ||
2238              D->hasAttr<WeakRefAttr>() ||
2239              D->isWeakImported()) {
2240     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2241   }
2242 
2243   SetCommonAttributes(D, GA);
2244 }
2245 
2246 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2247                                             ArrayRef<llvm::Type*> Tys) {
2248   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2249                                          Tys);
2250 }
2251 
2252 static llvm::StringMapEntry<llvm::Constant*> &
2253 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2254                          const StringLiteral *Literal,
2255                          bool TargetIsLSB,
2256                          bool &IsUTF16,
2257                          unsigned &StringLength) {
2258   StringRef String = Literal->getString();
2259   unsigned NumBytes = String.size();
2260 
2261   // Check for simple case.
2262   if (!Literal->containsNonAsciiOrNull()) {
2263     StringLength = NumBytes;
2264     return Map.GetOrCreateValue(String);
2265   }
2266 
2267   // Otherwise, convert the UTF8 literals into a string of shorts.
2268   IsUTF16 = true;
2269 
2270   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2271   const UTF8 *FromPtr = (const UTF8 *)String.data();
2272   UTF16 *ToPtr = &ToBuf[0];
2273 
2274   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2275                            &ToPtr, ToPtr + NumBytes,
2276                            strictConversion);
2277 
2278   // ConvertUTF8toUTF16 returns the length in ToPtr.
2279   StringLength = ToPtr - &ToBuf[0];
2280 
2281   // Add an explicit null.
2282   *ToPtr = 0;
2283   return Map.
2284     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2285                                (StringLength + 1) * 2));
2286 }
2287 
2288 static llvm::StringMapEntry<llvm::Constant*> &
2289 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2290                        const StringLiteral *Literal,
2291                        unsigned &StringLength) {
2292   StringRef String = Literal->getString();
2293   StringLength = String.size();
2294   return Map.GetOrCreateValue(String);
2295 }
2296 
2297 llvm::Constant *
2298 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2299   unsigned StringLength = 0;
2300   bool isUTF16 = false;
2301   llvm::StringMapEntry<llvm::Constant*> &Entry =
2302     GetConstantCFStringEntry(CFConstantStringMap, Literal,
2303                              getDataLayout().isLittleEndian(),
2304                              isUTF16, StringLength);
2305 
2306   if (llvm::Constant *C = Entry.getValue())
2307     return C;
2308 
2309   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2310   llvm::Constant *Zeros[] = { Zero, Zero };
2311   llvm::Value *V;
2312 
2313   // If we don't already have it, get __CFConstantStringClassReference.
2314   if (!CFConstantStringClassRef) {
2315     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2316     Ty = llvm::ArrayType::get(Ty, 0);
2317     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2318                                            "__CFConstantStringClassReference");
2319     // Decay array -> ptr
2320     V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2321     CFConstantStringClassRef = V;
2322   }
2323   else
2324     V = CFConstantStringClassRef;
2325 
2326   QualType CFTy = getContext().getCFConstantStringType();
2327 
2328   llvm::StructType *STy =
2329     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2330 
2331   llvm::Constant *Fields[4];
2332 
2333   // Class pointer.
2334   Fields[0] = cast<llvm::ConstantExpr>(V);
2335 
2336   // Flags.
2337   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2338   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2339     llvm::ConstantInt::get(Ty, 0x07C8);
2340 
2341   // String pointer.
2342   llvm::Constant *C = 0;
2343   if (isUTF16) {
2344     ArrayRef<uint16_t> Arr =
2345       llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2346                                      const_cast<char *>(Entry.getKey().data())),
2347                                    Entry.getKey().size() / 2);
2348     C = llvm::ConstantDataArray::get(VMContext, Arr);
2349   } else {
2350     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2351   }
2352 
2353   llvm::GlobalValue::LinkageTypes Linkage;
2354   if (isUTF16)
2355     // FIXME: why do utf strings get "_" labels instead of "L" labels?
2356     Linkage = llvm::GlobalValue::InternalLinkage;
2357   else
2358     // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2359     // when using private linkage. It is not clear if this is a bug in ld
2360     // or a reasonable new restriction.
2361     Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2362 
2363   // Note: -fwritable-strings doesn't make the backing store strings of
2364   // CFStrings writable. (See <rdar://problem/10657500>)
2365   llvm::GlobalVariable *GV =
2366     new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2367                              Linkage, C, ".str");
2368   GV->setUnnamedAddr(true);
2369   // Don't enforce the target's minimum global alignment, since the only use
2370   // of the string is via this class initializer.
2371   if (isUTF16) {
2372     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2373     GV->setAlignment(Align.getQuantity());
2374   } else {
2375     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2376     GV->setAlignment(Align.getQuantity());
2377   }
2378 
2379   // String.
2380   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2381 
2382   if (isUTF16)
2383     // Cast the UTF16 string to the correct type.
2384     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2385 
2386   // String length.
2387   Ty = getTypes().ConvertType(getContext().LongTy);
2388   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2389 
2390   // The struct.
2391   C = llvm::ConstantStruct::get(STy, Fields);
2392   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2393                                 llvm::GlobalVariable::PrivateLinkage, C,
2394                                 "_unnamed_cfstring_");
2395   if (const char *Sect = getTarget().getCFStringSection())
2396     GV->setSection(Sect);
2397   Entry.setValue(GV);
2398 
2399   return GV;
2400 }
2401 
2402 static RecordDecl *
2403 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2404                  DeclContext *DC, IdentifierInfo *Id) {
2405   SourceLocation Loc;
2406   if (Ctx.getLangOpts().CPlusPlus)
2407     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2408   else
2409     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2410 }
2411 
2412 llvm::Constant *
2413 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2414   unsigned StringLength = 0;
2415   llvm::StringMapEntry<llvm::Constant*> &Entry =
2416     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2417 
2418   if (llvm::Constant *C = Entry.getValue())
2419     return C;
2420 
2421   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2422   llvm::Constant *Zeros[] = { Zero, Zero };
2423   llvm::Value *V;
2424   // If we don't already have it, get _NSConstantStringClassReference.
2425   if (!ConstantStringClassRef) {
2426     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2427     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2428     llvm::Constant *GV;
2429     if (LangOpts.ObjCRuntime.isNonFragile()) {
2430       std::string str =
2431         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2432                             : "OBJC_CLASS_$_" + StringClass;
2433       GV = getObjCRuntime().GetClassGlobal(str);
2434       // Make sure the result is of the correct type.
2435       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2436       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2437       ConstantStringClassRef = V;
2438     } else {
2439       std::string str =
2440         StringClass.empty() ? "_NSConstantStringClassReference"
2441                             : "_" + StringClass + "ClassReference";
2442       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2443       GV = CreateRuntimeVariable(PTy, str);
2444       // Decay array -> ptr
2445       V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2446       ConstantStringClassRef = V;
2447     }
2448   }
2449   else
2450     V = ConstantStringClassRef;
2451 
2452   if (!NSConstantStringType) {
2453     // Construct the type for a constant NSString.
2454     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2455                                      Context.getTranslationUnitDecl(),
2456                                    &Context.Idents.get("__builtin_NSString"));
2457     D->startDefinition();
2458 
2459     QualType FieldTypes[3];
2460 
2461     // const int *isa;
2462     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2463     // const char *str;
2464     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2465     // unsigned int length;
2466     FieldTypes[2] = Context.UnsignedIntTy;
2467 
2468     // Create fields
2469     for (unsigned i = 0; i < 3; ++i) {
2470       FieldDecl *Field = FieldDecl::Create(Context, D,
2471                                            SourceLocation(),
2472                                            SourceLocation(), 0,
2473                                            FieldTypes[i], /*TInfo=*/0,
2474                                            /*BitWidth=*/0,
2475                                            /*Mutable=*/false,
2476                                            ICIS_NoInit);
2477       Field->setAccess(AS_public);
2478       D->addDecl(Field);
2479     }
2480 
2481     D->completeDefinition();
2482     QualType NSTy = Context.getTagDeclType(D);
2483     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2484   }
2485 
2486   llvm::Constant *Fields[3];
2487 
2488   // Class pointer.
2489   Fields[0] = cast<llvm::ConstantExpr>(V);
2490 
2491   // String pointer.
2492   llvm::Constant *C =
2493     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2494 
2495   llvm::GlobalValue::LinkageTypes Linkage;
2496   bool isConstant;
2497   Linkage = llvm::GlobalValue::PrivateLinkage;
2498   isConstant = !LangOpts.WritableStrings;
2499 
2500   llvm::GlobalVariable *GV =
2501   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2502                            ".str");
2503   GV->setUnnamedAddr(true);
2504   // Don't enforce the target's minimum global alignment, since the only use
2505   // of the string is via this class initializer.
2506   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2507   GV->setAlignment(Align.getQuantity());
2508   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2509 
2510   // String length.
2511   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2512   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2513 
2514   // The struct.
2515   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2516   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2517                                 llvm::GlobalVariable::PrivateLinkage, C,
2518                                 "_unnamed_nsstring_");
2519   // FIXME. Fix section.
2520   if (const char *Sect =
2521         LangOpts.ObjCRuntime.isNonFragile()
2522           ? getTarget().getNSStringNonFragileABISection()
2523           : getTarget().getNSStringSection())
2524     GV->setSection(Sect);
2525   Entry.setValue(GV);
2526 
2527   return GV;
2528 }
2529 
2530 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2531   if (ObjCFastEnumerationStateType.isNull()) {
2532     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2533                                      Context.getTranslationUnitDecl(),
2534                       &Context.Idents.get("__objcFastEnumerationState"));
2535     D->startDefinition();
2536 
2537     QualType FieldTypes[] = {
2538       Context.UnsignedLongTy,
2539       Context.getPointerType(Context.getObjCIdType()),
2540       Context.getPointerType(Context.UnsignedLongTy),
2541       Context.getConstantArrayType(Context.UnsignedLongTy,
2542                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2543     };
2544 
2545     for (size_t i = 0; i < 4; ++i) {
2546       FieldDecl *Field = FieldDecl::Create(Context,
2547                                            D,
2548                                            SourceLocation(),
2549                                            SourceLocation(), 0,
2550                                            FieldTypes[i], /*TInfo=*/0,
2551                                            /*BitWidth=*/0,
2552                                            /*Mutable=*/false,
2553                                            ICIS_NoInit);
2554       Field->setAccess(AS_public);
2555       D->addDecl(Field);
2556     }
2557 
2558     D->completeDefinition();
2559     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2560   }
2561 
2562   return ObjCFastEnumerationStateType;
2563 }
2564 
2565 llvm::Constant *
2566 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2567   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2568 
2569   // Don't emit it as the address of the string, emit the string data itself
2570   // as an inline array.
2571   if (E->getCharByteWidth() == 1) {
2572     SmallString<64> Str(E->getString());
2573 
2574     // Resize the string to the right size, which is indicated by its type.
2575     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2576     Str.resize(CAT->getSize().getZExtValue());
2577     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2578   }
2579 
2580   llvm::ArrayType *AType =
2581     cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2582   llvm::Type *ElemTy = AType->getElementType();
2583   unsigned NumElements = AType->getNumElements();
2584 
2585   // Wide strings have either 2-byte or 4-byte elements.
2586   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2587     SmallVector<uint16_t, 32> Elements;
2588     Elements.reserve(NumElements);
2589 
2590     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2591       Elements.push_back(E->getCodeUnit(i));
2592     Elements.resize(NumElements);
2593     return llvm::ConstantDataArray::get(VMContext, Elements);
2594   }
2595 
2596   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2597   SmallVector<uint32_t, 32> Elements;
2598   Elements.reserve(NumElements);
2599 
2600   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2601     Elements.push_back(E->getCodeUnit(i));
2602   Elements.resize(NumElements);
2603   return llvm::ConstantDataArray::get(VMContext, Elements);
2604 }
2605 
2606 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2607 /// constant array for the given string literal.
2608 llvm::Constant *
2609 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2610   CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
2611   if (S->isAscii() || S->isUTF8()) {
2612     SmallString<64> Str(S->getString());
2613 
2614     // Resize the string to the right size, which is indicated by its type.
2615     const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2616     Str.resize(CAT->getSize().getZExtValue());
2617     return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2618   }
2619 
2620   // FIXME: the following does not memoize wide strings.
2621   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2622   llvm::GlobalVariable *GV =
2623     new llvm::GlobalVariable(getModule(),C->getType(),
2624                              !LangOpts.WritableStrings,
2625                              llvm::GlobalValue::PrivateLinkage,
2626                              C,".str");
2627 
2628   GV->setAlignment(Align.getQuantity());
2629   GV->setUnnamedAddr(true);
2630   return GV;
2631 }
2632 
2633 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2634 /// array for the given ObjCEncodeExpr node.
2635 llvm::Constant *
2636 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2637   std::string Str;
2638   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2639 
2640   return GetAddrOfConstantCString(Str);
2641 }
2642 
2643 
2644 /// GenerateWritableString -- Creates storage for a string literal.
2645 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2646                                              bool constant,
2647                                              CodeGenModule &CGM,
2648                                              const char *GlobalName,
2649                                              unsigned Alignment) {
2650   // Create Constant for this string literal. Don't add a '\0'.
2651   llvm::Constant *C =
2652       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2653 
2654   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
2655   unsigned AddrSpace = 0;
2656   if (CGM.getLangOpts().OpenCL)
2657     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2658 
2659   // Create a global variable for this string
2660   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2661       CGM.getModule(), C->getType(), constant,
2662       llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0,
2663       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2664   GV->setAlignment(Alignment);
2665   GV->setUnnamedAddr(true);
2666   return GV;
2667 }
2668 
2669 /// GetAddrOfConstantString - Returns a pointer to a character array
2670 /// containing the literal. This contents are exactly that of the
2671 /// given string, i.e. it will not be null terminated automatically;
2672 /// see GetAddrOfConstantCString. Note that whether the result is
2673 /// actually a pointer to an LLVM constant depends on
2674 /// Feature.WriteableStrings.
2675 ///
2676 /// The result has pointer to array type.
2677 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2678                                                        const char *GlobalName,
2679                                                        unsigned Alignment) {
2680   // Get the default prefix if a name wasn't specified.
2681   if (!GlobalName)
2682     GlobalName = ".str";
2683 
2684   if (Alignment == 0)
2685     Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2686       .getQuantity();
2687 
2688   // Don't share any string literals if strings aren't constant.
2689   if (LangOpts.WritableStrings)
2690     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2691 
2692   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2693     ConstantStringMap.GetOrCreateValue(Str);
2694 
2695   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2696     if (Alignment > GV->getAlignment()) {
2697       GV->setAlignment(Alignment);
2698     }
2699     return GV;
2700   }
2701 
2702   // Create a global variable for this.
2703   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2704                                                    Alignment);
2705   Entry.setValue(GV);
2706   return GV;
2707 }
2708 
2709 /// GetAddrOfConstantCString - Returns a pointer to a character
2710 /// array containing the literal and a terminating '\0'
2711 /// character. The result has pointer to array type.
2712 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2713                                                         const char *GlobalName,
2714                                                         unsigned Alignment) {
2715   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2716   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2717 }
2718 
2719 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
2720     const MaterializeTemporaryExpr *E, const Expr *Init) {
2721   assert((E->getStorageDuration() == SD_Static ||
2722           E->getStorageDuration() == SD_Thread) && "not a global temporary");
2723   const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
2724 
2725   // If we're not materializing a subobject of the temporary, keep the
2726   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
2727   QualType MaterializedType = Init->getType();
2728   if (Init == E->GetTemporaryExpr())
2729     MaterializedType = E->getType();
2730 
2731   llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2732   if (Slot)
2733     return Slot;
2734 
2735   // FIXME: If an externally-visible declaration extends multiple temporaries,
2736   // we need to give each temporary the same name in every translation unit (and
2737   // we also need to make the temporaries externally-visible).
2738   SmallString<256> Name;
2739   llvm::raw_svector_ostream Out(Name);
2740   getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
2741   Out.flush();
2742 
2743   APValue *Value = 0;
2744   if (E->getStorageDuration() == SD_Static) {
2745     // We might have a cached constant initializer for this temporary. Note
2746     // that this might have a different value from the value computed by
2747     // evaluating the initializer if the surrounding constant expression
2748     // modifies the temporary.
2749     Value = getContext().getMaterializedTemporaryValue(E, false);
2750     if (Value && Value->isUninit())
2751       Value = 0;
2752   }
2753 
2754   // Try evaluating it now, it might have a constant initializer.
2755   Expr::EvalResult EvalResult;
2756   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2757       !EvalResult.hasSideEffects())
2758     Value = &EvalResult.Val;
2759 
2760   llvm::Constant *InitialValue = 0;
2761   bool Constant = false;
2762   llvm::Type *Type;
2763   if (Value) {
2764     // The temporary has a constant initializer, use it.
2765     InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
2766     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2767     Type = InitialValue->getType();
2768   } else {
2769     // No initializer, the initialization will be provided when we
2770     // initialize the declaration which performed lifetime extension.
2771     Type = getTypes().ConvertTypeForMem(MaterializedType);
2772   }
2773 
2774   // Create a global variable for this lifetime-extended temporary.
2775   llvm::GlobalVariable *GV =
2776     new llvm::GlobalVariable(getModule(), Type, Constant,
2777                              llvm::GlobalValue::PrivateLinkage,
2778                              InitialValue, Name.c_str());
2779   GV->setAlignment(
2780       getContext().getTypeAlignInChars(MaterializedType).getQuantity());
2781   if (VD->getTLSKind())
2782     setTLSMode(GV, *VD);
2783   Slot = GV;
2784   return GV;
2785 }
2786 
2787 /// EmitObjCPropertyImplementations - Emit information for synthesized
2788 /// properties for an implementation.
2789 void CodeGenModule::EmitObjCPropertyImplementations(const
2790                                                     ObjCImplementationDecl *D) {
2791   for (ObjCImplementationDecl::propimpl_iterator
2792          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2793     ObjCPropertyImplDecl *PID = *i;
2794 
2795     // Dynamic is just for type-checking.
2796     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2797       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2798 
2799       // Determine which methods need to be implemented, some may have
2800       // been overridden. Note that ::isPropertyAccessor is not the method
2801       // we want, that just indicates if the decl came from a
2802       // property. What we want to know is if the method is defined in
2803       // this implementation.
2804       if (!D->getInstanceMethod(PD->getGetterName()))
2805         CodeGenFunction(*this).GenerateObjCGetter(
2806                                  const_cast<ObjCImplementationDecl *>(D), PID);
2807       if (!PD->isReadOnly() &&
2808           !D->getInstanceMethod(PD->getSetterName()))
2809         CodeGenFunction(*this).GenerateObjCSetter(
2810                                  const_cast<ObjCImplementationDecl *>(D), PID);
2811     }
2812   }
2813 }
2814 
2815 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2816   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2817   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2818        ivar; ivar = ivar->getNextIvar())
2819     if (ivar->getType().isDestructedType())
2820       return true;
2821 
2822   return false;
2823 }
2824 
2825 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2826 /// for an implementation.
2827 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2828   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2829   if (needsDestructMethod(D)) {
2830     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2831     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2832     ObjCMethodDecl *DTORMethod =
2833       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2834                              cxxSelector, getContext().VoidTy, 0, D,
2835                              /*isInstance=*/true, /*isVariadic=*/false,
2836                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2837                              /*isDefined=*/false, ObjCMethodDecl::Required);
2838     D->addInstanceMethod(DTORMethod);
2839     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2840     D->setHasDestructors(true);
2841   }
2842 
2843   // If the implementation doesn't have any ivar initializers, we don't need
2844   // a .cxx_construct.
2845   if (D->getNumIvarInitializers() == 0)
2846     return;
2847 
2848   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2849   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2850   // The constructor returns 'self'.
2851   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2852                                                 D->getLocation(),
2853                                                 D->getLocation(),
2854                                                 cxxSelector,
2855                                                 getContext().getObjCIdType(), 0,
2856                                                 D, /*isInstance=*/true,
2857                                                 /*isVariadic=*/false,
2858                                                 /*isPropertyAccessor=*/true,
2859                                                 /*isImplicitlyDeclared=*/true,
2860                                                 /*isDefined=*/false,
2861                                                 ObjCMethodDecl::Required);
2862   D->addInstanceMethod(CTORMethod);
2863   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2864   D->setHasNonZeroConstructors(true);
2865 }
2866 
2867 /// EmitNamespace - Emit all declarations in a namespace.
2868 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2869   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2870        I != E; ++I) {
2871     if (const VarDecl *VD = dyn_cast<VarDecl>(*I))
2872       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2873           VD->getTemplateSpecializationKind() != TSK_Undeclared)
2874         continue;
2875     EmitTopLevelDecl(*I);
2876   }
2877 }
2878 
2879 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2880 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2881   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2882       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2883     ErrorUnsupported(LSD, "linkage spec");
2884     return;
2885   }
2886 
2887   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2888        I != E; ++I) {
2889     // Meta-data for ObjC class includes references to implemented methods.
2890     // Generate class's method definitions first.
2891     if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2892       for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2893            MEnd = OID->meth_end();
2894            M != MEnd; ++M)
2895         EmitTopLevelDecl(*M);
2896     }
2897     EmitTopLevelDecl(*I);
2898   }
2899 }
2900 
2901 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2902 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2903   // Ignore dependent declarations.
2904   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2905     return;
2906 
2907   switch (D->getKind()) {
2908   case Decl::CXXConversion:
2909   case Decl::CXXMethod:
2910   case Decl::Function:
2911     // Skip function templates
2912     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2913         cast<FunctionDecl>(D)->isLateTemplateParsed())
2914       return;
2915 
2916     EmitGlobal(cast<FunctionDecl>(D));
2917     break;
2918 
2919   case Decl::Var:
2920     // Skip variable templates
2921     if (cast<VarDecl>(D)->getDescribedVarTemplate())
2922       return;
2923   case Decl::VarTemplateSpecialization:
2924     EmitGlobal(cast<VarDecl>(D));
2925     break;
2926 
2927   // Indirect fields from global anonymous structs and unions can be
2928   // ignored; only the actual variable requires IR gen support.
2929   case Decl::IndirectField:
2930     break;
2931 
2932   // C++ Decls
2933   case Decl::Namespace:
2934     EmitNamespace(cast<NamespaceDecl>(D));
2935     break;
2936     // No code generation needed.
2937   case Decl::UsingShadow:
2938   case Decl::Using:
2939   case Decl::ClassTemplate:
2940   case Decl::VarTemplate:
2941   case Decl::VarTemplatePartialSpecialization:
2942   case Decl::FunctionTemplate:
2943   case Decl::TypeAliasTemplate:
2944   case Decl::Block:
2945   case Decl::Empty:
2946     break;
2947   case Decl::NamespaceAlias:
2948     if (CGDebugInfo *DI = getModuleDebugInfo())
2949         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
2950     return;
2951   case Decl::UsingDirective: // using namespace X; [C++]
2952     if (CGDebugInfo *DI = getModuleDebugInfo())
2953       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2954     return;
2955   case Decl::CXXConstructor:
2956     // Skip function templates
2957     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2958         cast<FunctionDecl>(D)->isLateTemplateParsed())
2959       return;
2960 
2961     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2962     break;
2963   case Decl::CXXDestructor:
2964     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2965       return;
2966     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2967     break;
2968 
2969   case Decl::StaticAssert:
2970     // Nothing to do.
2971     break;
2972 
2973   // Objective-C Decls
2974 
2975   // Forward declarations, no (immediate) code generation.
2976   case Decl::ObjCInterface:
2977   case Decl::ObjCCategory:
2978     break;
2979 
2980   case Decl::ObjCProtocol: {
2981     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2982     if (Proto->isThisDeclarationADefinition())
2983       ObjCRuntime->GenerateProtocol(Proto);
2984     break;
2985   }
2986 
2987   case Decl::ObjCCategoryImpl:
2988     // Categories have properties but don't support synthesize so we
2989     // can ignore them here.
2990     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2991     break;
2992 
2993   case Decl::ObjCImplementation: {
2994     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2995     EmitObjCPropertyImplementations(OMD);
2996     EmitObjCIvarInitializations(OMD);
2997     ObjCRuntime->GenerateClass(OMD);
2998     // Emit global variable debug information.
2999     if (CGDebugInfo *DI = getModuleDebugInfo())
3000       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3001         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3002             OMD->getClassInterface()), OMD->getLocation());
3003     break;
3004   }
3005   case Decl::ObjCMethod: {
3006     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
3007     // If this is not a prototype, emit the body.
3008     if (OMD->getBody())
3009       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3010     break;
3011   }
3012   case Decl::ObjCCompatibleAlias:
3013     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3014     break;
3015 
3016   case Decl::LinkageSpec:
3017     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3018     break;
3019 
3020   case Decl::FileScopeAsm: {
3021     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
3022     StringRef AsmString = AD->getAsmString()->getString();
3023 
3024     const std::string &S = getModule().getModuleInlineAsm();
3025     if (S.empty())
3026       getModule().setModuleInlineAsm(AsmString);
3027     else if (S.end()[-1] == '\n')
3028       getModule().setModuleInlineAsm(S + AsmString.str());
3029     else
3030       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
3031     break;
3032   }
3033 
3034   case Decl::Import: {
3035     ImportDecl *Import = cast<ImportDecl>(D);
3036 
3037     // Ignore import declarations that come from imported modules.
3038     if (clang::Module *Owner = Import->getOwningModule()) {
3039       if (getLangOpts().CurrentModule.empty() ||
3040           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3041         break;
3042     }
3043 
3044     ImportedModules.insert(Import->getImportedModule());
3045     break;
3046  }
3047 
3048   default:
3049     // Make sure we handled everything we should, every other kind is a
3050     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3051     // function. Need to recode Decl::Kind to do that easily.
3052     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3053   }
3054 }
3055 
3056 /// Turns the given pointer into a constant.
3057 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3058                                           const void *Ptr) {
3059   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3060   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3061   return llvm::ConstantInt::get(i64, PtrInt);
3062 }
3063 
3064 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3065                                    llvm::NamedMDNode *&GlobalMetadata,
3066                                    GlobalDecl D,
3067                                    llvm::GlobalValue *Addr) {
3068   if (!GlobalMetadata)
3069     GlobalMetadata =
3070       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3071 
3072   // TODO: should we report variant information for ctors/dtors?
3073   llvm::Value *Ops[] = {
3074     Addr,
3075     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3076   };
3077   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3078 }
3079 
3080 /// For each function which is declared within an extern "C" region and marked
3081 /// as 'used', but has internal linkage, create an alias from the unmangled
3082 /// name to the mangled name if possible. People expect to be able to refer
3083 /// to such functions with an unmangled name from inline assembly within the
3084 /// same translation unit.
3085 void CodeGenModule::EmitStaticExternCAliases() {
3086   for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3087                                   E = StaticExternCValues.end();
3088        I != E; ++I) {
3089     IdentifierInfo *Name = I->first;
3090     llvm::GlobalValue *Val = I->second;
3091     if (Val && !getModule().getNamedValue(Name->getName()))
3092       AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
3093                                           Name->getName(), Val, &getModule()));
3094   }
3095 }
3096 
3097 /// Emits metadata nodes associating all the global values in the
3098 /// current module with the Decls they came from.  This is useful for
3099 /// projects using IR gen as a subroutine.
3100 ///
3101 /// Since there's currently no way to associate an MDNode directly
3102 /// with an llvm::GlobalValue, we create a global named metadata
3103 /// with the name 'clang.global.decl.ptrs'.
3104 void CodeGenModule::EmitDeclMetadata() {
3105   llvm::NamedMDNode *GlobalMetadata = 0;
3106 
3107   // StaticLocalDeclMap
3108   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
3109          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3110        I != E; ++I) {
3111     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3112     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3113   }
3114 }
3115 
3116 /// Emits metadata nodes for all the local variables in the current
3117 /// function.
3118 void CodeGenFunction::EmitDeclMetadata() {
3119   if (LocalDeclMap.empty()) return;
3120 
3121   llvm::LLVMContext &Context = getLLVMContext();
3122 
3123   // Find the unique metadata ID for this name.
3124   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3125 
3126   llvm::NamedMDNode *GlobalMetadata = 0;
3127 
3128   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3129          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3130     const Decl *D = I->first;
3131     llvm::Value *Addr = I->second;
3132 
3133     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3134       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3135       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3136     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3137       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3138       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3139     }
3140   }
3141 }
3142 
3143 void CodeGenModule::EmitVersionIdentMetadata() {
3144   llvm::NamedMDNode *IdentMetadata =
3145     TheModule.getOrInsertNamedMetadata("llvm.ident");
3146   std::string Version = getClangFullVersion();
3147   llvm::LLVMContext &Ctx = TheModule.getContext();
3148 
3149   llvm::Value *IdentNode[] = {
3150     llvm::MDString::get(Ctx, Version)
3151   };
3152   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3153 }
3154 
3155 void CodeGenModule::EmitCoverageFile() {
3156   if (!getCodeGenOpts().CoverageFile.empty()) {
3157     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3158       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3159       llvm::LLVMContext &Ctx = TheModule.getContext();
3160       llvm::MDString *CoverageFile =
3161           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3162       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3163         llvm::MDNode *CU = CUNode->getOperand(i);
3164         llvm::Value *node[] = { CoverageFile, CU };
3165         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3166         GCov->addOperand(N);
3167       }
3168     }
3169   }
3170 }
3171 
3172 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3173                                                      QualType GuidType) {
3174   // Sema has checked that all uuid strings are of the form
3175   // "12345678-1234-1234-1234-1234567890ab".
3176   assert(Uuid.size() == 36);
3177   for (unsigned i = 0; i < 36; ++i) {
3178     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3179     else                                         assert(isHexDigit(Uuid[i]));
3180   }
3181 
3182   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3183 
3184   llvm::Constant *Field3[8];
3185   for (unsigned Idx = 0; Idx < 8; ++Idx)
3186     Field3[Idx] = llvm::ConstantInt::get(
3187         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3188 
3189   llvm::Constant *Fields[4] = {
3190     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3191     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3192     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3193     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3194   };
3195 
3196   return llvm::ConstantStruct::getAnon(Fields);
3197 }
3198