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