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