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