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