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