xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision f44bdf9c5fc347f1639d50c49de2b836f28017e2)
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 "CGDebugInfo.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenTBAA.h"
18 #include "CGCall.h"
19 #include "CGCUDARuntime.h"
20 #include "CGCXXABI.h"
21 #include "CGObjCRuntime.h"
22 #include "CGOpenCLRuntime.h"
23 #include "TargetInfo.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/CharUnits.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclCXX.h"
29 #include "clang/AST/DeclTemplate.h"
30 #include "clang/AST/Mangle.h"
31 #include "clang/AST/RecordLayout.h"
32 #include "clang/AST/RecursiveASTVisitor.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/Diagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "clang/Basic/ConvertUTF.h"
38 #include "llvm/CallingConv.h"
39 #include "llvm/Module.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/LLVMContext.h"
42 #include "llvm/ADT/APSInt.h"
43 #include "llvm/ADT/Triple.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ErrorHandling.h"
48 using namespace clang;
49 using namespace CodeGen;
50 
51 static const char AnnotationSection[] = "llvm.metadata";
52 
53 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
54   switch (CGM.getContext().getTargetInfo().getCXXABI()) {
55   case CXXABI_ARM: return *CreateARMCXXABI(CGM);
56   case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
57   case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
58   }
59 
60   llvm_unreachable("invalid C++ ABI kind");
61 }
62 
63 
64 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
65                              llvm::Module &M, const llvm::TargetData &TD,
66                              DiagnosticsEngine &diags)
67   : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
68     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
69     ABI(createCXXABI(*this)),
70     Types(*this),
71     TBAA(0),
72     VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
73     DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
74     RRData(0), CFConstantStringClassRef(0),
75     ConstantStringClassRef(0), NSConstantStringType(0),
76     VMContext(M.getContext()),
77     NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
78     BlockObjectAssign(0), BlockObjectDispose(0),
79     BlockDescriptorType(0), GenericBlockLiteralType(0) {
80 
81   // Initialize the type cache.
82   llvm::LLVMContext &LLVMContext = M.getContext();
83   VoidTy = llvm::Type::getVoidTy(LLVMContext);
84   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
85   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
86   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
87   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
88   FloatTy = llvm::Type::getFloatTy(LLVMContext);
89   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
90   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
91   PointerAlignInBytes =
92   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
93   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
94   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
95   Int8PtrTy = Int8Ty->getPointerTo(0);
96   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
97 
98   if (LangOpts.ObjC1)
99     createObjCRuntime();
100   if (LangOpts.OpenCL)
101     createOpenCLRuntime();
102   if (LangOpts.CUDA)
103     createCUDARuntime();
104 
105   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
106   if (LangOpts.ThreadSanitizer ||
107       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
108     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
109                            ABI.getMangleContext());
110 
111   // If debug info or coverage generation is enabled, create the CGDebugInfo
112   // object.
113   if (CodeGenOpts.DebugInfo != CodeGenOptions::NoDebugInfo ||
114       CodeGenOpts.EmitGcovArcs ||
115       CodeGenOpts.EmitGcovNotes)
116     DebugInfo = new CGDebugInfo(*this);
117 
118   Block.GlobalUniqueCount = 0;
119 
120   if (C.getLangOpts().ObjCAutoRefCount)
121     ARCData = new ARCEntrypoints();
122   RRData = new RREntrypoints();
123 }
124 
125 CodeGenModule::~CodeGenModule() {
126   delete ObjCRuntime;
127   delete OpenCLRuntime;
128   delete CUDARuntime;
129   delete TheTargetCodeGenInfo;
130   delete &ABI;
131   delete TBAA;
132   delete DebugInfo;
133   delete ARCData;
134   delete RRData;
135 }
136 
137 void CodeGenModule::createObjCRuntime() {
138   if (!LangOpts.NeXTRuntime)
139     ObjCRuntime = CreateGNUObjCRuntime(*this);
140   else
141     ObjCRuntime = CreateMacObjCRuntime(*this);
142 }
143 
144 void CodeGenModule::createOpenCLRuntime() {
145   OpenCLRuntime = new CGOpenCLRuntime(*this);
146 }
147 
148 void CodeGenModule::createCUDARuntime() {
149   CUDARuntime = CreateNVCUDARuntime(*this);
150 }
151 
152 void CodeGenModule::Release() {
153   EmitDeferred();
154   EmitCXXGlobalInitFunc();
155   EmitCXXGlobalDtorFunc();
156   if (ObjCRuntime)
157     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
158       AddGlobalCtor(ObjCInitFunction);
159   EmitCtorList(GlobalCtors, "llvm.global_ctors");
160   EmitCtorList(GlobalDtors, "llvm.global_dtors");
161   EmitGlobalAnnotations();
162   EmitLLVMUsed();
163 
164   SimplifyPersonality();
165 
166   if (getCodeGenOpts().EmitDeclMetadata)
167     EmitDeclMetadata();
168 
169   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
170     EmitCoverageFile();
171 
172   if (DebugInfo)
173     DebugInfo->finalize();
174 }
175 
176 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
177   // Make sure that this type is translated.
178   Types.UpdateCompletedType(TD);
179 }
180 
181 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
182   if (!TBAA)
183     return 0;
184   return TBAA->getTBAAInfo(QTy);
185 }
186 
187 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
188   if (!TBAA)
189     return 0;
190   return TBAA->getTBAAInfoForVTablePtr();
191 }
192 
193 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
194                                         llvm::MDNode *TBAAInfo) {
195   Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
196 }
197 
198 bool CodeGenModule::isTargetDarwin() const {
199   return getContext().getTargetInfo().getTriple().isOSDarwin();
200 }
201 
202 void CodeGenModule::Error(SourceLocation loc, StringRef error) {
203   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
204   getDiags().Report(Context.getFullLoc(loc), diagID);
205 }
206 
207 /// ErrorUnsupported - Print out an error that codegen doesn't support the
208 /// specified stmt yet.
209 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
210                                      bool OmitOnError) {
211   if (OmitOnError && getDiags().hasErrorOccurred())
212     return;
213   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
214                                                "cannot compile this %0 yet");
215   std::string Msg = Type;
216   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
217     << Msg << S->getSourceRange();
218 }
219 
220 /// ErrorUnsupported - Print out an error that codegen doesn't support the
221 /// specified decl yet.
222 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
223                                      bool OmitOnError) {
224   if (OmitOnError && getDiags().hasErrorOccurred())
225     return;
226   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
227                                                "cannot compile this %0 yet");
228   std::string Msg = Type;
229   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
230 }
231 
232 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
233   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
234 }
235 
236 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
237                                         const NamedDecl *D) const {
238   // Internal definitions always have default visibility.
239   if (GV->hasLocalLinkage()) {
240     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
241     return;
242   }
243 
244   // Set visibility for definitions.
245   NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
246   if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
247     GV->setVisibility(GetLLVMVisibility(LV.visibility()));
248 }
249 
250 /// Set the symbol visibility of type information (vtable and RTTI)
251 /// associated with the given type.
252 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
253                                       const CXXRecordDecl *RD,
254                                       TypeVisibilityKind TVK) const {
255   setGlobalVisibility(GV, RD);
256 
257   if (!CodeGenOpts.HiddenWeakVTables)
258     return;
259 
260   // We never want to drop the visibility for RTTI names.
261   if (TVK == TVK_ForRTTIName)
262     return;
263 
264   // We want to drop the visibility to hidden for weak type symbols.
265   // This isn't possible if there might be unresolved references
266   // elsewhere that rely on this symbol being visible.
267 
268   // This should be kept roughly in sync with setThunkVisibility
269   // in CGVTables.cpp.
270 
271   // Preconditions.
272   if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
273       GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
274     return;
275 
276   // Don't override an explicit visibility attribute.
277   if (RD->getExplicitVisibility())
278     return;
279 
280   switch (RD->getTemplateSpecializationKind()) {
281   // We have to disable the optimization if this is an EI definition
282   // because there might be EI declarations in other shared objects.
283   case TSK_ExplicitInstantiationDefinition:
284   case TSK_ExplicitInstantiationDeclaration:
285     return;
286 
287   // Every use of a non-template class's type information has to emit it.
288   case TSK_Undeclared:
289     break;
290 
291   // In theory, implicit instantiations can ignore the possibility of
292   // an explicit instantiation declaration because there necessarily
293   // must be an EI definition somewhere with default visibility.  In
294   // practice, it's possible to have an explicit instantiation for
295   // an arbitrary template class, and linkers aren't necessarily able
296   // to deal with mixed-visibility symbols.
297   case TSK_ExplicitSpecialization:
298   case TSK_ImplicitInstantiation:
299     if (!CodeGenOpts.HiddenWeakTemplateVTables)
300       return;
301     break;
302   }
303 
304   // If there's a key function, there may be translation units
305   // that don't have the key function's definition.  But ignore
306   // this if we're emitting RTTI under -fno-rtti.
307   if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
308     if (Context.getKeyFunction(RD))
309       return;
310   }
311 
312   // Otherwise, drop the visibility to hidden.
313   GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
314   GV->setUnnamedAddr(true);
315 }
316 
317 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
318   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
319 
320   StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
321   if (!Str.empty())
322     return Str;
323 
324   if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
325     IdentifierInfo *II = ND->getIdentifier();
326     assert(II && "Attempt to mangle unnamed decl.");
327 
328     Str = II->getName();
329     return Str;
330   }
331 
332   SmallString<256> Buffer;
333   llvm::raw_svector_ostream Out(Buffer);
334   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
335     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
336   else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
337     getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
338   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
339     getCXXABI().getMangleContext().mangleBlock(BD, Out);
340   else
341     getCXXABI().getMangleContext().mangleName(ND, Out);
342 
343   // Allocate space for the mangled name.
344   Out.flush();
345   size_t Length = Buffer.size();
346   char *Name = MangledNamesAllocator.Allocate<char>(Length);
347   std::copy(Buffer.begin(), Buffer.end(), Name);
348 
349   Str = StringRef(Name, Length);
350 
351   return Str;
352 }
353 
354 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
355                                         const BlockDecl *BD) {
356   MangleContext &MangleCtx = getCXXABI().getMangleContext();
357   const Decl *D = GD.getDecl();
358   llvm::raw_svector_ostream Out(Buffer.getBuffer());
359   if (D == 0)
360     MangleCtx.mangleGlobalBlock(BD, Out);
361   else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
362     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
363   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
364     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
365   else
366     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
367 }
368 
369 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
370   return getModule().getNamedValue(Name);
371 }
372 
373 /// AddGlobalCtor - Add a function to the list that will be called before
374 /// main() runs.
375 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
376   // FIXME: Type coercion of void()* types.
377   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
378 }
379 
380 /// AddGlobalDtor - Add a function to the list that will be called
381 /// when the module is unloaded.
382 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
383   // FIXME: Type coercion of void()* types.
384   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
385 }
386 
387 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
388   // Ctor function type is void()*.
389   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
390   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
391 
392   // Get the type of a ctor entry, { i32, void ()* }.
393   llvm::StructType *CtorStructTy =
394     llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
395 
396   // Construct the constructor and destructor arrays.
397   SmallVector<llvm::Constant*, 8> Ctors;
398   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
399     llvm::Constant *S[] = {
400       llvm::ConstantInt::get(Int32Ty, I->second, false),
401       llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
402     };
403     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
404   }
405 
406   if (!Ctors.empty()) {
407     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
408     new llvm::GlobalVariable(TheModule, AT, false,
409                              llvm::GlobalValue::AppendingLinkage,
410                              llvm::ConstantArray::get(AT, Ctors),
411                              GlobalName);
412   }
413 }
414 
415 llvm::GlobalValue::LinkageTypes
416 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
417   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
418 
419   if (Linkage == GVA_Internal)
420     return llvm::Function::InternalLinkage;
421 
422   if (D->hasAttr<DLLExportAttr>())
423     return llvm::Function::DLLExportLinkage;
424 
425   if (D->hasAttr<WeakAttr>())
426     return llvm::Function::WeakAnyLinkage;
427 
428   // In C99 mode, 'inline' functions are guaranteed to have a strong
429   // definition somewhere else, so we can use available_externally linkage.
430   if (Linkage == GVA_C99Inline)
431     return llvm::Function::AvailableExternallyLinkage;
432 
433   // Note that Apple's kernel linker doesn't support symbol
434   // coalescing, so we need to avoid linkonce and weak linkages there.
435   // Normally, this means we just map to internal, but for explicit
436   // instantiations we'll map to external.
437 
438   // In C++, the compiler has to emit a definition in every translation unit
439   // that references the function.  We should use linkonce_odr because
440   // a) if all references in this translation unit are optimized away, we
441   // don't need to codegen it.  b) if the function persists, it needs to be
442   // merged with other definitions. c) C++ has the ODR, so we know the
443   // definition is dependable.
444   if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
445     return !Context.getLangOpts().AppleKext
446              ? llvm::Function::LinkOnceODRLinkage
447              : llvm::Function::InternalLinkage;
448 
449   // An explicit instantiation of a template has weak linkage, since
450   // explicit instantiations can occur in multiple translation units
451   // and must all be equivalent. However, we are not allowed to
452   // throw away these explicit instantiations.
453   if (Linkage == GVA_ExplicitTemplateInstantiation)
454     return !Context.getLangOpts().AppleKext
455              ? llvm::Function::WeakODRLinkage
456              : llvm::Function::ExternalLinkage;
457 
458   // Otherwise, we have strong external linkage.
459   assert(Linkage == GVA_StrongExternal);
460   return llvm::Function::ExternalLinkage;
461 }
462 
463 
464 /// SetFunctionDefinitionAttributes - Set attributes for a global.
465 ///
466 /// FIXME: This is currently only done for aliases and functions, but not for
467 /// variables (these details are set in EmitGlobalVarDefinition for variables).
468 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
469                                                     llvm::GlobalValue *GV) {
470   SetCommonAttributes(D, GV);
471 }
472 
473 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
474                                               const CGFunctionInfo &Info,
475                                               llvm::Function *F) {
476   unsigned CallingConv;
477   AttributeListType AttributeList;
478   ConstructAttributeList(Info, D, AttributeList, CallingConv);
479   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
480                                           AttributeList.size()));
481   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
482 }
483 
484 /// Determines whether the language options require us to model
485 /// unwind exceptions.  We treat -fexceptions as mandating this
486 /// except under the fragile ObjC ABI with only ObjC exceptions
487 /// enabled.  This means, for example, that C with -fexceptions
488 /// enables this.
489 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
490   // If exceptions are completely disabled, obviously this is false.
491   if (!LangOpts.Exceptions) return false;
492 
493   // If C++ exceptions are enabled, this is true.
494   if (LangOpts.CXXExceptions) return true;
495 
496   // If ObjC exceptions are enabled, this depends on the ABI.
497   if (LangOpts.ObjCExceptions) {
498     if (!LangOpts.ObjCNonFragileABI) return false;
499   }
500 
501   return true;
502 }
503 
504 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
505                                                            llvm::Function *F) {
506   if (CodeGenOpts.UnwindTables)
507     F->setHasUWTable();
508 
509   if (!hasUnwindExceptions(LangOpts))
510     F->addFnAttr(llvm::Attribute::NoUnwind);
511 
512   if (D->hasAttr<NakedAttr>()) {
513     // Naked implies noinline: we should not be inlining such functions.
514     F->addFnAttr(llvm::Attribute::Naked);
515     F->addFnAttr(llvm::Attribute::NoInline);
516   }
517 
518   if (D->hasAttr<NoInlineAttr>())
519     F->addFnAttr(llvm::Attribute::NoInline);
520 
521   // (noinline wins over always_inline, and we can't specify both in IR)
522   if (D->hasAttr<AlwaysInlineAttr>() &&
523       !F->hasFnAttr(llvm::Attribute::NoInline))
524     F->addFnAttr(llvm::Attribute::AlwaysInline);
525 
526   // FIXME: Communicate hot and cold attributes to LLVM more directly.
527   if (D->hasAttr<ColdAttr>())
528     F->addFnAttr(llvm::Attribute::OptimizeForSize);
529 
530   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
531     F->setUnnamedAddr(true);
532 
533   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
534     F->addFnAttr(llvm::Attribute::StackProtect);
535   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
536     F->addFnAttr(llvm::Attribute::StackProtectReq);
537 
538   if (LangOpts.AddressSanitizer) {
539     // When AddressSanitizer is enabled, set AddressSafety attribute
540     // unless __attribute__((no_address_safety_analysis)) is used.
541     if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
542       F->addFnAttr(llvm::Attribute::AddressSafety);
543   }
544 
545   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
546   if (alignment)
547     F->setAlignment(alignment);
548 
549   // C++ ABI requires 2-byte alignment for member functions.
550   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
551     F->setAlignment(2);
552 }
553 
554 void CodeGenModule::SetCommonAttributes(const Decl *D,
555                                         llvm::GlobalValue *GV) {
556   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
557     setGlobalVisibility(GV, ND);
558   else
559     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
560 
561   if (D->hasAttr<UsedAttr>())
562     AddUsedGlobal(GV);
563 
564   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
565     GV->setSection(SA->getName());
566 
567   getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
568 }
569 
570 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
571                                                   llvm::Function *F,
572                                                   const CGFunctionInfo &FI) {
573   SetLLVMFunctionAttributes(D, FI, F);
574   SetLLVMFunctionAttributesForDefinition(D, F);
575 
576   F->setLinkage(llvm::Function::InternalLinkage);
577 
578   SetCommonAttributes(D, F);
579 }
580 
581 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
582                                           llvm::Function *F,
583                                           bool IsIncompleteFunction) {
584   if (unsigned IID = F->getIntrinsicID()) {
585     // If this is an intrinsic function, set the function's attributes
586     // to the intrinsic's attributes.
587     F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
588     return;
589   }
590 
591   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
592 
593   if (!IsIncompleteFunction)
594     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
595 
596   // Only a few attributes are set on declarations; these may later be
597   // overridden by a definition.
598 
599   if (FD->hasAttr<DLLImportAttr>()) {
600     F->setLinkage(llvm::Function::DLLImportLinkage);
601   } else if (FD->hasAttr<WeakAttr>() ||
602              FD->isWeakImported()) {
603     // "extern_weak" is overloaded in LLVM; we probably should have
604     // separate linkage types for this.
605     F->setLinkage(llvm::Function::ExternalWeakLinkage);
606   } else {
607     F->setLinkage(llvm::Function::ExternalLinkage);
608 
609     NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
610     if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
611       F->setVisibility(GetLLVMVisibility(LV.visibility()));
612     }
613   }
614 
615   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
616     F->setSection(SA->getName());
617 }
618 
619 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
620   assert(!GV->isDeclaration() &&
621          "Only globals with definition can force usage.");
622   LLVMUsed.push_back(GV);
623 }
624 
625 void CodeGenModule::EmitLLVMUsed() {
626   // Don't create llvm.used if there is no need.
627   if (LLVMUsed.empty())
628     return;
629 
630   // Convert LLVMUsed to what ConstantArray needs.
631   SmallVector<llvm::Constant*, 8> UsedArray;
632   UsedArray.resize(LLVMUsed.size());
633   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
634     UsedArray[i] =
635      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
636                                     Int8PtrTy);
637   }
638 
639   if (UsedArray.empty())
640     return;
641   llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
642 
643   llvm::GlobalVariable *GV =
644     new llvm::GlobalVariable(getModule(), ATy, false,
645                              llvm::GlobalValue::AppendingLinkage,
646                              llvm::ConstantArray::get(ATy, UsedArray),
647                              "llvm.used");
648 
649   GV->setSection("llvm.metadata");
650 }
651 
652 void CodeGenModule::EmitDeferred() {
653   // Emit code for any potentially referenced deferred decls.  Since a
654   // previously unused static decl may become used during the generation of code
655   // for a static function, iterate until no changes are made.
656 
657   while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
658     if (!DeferredVTables.empty()) {
659       const CXXRecordDecl *RD = DeferredVTables.back();
660       DeferredVTables.pop_back();
661       getVTables().GenerateClassData(getVTableLinkage(RD), RD);
662       continue;
663     }
664 
665     GlobalDecl D = DeferredDeclsToEmit.back();
666     DeferredDeclsToEmit.pop_back();
667 
668     // Check to see if we've already emitted this.  This is necessary
669     // for a couple of reasons: first, decls can end up in the
670     // deferred-decls queue multiple times, and second, decls can end
671     // up with definitions in unusual ways (e.g. by an extern inline
672     // function acquiring a strong function redefinition).  Just
673     // ignore these cases.
674     //
675     // TODO: That said, looking this up multiple times is very wasteful.
676     StringRef Name = getMangledName(D);
677     llvm::GlobalValue *CGRef = GetGlobalValue(Name);
678     assert(CGRef && "Deferred decl wasn't referenced?");
679 
680     if (!CGRef->isDeclaration())
681       continue;
682 
683     // GlobalAlias::isDeclaration() defers to the aliasee, but for our
684     // purposes an alias counts as a definition.
685     if (isa<llvm::GlobalAlias>(CGRef))
686       continue;
687 
688     // Otherwise, emit the definition and move on to the next one.
689     EmitGlobalDefinition(D);
690   }
691 }
692 
693 void CodeGenModule::EmitGlobalAnnotations() {
694   if (Annotations.empty())
695     return;
696 
697   // Create a new global variable for the ConstantStruct in the Module.
698   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
699     Annotations[0]->getType(), Annotations.size()), Annotations);
700   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
701     Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
702     "llvm.global.annotations");
703   gv->setSection(AnnotationSection);
704 }
705 
706 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
707   llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
708   if (i != AnnotationStrings.end())
709     return i->second;
710 
711   // Not found yet, create a new global.
712   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
713   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
714     true, llvm::GlobalValue::PrivateLinkage, s, ".str");
715   gv->setSection(AnnotationSection);
716   gv->setUnnamedAddr(true);
717   AnnotationStrings[Str] = gv;
718   return gv;
719 }
720 
721 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
722   SourceManager &SM = getContext().getSourceManager();
723   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
724   if (PLoc.isValid())
725     return EmitAnnotationString(PLoc.getFilename());
726   return EmitAnnotationString(SM.getBufferName(Loc));
727 }
728 
729 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
730   SourceManager &SM = getContext().getSourceManager();
731   PresumedLoc PLoc = SM.getPresumedLoc(L);
732   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
733     SM.getExpansionLineNumber(L);
734   return llvm::ConstantInt::get(Int32Ty, LineNo);
735 }
736 
737 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
738                                                 const AnnotateAttr *AA,
739                                                 SourceLocation L) {
740   // Get the globals for file name, annotation, and the line number.
741   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
742                  *UnitGV = EmitAnnotationUnit(L),
743                  *LineNoCst = EmitAnnotationLineNo(L);
744 
745   // Create the ConstantStruct for the global annotation.
746   llvm::Constant *Fields[4] = {
747     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
748     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
749     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
750     LineNoCst
751   };
752   return llvm::ConstantStruct::getAnon(Fields);
753 }
754 
755 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
756                                          llvm::GlobalValue *GV) {
757   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
758   // Get the struct elements for these annotations.
759   for (specific_attr_iterator<AnnotateAttr>
760        ai = D->specific_attr_begin<AnnotateAttr>(),
761        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
762     Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
763 }
764 
765 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
766   // Never defer when EmitAllDecls is specified.
767   if (LangOpts.EmitAllDecls)
768     return false;
769 
770   return !getContext().DeclMustBeEmitted(Global);
771 }
772 
773 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
774   const AliasAttr *AA = VD->getAttr<AliasAttr>();
775   assert(AA && "No alias?");
776 
777   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
778 
779   // See if there is already something with the target's name in the module.
780   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
781 
782   llvm::Constant *Aliasee;
783   if (isa<llvm::FunctionType>(DeclTy))
784     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
785                                       /*ForVTable=*/false);
786   else
787     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
788                                     llvm::PointerType::getUnqual(DeclTy), 0);
789   if (!Entry) {
790     llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
791     F->setLinkage(llvm::Function::ExternalWeakLinkage);
792     WeakRefReferences.insert(F);
793   }
794 
795   return Aliasee;
796 }
797 
798 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
799   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
800 
801   // Weak references don't produce any output by themselves.
802   if (Global->hasAttr<WeakRefAttr>())
803     return;
804 
805   // If this is an alias definition (which otherwise looks like a declaration)
806   // emit it now.
807   if (Global->hasAttr<AliasAttr>())
808     return EmitAliasDefinition(GD);
809 
810   // If this is CUDA, be selective about which declarations we emit.
811   if (LangOpts.CUDA) {
812     if (CodeGenOpts.CUDAIsDevice) {
813       if (!Global->hasAttr<CUDADeviceAttr>() &&
814           !Global->hasAttr<CUDAGlobalAttr>() &&
815           !Global->hasAttr<CUDAConstantAttr>() &&
816           !Global->hasAttr<CUDASharedAttr>())
817         return;
818     } else {
819       if (!Global->hasAttr<CUDAHostAttr>() && (
820             Global->hasAttr<CUDADeviceAttr>() ||
821             Global->hasAttr<CUDAConstantAttr>() ||
822             Global->hasAttr<CUDASharedAttr>()))
823         return;
824     }
825   }
826 
827   // Ignore declarations, they will be emitted on their first use.
828   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
829     // Forward declarations are emitted lazily on first use.
830     if (!FD->doesThisDeclarationHaveABody()) {
831       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
832         return;
833 
834       const FunctionDecl *InlineDefinition = 0;
835       FD->getBody(InlineDefinition);
836 
837       StringRef MangledName = getMangledName(GD);
838       DeferredDecls.erase(MangledName);
839       EmitGlobalDefinition(InlineDefinition);
840       return;
841     }
842   } else {
843     const VarDecl *VD = cast<VarDecl>(Global);
844     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
845 
846     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
847       return;
848   }
849 
850   // Defer code generation when possible if this is a static definition, inline
851   // function etc.  These we only want to emit if they are used.
852   if (!MayDeferGeneration(Global)) {
853     // Emit the definition if it can't be deferred.
854     EmitGlobalDefinition(GD);
855     return;
856   }
857 
858   // If we're deferring emission of a C++ variable with an
859   // initializer, remember the order in which it appeared in the file.
860   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
861       cast<VarDecl>(Global)->hasInit()) {
862     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
863     CXXGlobalInits.push_back(0);
864   }
865 
866   // If the value has already been used, add it directly to the
867   // DeferredDeclsToEmit list.
868   StringRef MangledName = getMangledName(GD);
869   if (GetGlobalValue(MangledName))
870     DeferredDeclsToEmit.push_back(GD);
871   else {
872     // Otherwise, remember that we saw a deferred decl with this name.  The
873     // first use of the mangled name will cause it to move into
874     // DeferredDeclsToEmit.
875     DeferredDecls[MangledName] = GD;
876   }
877 }
878 
879 namespace {
880   struct FunctionIsDirectlyRecursive :
881     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
882     const StringRef Name;
883     const Builtin::Context &BI;
884     bool Result;
885     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
886       Name(N), BI(C), Result(false) {
887     }
888     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
889 
890     bool TraverseCallExpr(CallExpr *E) {
891       const FunctionDecl *FD = E->getDirectCallee();
892       if (!FD)
893         return true;
894       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
895       if (Attr && Name == Attr->getLabel()) {
896         Result = true;
897         return false;
898       }
899       unsigned BuiltinID = FD->getBuiltinID();
900       if (!BuiltinID)
901         return true;
902       StringRef BuiltinName = BI.GetName(BuiltinID);
903       if (BuiltinName.startswith("__builtin_") &&
904           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
905         Result = true;
906         return false;
907       }
908       return true;
909     }
910   };
911 }
912 
913 // isTriviallyRecursive - Check if this function calls another
914 // decl that, because of the asm attribute or the other decl being a builtin,
915 // ends up pointing to itself.
916 bool
917 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
918   StringRef Name;
919   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
920     // asm labels are a special kind of mangling we have to support.
921     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
922     if (!Attr)
923       return false;
924     Name = Attr->getLabel();
925   } else {
926     Name = FD->getName();
927   }
928 
929   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
930   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
931   return Walker.Result;
932 }
933 
934 bool
935 CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
936   if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
937     return true;
938   if (CodeGenOpts.OptimizationLevel == 0 &&
939       !F->hasAttr<AlwaysInlineAttr>())
940     return false;
941   // PR9614. Avoid cases where the source code is lying to us. An available
942   // externally function should have an equivalent function somewhere else,
943   // but a function that calls itself is clearly not equivalent to the real
944   // implementation.
945   // This happens in glibc's btowc and in some configure checks.
946   return !isTriviallyRecursive(F);
947 }
948 
949 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
950   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
951 
952   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
953                                  Context.getSourceManager(),
954                                  "Generating code for declaration");
955 
956   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
957     // At -O0, don't generate IR for functions with available_externally
958     // linkage.
959     if (!shouldEmitFunction(Function))
960       return;
961 
962     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
963       // Make sure to emit the definition(s) before we emit the thunks.
964       // This is necessary for the generation of certain thunks.
965       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
966         EmitCXXConstructor(CD, GD.getCtorType());
967       else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
968         EmitCXXDestructor(DD, GD.getDtorType());
969       else
970         EmitGlobalFunctionDefinition(GD);
971 
972       if (Method->isVirtual())
973         getVTables().EmitThunks(GD);
974 
975       return;
976     }
977 
978     return EmitGlobalFunctionDefinition(GD);
979   }
980 
981   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
982     return EmitGlobalVarDefinition(VD);
983 
984   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
985 }
986 
987 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
988 /// module, create and return an llvm Function with the specified type. If there
989 /// is something in the module with the specified name, return it potentially
990 /// bitcasted to the right type.
991 ///
992 /// If D is non-null, it specifies a decl that correspond to this.  This is used
993 /// to set the attributes on the function when it is first created.
994 llvm::Constant *
995 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
996                                        llvm::Type *Ty,
997                                        GlobalDecl D, bool ForVTable,
998                                        llvm::Attributes ExtraAttrs) {
999   // Lookup the entry, lazily creating it if necessary.
1000   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1001   if (Entry) {
1002     if (WeakRefReferences.count(Entry)) {
1003       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1004       if (FD && !FD->hasAttr<WeakAttr>())
1005         Entry->setLinkage(llvm::Function::ExternalLinkage);
1006 
1007       WeakRefReferences.erase(Entry);
1008     }
1009 
1010     if (Entry->getType()->getElementType() == Ty)
1011       return Entry;
1012 
1013     // Make sure the result is of the correct type.
1014     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1015   }
1016 
1017   // This function doesn't have a complete type (for example, the return
1018   // type is an incomplete struct). Use a fake type instead, and make
1019   // sure not to try to set attributes.
1020   bool IsIncompleteFunction = false;
1021 
1022   llvm::FunctionType *FTy;
1023   if (isa<llvm::FunctionType>(Ty)) {
1024     FTy = cast<llvm::FunctionType>(Ty);
1025   } else {
1026     FTy = llvm::FunctionType::get(VoidTy, false);
1027     IsIncompleteFunction = true;
1028   }
1029 
1030   llvm::Function *F = llvm::Function::Create(FTy,
1031                                              llvm::Function::ExternalLinkage,
1032                                              MangledName, &getModule());
1033   assert(F->getName() == MangledName && "name was uniqued!");
1034   if (D.getDecl())
1035     SetFunctionAttributes(D, F, IsIncompleteFunction);
1036   if (ExtraAttrs != llvm::Attribute::None)
1037     F->addFnAttr(ExtraAttrs);
1038 
1039   // This is the first use or definition of a mangled name.  If there is a
1040   // deferred decl with this name, remember that we need to emit it at the end
1041   // of the file.
1042   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1043   if (DDI != DeferredDecls.end()) {
1044     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1045     // list, and remove it from DeferredDecls (since we don't need it anymore).
1046     DeferredDeclsToEmit.push_back(DDI->second);
1047     DeferredDecls.erase(DDI);
1048 
1049   // Otherwise, there are cases we have to worry about where we're
1050   // using a declaration for which we must emit a definition but where
1051   // we might not find a top-level definition:
1052   //   - member functions defined inline in their classes
1053   //   - friend functions defined inline in some class
1054   //   - special member functions with implicit definitions
1055   // If we ever change our AST traversal to walk into class methods,
1056   // this will be unnecessary.
1057   //
1058   // We also don't emit a definition for a function if it's going to be an entry
1059   // in a vtable, unless it's already marked as used.
1060   } else if (getLangOpts().CPlusPlus && D.getDecl()) {
1061     // Look for a declaration that's lexically in a record.
1062     const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1063     do {
1064       if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1065         if (FD->isImplicit() && !ForVTable) {
1066           assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1067           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1068           break;
1069         } else if (FD->doesThisDeclarationHaveABody()) {
1070           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1071           break;
1072         }
1073       }
1074       FD = FD->getPreviousDecl();
1075     } while (FD);
1076   }
1077 
1078   // Make sure the result is of the requested type.
1079   if (!IsIncompleteFunction) {
1080     assert(F->getType()->getElementType() == Ty);
1081     return F;
1082   }
1083 
1084   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1085   return llvm::ConstantExpr::getBitCast(F, PTy);
1086 }
1087 
1088 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1089 /// non-null, then this function will use the specified type if it has to
1090 /// create it (this occurs when we see a definition of the function).
1091 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1092                                                  llvm::Type *Ty,
1093                                                  bool ForVTable) {
1094   // If there was no specific requested type, just convert it now.
1095   if (!Ty)
1096     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1097 
1098   StringRef MangledName = getMangledName(GD);
1099   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1100 }
1101 
1102 /// CreateRuntimeFunction - Create a new runtime function with the specified
1103 /// type and name.
1104 llvm::Constant *
1105 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1106                                      StringRef Name,
1107                                      llvm::Attributes ExtraAttrs) {
1108   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1109                                  ExtraAttrs);
1110 }
1111 
1112 /// isTypeConstant - Determine whether an object of this type can be emitted
1113 /// as a constant.
1114 ///
1115 /// If ExcludeCtor is true, the duration when the object's constructor runs
1116 /// will not be considered. The caller will need to verify that the object is
1117 /// not written to during its construction.
1118 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1119   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1120     return false;
1121 
1122   if (Context.getLangOpts().CPlusPlus) {
1123     if (const CXXRecordDecl *Record
1124           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1125       return ExcludeCtor && !Record->hasMutableFields() &&
1126              Record->hasTrivialDestructor();
1127   }
1128 
1129   return true;
1130 }
1131 
1132 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1133 /// create and return an llvm GlobalVariable with the specified type.  If there
1134 /// is something in the module with the specified name, return it potentially
1135 /// bitcasted to the right type.
1136 ///
1137 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1138 /// to set the attributes on the global when it is first created.
1139 llvm::Constant *
1140 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1141                                      llvm::PointerType *Ty,
1142                                      const VarDecl *D,
1143                                      bool UnnamedAddr) {
1144   // Lookup the entry, lazily creating it if necessary.
1145   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1146   if (Entry) {
1147     if (WeakRefReferences.count(Entry)) {
1148       if (D && !D->hasAttr<WeakAttr>())
1149         Entry->setLinkage(llvm::Function::ExternalLinkage);
1150 
1151       WeakRefReferences.erase(Entry);
1152     }
1153 
1154     if (UnnamedAddr)
1155       Entry->setUnnamedAddr(true);
1156 
1157     if (Entry->getType() == Ty)
1158       return Entry;
1159 
1160     // Make sure the result is of the correct type.
1161     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1162   }
1163 
1164   // This is the first use or definition of a mangled name.  If there is a
1165   // deferred decl with this name, remember that we need to emit it at the end
1166   // of the file.
1167   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1168   if (DDI != DeferredDecls.end()) {
1169     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1170     // list, and remove it from DeferredDecls (since we don't need it anymore).
1171     DeferredDeclsToEmit.push_back(DDI->second);
1172     DeferredDecls.erase(DDI);
1173   }
1174 
1175   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1176   llvm::GlobalVariable *GV =
1177     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1178                              llvm::GlobalValue::ExternalLinkage,
1179                              0, MangledName, 0,
1180                              false, AddrSpace);
1181 
1182   // Handle things which are present even on external declarations.
1183   if (D) {
1184     // FIXME: This code is overly simple and should be merged with other global
1185     // handling.
1186     GV->setConstant(isTypeConstant(D->getType(), false));
1187 
1188     // Set linkage and visibility in case we never see a definition.
1189     NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1190     if (LV.linkage() != ExternalLinkage) {
1191       // Don't set internal linkage on declarations.
1192     } else {
1193       if (D->hasAttr<DLLImportAttr>())
1194         GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1195       else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1196         GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1197 
1198       // Set visibility on a declaration only if it's explicit.
1199       if (LV.visibilityExplicit())
1200         GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1201     }
1202 
1203     GV->setThreadLocal(D->isThreadSpecified());
1204   }
1205 
1206   if (AddrSpace != Ty->getAddressSpace())
1207     return llvm::ConstantExpr::getBitCast(GV, Ty);
1208   else
1209     return GV;
1210 }
1211 
1212 
1213 llvm::GlobalVariable *
1214 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1215                                       llvm::Type *Ty,
1216                                       llvm::GlobalValue::LinkageTypes Linkage) {
1217   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1218   llvm::GlobalVariable *OldGV = 0;
1219 
1220 
1221   if (GV) {
1222     // Check if the variable has the right type.
1223     if (GV->getType()->getElementType() == Ty)
1224       return GV;
1225 
1226     // Because C++ name mangling, the only way we can end up with an already
1227     // existing global with the same name is if it has been declared extern "C".
1228       assert(GV->isDeclaration() && "Declaration has wrong type!");
1229     OldGV = GV;
1230   }
1231 
1232   // Create a new variable.
1233   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1234                                 Linkage, 0, Name);
1235 
1236   if (OldGV) {
1237     // Replace occurrences of the old variable if needed.
1238     GV->takeName(OldGV);
1239 
1240     if (!OldGV->use_empty()) {
1241       llvm::Constant *NewPtrForOldDecl =
1242       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1243       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1244     }
1245 
1246     OldGV->eraseFromParent();
1247   }
1248 
1249   return GV;
1250 }
1251 
1252 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1253 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1254 /// then it will be created with the specified type instead of whatever the
1255 /// normal requested type would be.
1256 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1257                                                   llvm::Type *Ty) {
1258   assert(D->hasGlobalStorage() && "Not a global variable");
1259   QualType ASTTy = D->getType();
1260   if (Ty == 0)
1261     Ty = getTypes().ConvertTypeForMem(ASTTy);
1262 
1263   llvm::PointerType *PTy =
1264     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1265 
1266   StringRef MangledName = getMangledName(D);
1267   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1268 }
1269 
1270 /// CreateRuntimeVariable - Create a new runtime global variable with the
1271 /// specified type and name.
1272 llvm::Constant *
1273 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1274                                      StringRef Name) {
1275   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1276                                true);
1277 }
1278 
1279 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1280   assert(!D->getInit() && "Cannot emit definite definitions here!");
1281 
1282   if (MayDeferGeneration(D)) {
1283     // If we have not seen a reference to this variable yet, place it
1284     // into the deferred declarations table to be emitted if needed
1285     // later.
1286     StringRef MangledName = getMangledName(D);
1287     if (!GetGlobalValue(MangledName)) {
1288       DeferredDecls[MangledName] = D;
1289       return;
1290     }
1291   }
1292 
1293   // The tentative definition is the only definition.
1294   EmitGlobalVarDefinition(D);
1295 }
1296 
1297 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1298   if (DefinitionRequired)
1299     getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1300 }
1301 
1302 llvm::GlobalVariable::LinkageTypes
1303 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1304   if (RD->getLinkage() != ExternalLinkage)
1305     return llvm::GlobalVariable::InternalLinkage;
1306 
1307   if (const CXXMethodDecl *KeyFunction
1308                                     = RD->getASTContext().getKeyFunction(RD)) {
1309     // If this class has a key function, use that to determine the linkage of
1310     // the vtable.
1311     const FunctionDecl *Def = 0;
1312     if (KeyFunction->hasBody(Def))
1313       KeyFunction = cast<CXXMethodDecl>(Def);
1314 
1315     switch (KeyFunction->getTemplateSpecializationKind()) {
1316       case TSK_Undeclared:
1317       case TSK_ExplicitSpecialization:
1318         // When compiling with optimizations turned on, we emit all vtables,
1319         // even if the key function is not defined in the current translation
1320         // unit. If this is the case, use available_externally linkage.
1321         if (!Def && CodeGenOpts.OptimizationLevel)
1322           return llvm::GlobalVariable::AvailableExternallyLinkage;
1323 
1324         if (KeyFunction->isInlined())
1325           return !Context.getLangOpts().AppleKext ?
1326                    llvm::GlobalVariable::LinkOnceODRLinkage :
1327                    llvm::Function::InternalLinkage;
1328 
1329         return llvm::GlobalVariable::ExternalLinkage;
1330 
1331       case TSK_ImplicitInstantiation:
1332         return !Context.getLangOpts().AppleKext ?
1333                  llvm::GlobalVariable::LinkOnceODRLinkage :
1334                  llvm::Function::InternalLinkage;
1335 
1336       case TSK_ExplicitInstantiationDefinition:
1337         return !Context.getLangOpts().AppleKext ?
1338                  llvm::GlobalVariable::WeakODRLinkage :
1339                  llvm::Function::InternalLinkage;
1340 
1341       case TSK_ExplicitInstantiationDeclaration:
1342         // FIXME: Use available_externally linkage. However, this currently
1343         // breaks LLVM's build due to undefined symbols.
1344         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1345         return !Context.getLangOpts().AppleKext ?
1346                  llvm::GlobalVariable::LinkOnceODRLinkage :
1347                  llvm::Function::InternalLinkage;
1348     }
1349   }
1350 
1351   if (Context.getLangOpts().AppleKext)
1352     return llvm::Function::InternalLinkage;
1353 
1354   switch (RD->getTemplateSpecializationKind()) {
1355   case TSK_Undeclared:
1356   case TSK_ExplicitSpecialization:
1357   case TSK_ImplicitInstantiation:
1358     // FIXME: Use available_externally linkage. However, this currently
1359     // breaks LLVM's build due to undefined symbols.
1360     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1361   case TSK_ExplicitInstantiationDeclaration:
1362     return llvm::GlobalVariable::LinkOnceODRLinkage;
1363 
1364   case TSK_ExplicitInstantiationDefinition:
1365       return llvm::GlobalVariable::WeakODRLinkage;
1366   }
1367 
1368   llvm_unreachable("Invalid TemplateSpecializationKind!");
1369 }
1370 
1371 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1372     return Context.toCharUnitsFromBits(
1373       TheTargetData.getTypeStoreSizeInBits(Ty));
1374 }
1375 
1376 llvm::Constant *
1377 CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1378                                                        const Expr *rawInit) {
1379   ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1380   if (const ExprWithCleanups *withCleanups =
1381           dyn_cast<ExprWithCleanups>(rawInit)) {
1382     cleanups = withCleanups->getObjects();
1383     rawInit = withCleanups->getSubExpr();
1384   }
1385 
1386   const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1387   if (!init || !init->initializesStdInitializerList() ||
1388       init->getNumInits() == 0)
1389     return 0;
1390 
1391   ASTContext &ctx = getContext();
1392   unsigned numInits = init->getNumInits();
1393   // FIXME: This check is here because we would otherwise silently miscompile
1394   // nested global std::initializer_lists. Better would be to have a real
1395   // implementation.
1396   for (unsigned i = 0; i < numInits; ++i) {
1397     const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1398     if (inner && inner->initializesStdInitializerList()) {
1399       ErrorUnsupported(inner, "nested global std::initializer_list");
1400       return 0;
1401     }
1402   }
1403 
1404   // Synthesize a fake VarDecl for the array and initialize that.
1405   QualType elementType = init->getInit(0)->getType();
1406   llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1407   QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1408                                                 ArrayType::Normal, 0);
1409 
1410   IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1411   TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1412                                               arrayType, D->getLocation());
1413   VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1414                                                           D->getDeclContext()),
1415                                           D->getLocStart(), D->getLocation(),
1416                                           name, arrayType, sourceInfo,
1417                                           SC_Static, SC_Static);
1418 
1419   // Now clone the InitListExpr to initialize the array instead.
1420   // Incredible hack: we want to use the existing InitListExpr here, so we need
1421   // to tell it that it no longer initializes a std::initializer_list.
1422   Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(),
1423                                     const_cast<InitListExpr*>(init)->getInits(),
1424                                                    init->getNumInits(),
1425                                                    init->getRBraceLoc());
1426   arrayInit->setType(arrayType);
1427 
1428   if (!cleanups.empty())
1429     arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1430 
1431   backingArray->setInit(arrayInit);
1432 
1433   // Emit the definition of the array.
1434   EmitGlobalVarDefinition(backingArray);
1435 
1436   // Inspect the initializer list to validate it and determine its type.
1437   // FIXME: doing this every time is probably inefficient; caching would be nice
1438   RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1439   RecordDecl::field_iterator field = record->field_begin();
1440   if (field == record->field_end()) {
1441     ErrorUnsupported(D, "weird std::initializer_list");
1442     return 0;
1443   }
1444   QualType elementPtr = ctx.getPointerType(elementType.withConst());
1445   // Start pointer.
1446   if (!ctx.hasSameType(field->getType(), elementPtr)) {
1447     ErrorUnsupported(D, "weird std::initializer_list");
1448     return 0;
1449   }
1450   ++field;
1451   if (field == record->field_end()) {
1452     ErrorUnsupported(D, "weird std::initializer_list");
1453     return 0;
1454   }
1455   bool isStartEnd = false;
1456   if (ctx.hasSameType(field->getType(), elementPtr)) {
1457     // End pointer.
1458     isStartEnd = true;
1459   } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1460     ErrorUnsupported(D, "weird std::initializer_list");
1461     return 0;
1462   }
1463 
1464   // Now build an APValue representing the std::initializer_list.
1465   APValue initListValue(APValue::UninitStruct(), 0, 2);
1466   APValue &startField = initListValue.getStructField(0);
1467   APValue::LValuePathEntry startOffsetPathEntry;
1468   startOffsetPathEntry.ArrayIndex = 0;
1469   startField = APValue(APValue::LValueBase(backingArray),
1470                        CharUnits::fromQuantity(0),
1471                        llvm::makeArrayRef(startOffsetPathEntry),
1472                        /*IsOnePastTheEnd=*/false, 0);
1473 
1474   if (isStartEnd) {
1475     APValue &endField = initListValue.getStructField(1);
1476     APValue::LValuePathEntry endOffsetPathEntry;
1477     endOffsetPathEntry.ArrayIndex = numInits;
1478     endField = APValue(APValue::LValueBase(backingArray),
1479                        ctx.getTypeSizeInChars(elementType) * numInits,
1480                        llvm::makeArrayRef(endOffsetPathEntry),
1481                        /*IsOnePastTheEnd=*/true, 0);
1482   } else {
1483     APValue &sizeField = initListValue.getStructField(1);
1484     sizeField = APValue(llvm::APSInt(numElements));
1485   }
1486 
1487   // Emit the constant for the initializer_list.
1488   llvm::Constant *llvmInit =
1489       EmitConstantValueForMemory(initListValue, D->getType());
1490   assert(llvmInit && "failed to initialize as constant");
1491   return llvmInit;
1492 }
1493 
1494 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1495                                                  unsigned AddrSpace) {
1496   if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1497     if (D->hasAttr<CUDAConstantAttr>())
1498       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1499     else if (D->hasAttr<CUDASharedAttr>())
1500       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1501     else
1502       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1503   }
1504 
1505   return AddrSpace;
1506 }
1507 
1508 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1509   llvm::Constant *Init = 0;
1510   QualType ASTTy = D->getType();
1511   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1512   bool NeedsGlobalCtor = false;
1513   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1514 
1515   const VarDecl *InitDecl;
1516   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1517 
1518   if (!InitExpr) {
1519     // This is a tentative definition; tentative definitions are
1520     // implicitly initialized with { 0 }.
1521     //
1522     // Note that tentative definitions are only emitted at the end of
1523     // a translation unit, so they should never have incomplete
1524     // type. In addition, EmitTentativeDefinition makes sure that we
1525     // never attempt to emit a tentative definition if a real one
1526     // exists. A use may still exists, however, so we still may need
1527     // to do a RAUW.
1528     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1529     Init = EmitNullConstant(D->getType());
1530   } else {
1531     // If this is a std::initializer_list, emit the special initializer.
1532     Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1533     // An empty init list will perform zero-initialization, which happens
1534     // to be exactly what we want.
1535     // FIXME: It does so in a global constructor, which is *not* what we
1536     // want.
1537 
1538     if (!Init)
1539       Init = EmitConstantInit(*InitDecl);
1540     if (!Init) {
1541       QualType T = InitExpr->getType();
1542       if (D->getType()->isReferenceType())
1543         T = D->getType();
1544 
1545       if (getLangOpts().CPlusPlus) {
1546         Init = EmitNullConstant(T);
1547         NeedsGlobalCtor = true;
1548       } else {
1549         ErrorUnsupported(D, "static initializer");
1550         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1551       }
1552     } else {
1553       // We don't need an initializer, so remove the entry for the delayed
1554       // initializer position (just in case this entry was delayed) if we
1555       // also don't need to register a destructor.
1556       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1557         DelayedCXXInitPosition.erase(D);
1558     }
1559   }
1560 
1561   llvm::Type* InitType = Init->getType();
1562   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1563 
1564   // Strip off a bitcast if we got one back.
1565   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1566     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1567            // all zero index gep.
1568            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1569     Entry = CE->getOperand(0);
1570   }
1571 
1572   // Entry is now either a Function or GlobalVariable.
1573   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1574 
1575   // We have a definition after a declaration with the wrong type.
1576   // We must make a new GlobalVariable* and update everything that used OldGV
1577   // (a declaration or tentative definition) with the new GlobalVariable*
1578   // (which will be a definition).
1579   //
1580   // This happens if there is a prototype for a global (e.g.
1581   // "extern int x[];") and then a definition of a different type (e.g.
1582   // "int x[10];"). This also happens when an initializer has a different type
1583   // from the type of the global (this happens with unions).
1584   if (GV == 0 ||
1585       GV->getType()->getElementType() != InitType ||
1586       GV->getType()->getAddressSpace() !=
1587        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1588 
1589     // Move the old entry aside so that we'll create a new one.
1590     Entry->setName(StringRef());
1591 
1592     // Make a new global with the correct type, this is now guaranteed to work.
1593     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1594 
1595     // Replace all uses of the old global with the new global
1596     llvm::Constant *NewPtrForOldDecl =
1597         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1598     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1599 
1600     // Erase the old global, since it is no longer used.
1601     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1602   }
1603 
1604   if (D->hasAttr<AnnotateAttr>())
1605     AddGlobalAnnotations(D, GV);
1606 
1607   GV->setInitializer(Init);
1608 
1609   // If it is safe to mark the global 'constant', do so now.
1610   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1611                   isTypeConstant(D->getType(), true));
1612 
1613   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1614 
1615   // Set the llvm linkage type as appropriate.
1616   llvm::GlobalValue::LinkageTypes Linkage =
1617     GetLLVMLinkageVarDefinition(D, GV);
1618   GV->setLinkage(Linkage);
1619   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1620     // common vars aren't constant even if declared const.
1621     GV->setConstant(false);
1622 
1623   SetCommonAttributes(D, GV);
1624 
1625   // Emit the initializer function if necessary.
1626   if (NeedsGlobalCtor || NeedsGlobalDtor)
1627     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1628 
1629   // Emit global variable debug information.
1630   if (CGDebugInfo *DI = getModuleDebugInfo())
1631     if (getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo)
1632       DI->EmitGlobalVariable(GV, D);
1633 }
1634 
1635 llvm::GlobalValue::LinkageTypes
1636 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1637                                            llvm::GlobalVariable *GV) {
1638   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1639   if (Linkage == GVA_Internal)
1640     return llvm::Function::InternalLinkage;
1641   else if (D->hasAttr<DLLImportAttr>())
1642     return llvm::Function::DLLImportLinkage;
1643   else if (D->hasAttr<DLLExportAttr>())
1644     return llvm::Function::DLLExportLinkage;
1645   else if (D->hasAttr<WeakAttr>()) {
1646     if (GV->isConstant())
1647       return llvm::GlobalVariable::WeakODRLinkage;
1648     else
1649       return llvm::GlobalVariable::WeakAnyLinkage;
1650   } else if (Linkage == GVA_TemplateInstantiation ||
1651              Linkage == GVA_ExplicitTemplateInstantiation)
1652     return llvm::GlobalVariable::WeakODRLinkage;
1653   else if (!getLangOpts().CPlusPlus &&
1654            ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1655              D->getAttr<CommonAttr>()) &&
1656            !D->hasExternalStorage() && !D->getInit() &&
1657            !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1658            !D->getAttr<WeakImportAttr>()) {
1659     // Thread local vars aren't considered common linkage.
1660     return llvm::GlobalVariable::CommonLinkage;
1661   }
1662   return llvm::GlobalVariable::ExternalLinkage;
1663 }
1664 
1665 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1666 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1667 /// existing call uses of the old function in the module, this adjusts them to
1668 /// call the new function directly.
1669 ///
1670 /// This is not just a cleanup: the always_inline pass requires direct calls to
1671 /// functions to be able to inline them.  If there is a bitcast in the way, it
1672 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1673 /// run at -O0.
1674 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1675                                                       llvm::Function *NewFn) {
1676   // If we're redefining a global as a function, don't transform it.
1677   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1678   if (OldFn == 0) return;
1679 
1680   llvm::Type *NewRetTy = NewFn->getReturnType();
1681   SmallVector<llvm::Value*, 4> ArgList;
1682 
1683   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1684        UI != E; ) {
1685     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1686     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1687     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1688     if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1689     llvm::CallSite CS(CI);
1690     if (!CI || !CS.isCallee(I)) continue;
1691 
1692     // If the return types don't match exactly, and if the call isn't dead, then
1693     // we can't transform this call.
1694     if (CI->getType() != NewRetTy && !CI->use_empty())
1695       continue;
1696 
1697     // Get the attribute list.
1698     llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
1699     llvm::AttrListPtr AttrList = CI->getAttributes();
1700 
1701     // Get any return attributes.
1702     llvm::Attributes RAttrs = AttrList.getRetAttributes();
1703 
1704     // Add the return attributes.
1705     if (RAttrs)
1706       AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
1707 
1708     // If the function was passed too few arguments, don't transform.  If extra
1709     // arguments were passed, we silently drop them.  If any of the types
1710     // mismatch, we don't transform.
1711     unsigned ArgNo = 0;
1712     bool DontTransform = false;
1713     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1714          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1715       if (CS.arg_size() == ArgNo ||
1716           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1717         DontTransform = true;
1718         break;
1719       }
1720 
1721       // Add any parameter attributes.
1722       if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
1723         AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1724     }
1725     if (DontTransform)
1726       continue;
1727 
1728     if (llvm::Attributes FnAttrs =  AttrList.getFnAttributes())
1729       AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
1730 
1731     // Okay, we can transform this.  Create the new call instruction and copy
1732     // over the required information.
1733     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1734     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1735     ArgList.clear();
1736     if (!NewCall->getType()->isVoidTy())
1737       NewCall->takeName(CI);
1738     NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
1739                                                   AttrVec.end()));
1740     NewCall->setCallingConv(CI->getCallingConv());
1741 
1742     // Finally, remove the old call, replacing any uses with the new one.
1743     if (!CI->use_empty())
1744       CI->replaceAllUsesWith(NewCall);
1745 
1746     // Copy debug location attached to CI.
1747     if (!CI->getDebugLoc().isUnknown())
1748       NewCall->setDebugLoc(CI->getDebugLoc());
1749     CI->eraseFromParent();
1750   }
1751 }
1752 
1753 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1754   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1755   // If we have a definition, this might be a deferred decl. If the
1756   // instantiation is explicit, make sure we emit it at the end.
1757   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1758     GetAddrOfGlobalVar(VD);
1759 }
1760 
1761 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1762   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1763 
1764   // Compute the function info and LLVM type.
1765   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1766   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
1767 
1768   // Get or create the prototype for the function.
1769   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1770 
1771   // Strip off a bitcast if we got one back.
1772   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1773     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1774     Entry = CE->getOperand(0);
1775   }
1776 
1777 
1778   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1779     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1780 
1781     // If the types mismatch then we have to rewrite the definition.
1782     assert(OldFn->isDeclaration() &&
1783            "Shouldn't replace non-declaration");
1784 
1785     // F is the Function* for the one with the wrong type, we must make a new
1786     // Function* and update everything that used F (a declaration) with the new
1787     // Function* (which will be a definition).
1788     //
1789     // This happens if there is a prototype for a function
1790     // (e.g. "int f()") and then a definition of a different type
1791     // (e.g. "int f(int x)").  Move the old function aside so that it
1792     // doesn't interfere with GetAddrOfFunction.
1793     OldFn->setName(StringRef());
1794     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1795 
1796     // If this is an implementation of a function without a prototype, try to
1797     // replace any existing uses of the function (which may be calls) with uses
1798     // of the new function
1799     if (D->getType()->isFunctionNoProtoType()) {
1800       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1801       OldFn->removeDeadConstantUsers();
1802     }
1803 
1804     // Replace uses of F with the Function we will endow with a body.
1805     if (!Entry->use_empty()) {
1806       llvm::Constant *NewPtrForOldDecl =
1807         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1808       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1809     }
1810 
1811     // Ok, delete the old function now, which is dead.
1812     OldFn->eraseFromParent();
1813 
1814     Entry = NewFn;
1815   }
1816 
1817   // We need to set linkage and visibility on the function before
1818   // generating code for it because various parts of IR generation
1819   // want to propagate this information down (e.g. to local static
1820   // declarations).
1821   llvm::Function *Fn = cast<llvm::Function>(Entry);
1822   setFunctionLinkage(D, Fn);
1823 
1824   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1825   setGlobalVisibility(Fn, D);
1826 
1827   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1828 
1829   SetFunctionDefinitionAttributes(D, Fn);
1830   SetLLVMFunctionAttributesForDefinition(D, Fn);
1831 
1832   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1833     AddGlobalCtor(Fn, CA->getPriority());
1834   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1835     AddGlobalDtor(Fn, DA->getPriority());
1836   if (D->hasAttr<AnnotateAttr>())
1837     AddGlobalAnnotations(D, Fn);
1838 }
1839 
1840 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1841   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1842   const AliasAttr *AA = D->getAttr<AliasAttr>();
1843   assert(AA && "Not an alias?");
1844 
1845   StringRef MangledName = getMangledName(GD);
1846 
1847   // If there is a definition in the module, then it wins over the alias.
1848   // This is dubious, but allow it to be safe.  Just ignore the alias.
1849   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1850   if (Entry && !Entry->isDeclaration())
1851     return;
1852 
1853   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1854 
1855   // Create a reference to the named value.  This ensures that it is emitted
1856   // if a deferred decl.
1857   llvm::Constant *Aliasee;
1858   if (isa<llvm::FunctionType>(DeclTy))
1859     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1860                                       /*ForVTable=*/false);
1861   else
1862     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1863                                     llvm::PointerType::getUnqual(DeclTy), 0);
1864 
1865   // Create the new alias itself, but don't set a name yet.
1866   llvm::GlobalValue *GA =
1867     new llvm::GlobalAlias(Aliasee->getType(),
1868                           llvm::Function::ExternalLinkage,
1869                           "", Aliasee, &getModule());
1870 
1871   if (Entry) {
1872     assert(Entry->isDeclaration());
1873 
1874     // If there is a declaration in the module, then we had an extern followed
1875     // by the alias, as in:
1876     //   extern int test6();
1877     //   ...
1878     //   int test6() __attribute__((alias("test7")));
1879     //
1880     // Remove it and replace uses of it with the alias.
1881     GA->takeName(Entry);
1882 
1883     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1884                                                           Entry->getType()));
1885     Entry->eraseFromParent();
1886   } else {
1887     GA->setName(MangledName);
1888   }
1889 
1890   // Set attributes which are particular to an alias; this is a
1891   // specialization of the attributes which may be set on a global
1892   // variable/function.
1893   if (D->hasAttr<DLLExportAttr>()) {
1894     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1895       // The dllexport attribute is ignored for undefined symbols.
1896       if (FD->hasBody())
1897         GA->setLinkage(llvm::Function::DLLExportLinkage);
1898     } else {
1899       GA->setLinkage(llvm::Function::DLLExportLinkage);
1900     }
1901   } else if (D->hasAttr<WeakAttr>() ||
1902              D->hasAttr<WeakRefAttr>() ||
1903              D->isWeakImported()) {
1904     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1905   }
1906 
1907   SetCommonAttributes(D, GA);
1908 }
1909 
1910 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
1911                                             ArrayRef<llvm::Type*> Tys) {
1912   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
1913                                          Tys);
1914 }
1915 
1916 static llvm::StringMapEntry<llvm::Constant*> &
1917 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1918                          const StringLiteral *Literal,
1919                          bool TargetIsLSB,
1920                          bool &IsUTF16,
1921                          unsigned &StringLength) {
1922   StringRef String = Literal->getString();
1923   unsigned NumBytes = String.size();
1924 
1925   // Check for simple case.
1926   if (!Literal->containsNonAsciiOrNull()) {
1927     StringLength = NumBytes;
1928     return Map.GetOrCreateValue(String);
1929   }
1930 
1931   // Otherwise, convert the UTF8 literals into a string of shorts.
1932   IsUTF16 = true;
1933 
1934   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
1935   const UTF8 *FromPtr = (UTF8 *)String.data();
1936   UTF16 *ToPtr = &ToBuf[0];
1937 
1938   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1939                            &ToPtr, ToPtr + NumBytes,
1940                            strictConversion);
1941 
1942   // ConvertUTF8toUTF16 returns the length in ToPtr.
1943   StringLength = ToPtr - &ToBuf[0];
1944 
1945   // Add an explicit null.
1946   *ToPtr = 0;
1947   return Map.
1948     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
1949                                (StringLength + 1) * 2));
1950 }
1951 
1952 static llvm::StringMapEntry<llvm::Constant*> &
1953 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1954                        const StringLiteral *Literal,
1955                        unsigned &StringLength) {
1956   StringRef String = Literal->getString();
1957   StringLength = String.size();
1958   return Map.GetOrCreateValue(String);
1959 }
1960 
1961 llvm::Constant *
1962 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1963   unsigned StringLength = 0;
1964   bool isUTF16 = false;
1965   llvm::StringMapEntry<llvm::Constant*> &Entry =
1966     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1967                              getTargetData().isLittleEndian(),
1968                              isUTF16, StringLength);
1969 
1970   if (llvm::Constant *C = Entry.getValue())
1971     return C;
1972 
1973   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
1974   llvm::Constant *Zeros[] = { Zero, Zero };
1975 
1976   // If we don't already have it, get __CFConstantStringClassReference.
1977   if (!CFConstantStringClassRef) {
1978     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1979     Ty = llvm::ArrayType::get(Ty, 0);
1980     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1981                                            "__CFConstantStringClassReference");
1982     // Decay array -> ptr
1983     CFConstantStringClassRef =
1984       llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1985   }
1986 
1987   QualType CFTy = getContext().getCFConstantStringType();
1988 
1989   llvm::StructType *STy =
1990     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1991 
1992   llvm::Constant *Fields[4];
1993 
1994   // Class pointer.
1995   Fields[0] = CFConstantStringClassRef;
1996 
1997   // Flags.
1998   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1999   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2000     llvm::ConstantInt::get(Ty, 0x07C8);
2001 
2002   // String pointer.
2003   llvm::Constant *C = 0;
2004   if (isUTF16) {
2005     ArrayRef<uint16_t> Arr =
2006       llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
2007                                    Entry.getKey().size() / 2);
2008     C = llvm::ConstantDataArray::get(VMContext, Arr);
2009   } else {
2010     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2011   }
2012 
2013   llvm::GlobalValue::LinkageTypes Linkage;
2014   if (isUTF16)
2015     // FIXME: why do utf strings get "_" labels instead of "L" labels?
2016     Linkage = llvm::GlobalValue::InternalLinkage;
2017   else
2018     // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2019     // when using private linkage. It is not clear if this is a bug in ld
2020     // or a reasonable new restriction.
2021     Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2022 
2023   // Note: -fwritable-strings doesn't make the backing store strings of
2024   // CFStrings writable. (See <rdar://problem/10657500>)
2025   llvm::GlobalVariable *GV =
2026     new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2027                              Linkage, C, ".str");
2028   GV->setUnnamedAddr(true);
2029   if (isUTF16) {
2030     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2031     GV->setAlignment(Align.getQuantity());
2032   } else {
2033     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2034     GV->setAlignment(Align.getQuantity());
2035   }
2036 
2037   // String.
2038   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2039 
2040   if (isUTF16)
2041     // Cast the UTF16 string to the correct type.
2042     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2043 
2044   // String length.
2045   Ty = getTypes().ConvertType(getContext().LongTy);
2046   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2047 
2048   // The struct.
2049   C = llvm::ConstantStruct::get(STy, Fields);
2050   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2051                                 llvm::GlobalVariable::PrivateLinkage, C,
2052                                 "_unnamed_cfstring_");
2053   if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
2054     GV->setSection(Sect);
2055   Entry.setValue(GV);
2056 
2057   return GV;
2058 }
2059 
2060 static RecordDecl *
2061 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2062                  DeclContext *DC, IdentifierInfo *Id) {
2063   SourceLocation Loc;
2064   if (Ctx.getLangOpts().CPlusPlus)
2065     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2066   else
2067     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2068 }
2069 
2070 llvm::Constant *
2071 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2072   unsigned StringLength = 0;
2073   llvm::StringMapEntry<llvm::Constant*> &Entry =
2074     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2075 
2076   if (llvm::Constant *C = Entry.getValue())
2077     return C;
2078 
2079   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2080   llvm::Constant *Zeros[] = { Zero, Zero };
2081 
2082   // If we don't already have it, get _NSConstantStringClassReference.
2083   if (!ConstantStringClassRef) {
2084     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2085     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2086     llvm::Constant *GV;
2087     if (LangOpts.ObjCNonFragileABI) {
2088       std::string str =
2089         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2090                             : "OBJC_CLASS_$_" + StringClass;
2091       GV = getObjCRuntime().GetClassGlobal(str);
2092       // Make sure the result is of the correct type.
2093       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2094       ConstantStringClassRef =
2095         llvm::ConstantExpr::getBitCast(GV, PTy);
2096     } else {
2097       std::string str =
2098         StringClass.empty() ? "_NSConstantStringClassReference"
2099                             : "_" + StringClass + "ClassReference";
2100       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2101       GV = CreateRuntimeVariable(PTy, str);
2102       // Decay array -> ptr
2103       ConstantStringClassRef =
2104         llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2105     }
2106   }
2107 
2108   if (!NSConstantStringType) {
2109     // Construct the type for a constant NSString.
2110     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2111                                      Context.getTranslationUnitDecl(),
2112                                    &Context.Idents.get("__builtin_NSString"));
2113     D->startDefinition();
2114 
2115     QualType FieldTypes[3];
2116 
2117     // const int *isa;
2118     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2119     // const char *str;
2120     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2121     // unsigned int length;
2122     FieldTypes[2] = Context.UnsignedIntTy;
2123 
2124     // Create fields
2125     for (unsigned i = 0; i < 3; ++i) {
2126       FieldDecl *Field = FieldDecl::Create(Context, D,
2127                                            SourceLocation(),
2128                                            SourceLocation(), 0,
2129                                            FieldTypes[i], /*TInfo=*/0,
2130                                            /*BitWidth=*/0,
2131                                            /*Mutable=*/false,
2132                                            /*HasInit=*/false);
2133       Field->setAccess(AS_public);
2134       D->addDecl(Field);
2135     }
2136 
2137     D->completeDefinition();
2138     QualType NSTy = Context.getTagDeclType(D);
2139     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2140   }
2141 
2142   llvm::Constant *Fields[3];
2143 
2144   // Class pointer.
2145   Fields[0] = ConstantStringClassRef;
2146 
2147   // String pointer.
2148   llvm::Constant *C =
2149     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2150 
2151   llvm::GlobalValue::LinkageTypes Linkage;
2152   bool isConstant;
2153   Linkage = llvm::GlobalValue::PrivateLinkage;
2154   isConstant = !LangOpts.WritableStrings;
2155 
2156   llvm::GlobalVariable *GV =
2157   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2158                            ".str");
2159   GV->setUnnamedAddr(true);
2160   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2161   GV->setAlignment(Align.getQuantity());
2162   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2163 
2164   // String length.
2165   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2166   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2167 
2168   // The struct.
2169   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2170   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2171                                 llvm::GlobalVariable::PrivateLinkage, C,
2172                                 "_unnamed_nsstring_");
2173   // FIXME. Fix section.
2174   if (const char *Sect =
2175         LangOpts.ObjCNonFragileABI
2176           ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2177           : getContext().getTargetInfo().getNSStringSection())
2178     GV->setSection(Sect);
2179   Entry.setValue(GV);
2180 
2181   return GV;
2182 }
2183 
2184 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2185   if (ObjCFastEnumerationStateType.isNull()) {
2186     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2187                                      Context.getTranslationUnitDecl(),
2188                       &Context.Idents.get("__objcFastEnumerationState"));
2189     D->startDefinition();
2190 
2191     QualType FieldTypes[] = {
2192       Context.UnsignedLongTy,
2193       Context.getPointerType(Context.getObjCIdType()),
2194       Context.getPointerType(Context.UnsignedLongTy),
2195       Context.getConstantArrayType(Context.UnsignedLongTy,
2196                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2197     };
2198 
2199     for (size_t i = 0; i < 4; ++i) {
2200       FieldDecl *Field = FieldDecl::Create(Context,
2201                                            D,
2202                                            SourceLocation(),
2203                                            SourceLocation(), 0,
2204                                            FieldTypes[i], /*TInfo=*/0,
2205                                            /*BitWidth=*/0,
2206                                            /*Mutable=*/false,
2207                                            /*HasInit=*/false);
2208       Field->setAccess(AS_public);
2209       D->addDecl(Field);
2210     }
2211 
2212     D->completeDefinition();
2213     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2214   }
2215 
2216   return ObjCFastEnumerationStateType;
2217 }
2218 
2219 llvm::Constant *
2220 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2221   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2222 
2223   // Don't emit it as the address of the string, emit the string data itself
2224   // as an inline array.
2225   if (E->getCharByteWidth() == 1) {
2226     SmallString<64> Str(E->getString());
2227 
2228     // Resize the string to the right size, which is indicated by its type.
2229     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2230     Str.resize(CAT->getSize().getZExtValue());
2231     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2232   }
2233 
2234   llvm::ArrayType *AType =
2235     cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2236   llvm::Type *ElemTy = AType->getElementType();
2237   unsigned NumElements = AType->getNumElements();
2238 
2239   // Wide strings have either 2-byte or 4-byte elements.
2240   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2241     SmallVector<uint16_t, 32> Elements;
2242     Elements.reserve(NumElements);
2243 
2244     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2245       Elements.push_back(E->getCodeUnit(i));
2246     Elements.resize(NumElements);
2247     return llvm::ConstantDataArray::get(VMContext, Elements);
2248   }
2249 
2250   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2251   SmallVector<uint32_t, 32> Elements;
2252   Elements.reserve(NumElements);
2253 
2254   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2255     Elements.push_back(E->getCodeUnit(i));
2256   Elements.resize(NumElements);
2257   return llvm::ConstantDataArray::get(VMContext, Elements);
2258 }
2259 
2260 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2261 /// constant array for the given string literal.
2262 llvm::Constant *
2263 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2264   CharUnits Align = getContext().getTypeAlignInChars(S->getType());
2265   if (S->isAscii() || S->isUTF8()) {
2266     SmallString<64> Str(S->getString());
2267 
2268     // Resize the string to the right size, which is indicated by its type.
2269     const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2270     Str.resize(CAT->getSize().getZExtValue());
2271     return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2272   }
2273 
2274   // FIXME: the following does not memoize wide strings.
2275   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2276   llvm::GlobalVariable *GV =
2277     new llvm::GlobalVariable(getModule(),C->getType(),
2278                              !LangOpts.WritableStrings,
2279                              llvm::GlobalValue::PrivateLinkage,
2280                              C,".str");
2281 
2282   GV->setAlignment(Align.getQuantity());
2283   GV->setUnnamedAddr(true);
2284   return GV;
2285 }
2286 
2287 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2288 /// array for the given ObjCEncodeExpr node.
2289 llvm::Constant *
2290 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2291   std::string Str;
2292   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2293 
2294   return GetAddrOfConstantCString(Str);
2295 }
2296 
2297 
2298 /// GenerateWritableString -- Creates storage for a string literal.
2299 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2300                                              bool constant,
2301                                              CodeGenModule &CGM,
2302                                              const char *GlobalName,
2303                                              unsigned Alignment) {
2304   // Create Constant for this string literal. Don't add a '\0'.
2305   llvm::Constant *C =
2306       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2307 
2308   // Create a global variable for this string
2309   llvm::GlobalVariable *GV =
2310     new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2311                              llvm::GlobalValue::PrivateLinkage,
2312                              C, GlobalName);
2313   GV->setAlignment(Alignment);
2314   GV->setUnnamedAddr(true);
2315   return GV;
2316 }
2317 
2318 /// GetAddrOfConstantString - Returns a pointer to a character array
2319 /// containing the literal. This contents are exactly that of the
2320 /// given string, i.e. it will not be null terminated automatically;
2321 /// see GetAddrOfConstantCString. Note that whether the result is
2322 /// actually a pointer to an LLVM constant depends on
2323 /// Feature.WriteableStrings.
2324 ///
2325 /// The result has pointer to array type.
2326 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2327                                                        const char *GlobalName,
2328                                                        unsigned Alignment) {
2329   // Get the default prefix if a name wasn't specified.
2330   if (!GlobalName)
2331     GlobalName = ".str";
2332 
2333   // Don't share any string literals if strings aren't constant.
2334   if (LangOpts.WritableStrings)
2335     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2336 
2337   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2338     ConstantStringMap.GetOrCreateValue(Str);
2339 
2340   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2341     if (Alignment > GV->getAlignment()) {
2342       GV->setAlignment(Alignment);
2343     }
2344     return GV;
2345   }
2346 
2347   // Create a global variable for this.
2348   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2349                                                    Alignment);
2350   Entry.setValue(GV);
2351   return GV;
2352 }
2353 
2354 /// GetAddrOfConstantCString - Returns a pointer to a character
2355 /// array containing the literal and a terminating '\0'
2356 /// character. The result has pointer to array type.
2357 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2358                                                         const char *GlobalName,
2359                                                         unsigned Alignment) {
2360   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2361   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2362 }
2363 
2364 /// EmitObjCPropertyImplementations - Emit information for synthesized
2365 /// properties for an implementation.
2366 void CodeGenModule::EmitObjCPropertyImplementations(const
2367                                                     ObjCImplementationDecl *D) {
2368   for (ObjCImplementationDecl::propimpl_iterator
2369          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2370     ObjCPropertyImplDecl *PID = &*i;
2371 
2372     // Dynamic is just for type-checking.
2373     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2374       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2375 
2376       // Determine which methods need to be implemented, some may have
2377       // been overridden. Note that ::isSynthesized is not the method
2378       // we want, that just indicates if the decl came from a
2379       // property. What we want to know is if the method is defined in
2380       // this implementation.
2381       if (!D->getInstanceMethod(PD->getGetterName()))
2382         CodeGenFunction(*this).GenerateObjCGetter(
2383                                  const_cast<ObjCImplementationDecl *>(D), PID);
2384       if (!PD->isReadOnly() &&
2385           !D->getInstanceMethod(PD->getSetterName()))
2386         CodeGenFunction(*this).GenerateObjCSetter(
2387                                  const_cast<ObjCImplementationDecl *>(D), PID);
2388     }
2389   }
2390 }
2391 
2392 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2393   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2394   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2395        ivar; ivar = ivar->getNextIvar())
2396     if (ivar->getType().isDestructedType())
2397       return true;
2398 
2399   return false;
2400 }
2401 
2402 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2403 /// for an implementation.
2404 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2405   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2406   if (needsDestructMethod(D)) {
2407     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2408     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2409     ObjCMethodDecl *DTORMethod =
2410       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2411                              cxxSelector, getContext().VoidTy, 0, D,
2412                              /*isInstance=*/true, /*isVariadic=*/false,
2413                           /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
2414                              /*isDefined=*/false, ObjCMethodDecl::Required);
2415     D->addInstanceMethod(DTORMethod);
2416     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2417     D->setHasCXXStructors(true);
2418   }
2419 
2420   // If the implementation doesn't have any ivar initializers, we don't need
2421   // a .cxx_construct.
2422   if (D->getNumIvarInitializers() == 0)
2423     return;
2424 
2425   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2426   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2427   // The constructor returns 'self'.
2428   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2429                                                 D->getLocation(),
2430                                                 D->getLocation(),
2431                                                 cxxSelector,
2432                                                 getContext().getObjCIdType(), 0,
2433                                                 D, /*isInstance=*/true,
2434                                                 /*isVariadic=*/false,
2435                                                 /*isSynthesized=*/true,
2436                                                 /*isImplicitlyDeclared=*/true,
2437                                                 /*isDefined=*/false,
2438                                                 ObjCMethodDecl::Required);
2439   D->addInstanceMethod(CTORMethod);
2440   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2441   D->setHasCXXStructors(true);
2442 }
2443 
2444 /// EmitNamespace - Emit all declarations in a namespace.
2445 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2446   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2447        I != E; ++I)
2448     EmitTopLevelDecl(*I);
2449 }
2450 
2451 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2452 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2453   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2454       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2455     ErrorUnsupported(LSD, "linkage spec");
2456     return;
2457   }
2458 
2459   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2460        I != E; ++I)
2461     EmitTopLevelDecl(*I);
2462 }
2463 
2464 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2465 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2466   // If an error has occurred, stop code generation, but continue
2467   // parsing and semantic analysis (to ensure all warnings and errors
2468   // are emitted).
2469   if (Diags.hasErrorOccurred())
2470     return;
2471 
2472   // Ignore dependent declarations.
2473   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2474     return;
2475 
2476   switch (D->getKind()) {
2477   case Decl::CXXConversion:
2478   case Decl::CXXMethod:
2479   case Decl::Function:
2480     // Skip function templates
2481     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2482         cast<FunctionDecl>(D)->isLateTemplateParsed())
2483       return;
2484 
2485     EmitGlobal(cast<FunctionDecl>(D));
2486     break;
2487 
2488   case Decl::Var:
2489     EmitGlobal(cast<VarDecl>(D));
2490     break;
2491 
2492   // Indirect fields from global anonymous structs and unions can be
2493   // ignored; only the actual variable requires IR gen support.
2494   case Decl::IndirectField:
2495     break;
2496 
2497   // C++ Decls
2498   case Decl::Namespace:
2499     EmitNamespace(cast<NamespaceDecl>(D));
2500     break;
2501     // No code generation needed.
2502   case Decl::UsingShadow:
2503   case Decl::Using:
2504   case Decl::UsingDirective:
2505   case Decl::ClassTemplate:
2506   case Decl::FunctionTemplate:
2507   case Decl::TypeAliasTemplate:
2508   case Decl::NamespaceAlias:
2509   case Decl::Block:
2510   case Decl::Import:
2511     break;
2512   case Decl::CXXConstructor:
2513     // Skip function templates
2514     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2515         cast<FunctionDecl>(D)->isLateTemplateParsed())
2516       return;
2517 
2518     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2519     break;
2520   case Decl::CXXDestructor:
2521     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2522       return;
2523     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2524     break;
2525 
2526   case Decl::StaticAssert:
2527     // Nothing to do.
2528     break;
2529 
2530   // Objective-C Decls
2531 
2532   // Forward declarations, no (immediate) code generation.
2533   case Decl::ObjCInterface:
2534     break;
2535 
2536   case Decl::ObjCCategory: {
2537     ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2538     if (CD->IsClassExtension() && CD->hasSynthBitfield())
2539       Context.ResetObjCLayout(CD->getClassInterface());
2540     break;
2541   }
2542 
2543   case Decl::ObjCProtocol: {
2544     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2545     if (Proto->isThisDeclarationADefinition())
2546       ObjCRuntime->GenerateProtocol(Proto);
2547     break;
2548   }
2549 
2550   case Decl::ObjCCategoryImpl:
2551     // Categories have properties but don't support synthesize so we
2552     // can ignore them here.
2553     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2554     break;
2555 
2556   case Decl::ObjCImplementation: {
2557     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2558     if (LangOpts.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2559       Context.ResetObjCLayout(OMD->getClassInterface());
2560     EmitObjCPropertyImplementations(OMD);
2561     EmitObjCIvarInitializations(OMD);
2562     ObjCRuntime->GenerateClass(OMD);
2563     // Emit global variable debug information.
2564     if (CGDebugInfo *DI = getModuleDebugInfo())
2565       DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()),
2566 				   OMD->getLocation());
2567 
2568     break;
2569   }
2570   case Decl::ObjCMethod: {
2571     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2572     // If this is not a prototype, emit the body.
2573     if (OMD->getBody())
2574       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2575     break;
2576   }
2577   case Decl::ObjCCompatibleAlias:
2578     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2579     break;
2580 
2581   case Decl::LinkageSpec:
2582     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2583     break;
2584 
2585   case Decl::FileScopeAsm: {
2586     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2587     StringRef AsmString = AD->getAsmString()->getString();
2588 
2589     const std::string &S = getModule().getModuleInlineAsm();
2590     if (S.empty())
2591       getModule().setModuleInlineAsm(AsmString);
2592     else if (*--S.end() == '\n')
2593       getModule().setModuleInlineAsm(S + AsmString.str());
2594     else
2595       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2596     break;
2597   }
2598 
2599   default:
2600     // Make sure we handled everything we should, every other kind is a
2601     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2602     // function. Need to recode Decl::Kind to do that easily.
2603     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2604   }
2605 }
2606 
2607 /// Turns the given pointer into a constant.
2608 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2609                                           const void *Ptr) {
2610   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2611   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2612   return llvm::ConstantInt::get(i64, PtrInt);
2613 }
2614 
2615 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2616                                    llvm::NamedMDNode *&GlobalMetadata,
2617                                    GlobalDecl D,
2618                                    llvm::GlobalValue *Addr) {
2619   if (!GlobalMetadata)
2620     GlobalMetadata =
2621       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2622 
2623   // TODO: should we report variant information for ctors/dtors?
2624   llvm::Value *Ops[] = {
2625     Addr,
2626     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2627   };
2628   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2629 }
2630 
2631 /// Emits metadata nodes associating all the global values in the
2632 /// current module with the Decls they came from.  This is useful for
2633 /// projects using IR gen as a subroutine.
2634 ///
2635 /// Since there's currently no way to associate an MDNode directly
2636 /// with an llvm::GlobalValue, we create a global named metadata
2637 /// with the name 'clang.global.decl.ptrs'.
2638 void CodeGenModule::EmitDeclMetadata() {
2639   llvm::NamedMDNode *GlobalMetadata = 0;
2640 
2641   // StaticLocalDeclMap
2642   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2643          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2644        I != E; ++I) {
2645     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2646     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2647   }
2648 }
2649 
2650 /// Emits metadata nodes for all the local variables in the current
2651 /// function.
2652 void CodeGenFunction::EmitDeclMetadata() {
2653   if (LocalDeclMap.empty()) return;
2654 
2655   llvm::LLVMContext &Context = getLLVMContext();
2656 
2657   // Find the unique metadata ID for this name.
2658   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2659 
2660   llvm::NamedMDNode *GlobalMetadata = 0;
2661 
2662   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2663          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2664     const Decl *D = I->first;
2665     llvm::Value *Addr = I->second;
2666 
2667     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2668       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2669       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2670     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2671       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2672       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2673     }
2674   }
2675 }
2676 
2677 void CodeGenModule::EmitCoverageFile() {
2678   if (!getCodeGenOpts().CoverageFile.empty()) {
2679     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2680       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2681       llvm::LLVMContext &Ctx = TheModule.getContext();
2682       llvm::MDString *CoverageFile =
2683           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
2684       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2685         llvm::MDNode *CU = CUNode->getOperand(i);
2686         llvm::Value *node[] = { CoverageFile, CU };
2687         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2688         GCov->addOperand(N);
2689       }
2690     }
2691   }
2692 }
2693