xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision c6a47895f73b8e4489b4a724942bad439c6dde3f)
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 static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
168   switch (V) {
169   case DefaultVisibility:   return llvm::GlobalValue::DefaultVisibility;
170   case HiddenVisibility:    return llvm::GlobalValue::HiddenVisibility;
171   case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
172   }
173   llvm_unreachable("unknown visibility!");
174   return llvm::GlobalValue::DefaultVisibility;
175 }
176 
177 
178 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
179                                         const NamedDecl *D) const {
180   // Internal definitions always have default visibility.
181   if (GV->hasLocalLinkage()) {
182     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
183     return;
184   }
185 
186   // Set visibility for definitions.
187   NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
188   if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
189     GV->setVisibility(GetLLVMVisibility(LV.visibility()));
190 }
191 
192 /// Set the symbol visibility of type information (vtable and RTTI)
193 /// associated with the given type.
194 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
195                                       const CXXRecordDecl *RD,
196                                       bool IsForRTTI) const {
197   setGlobalVisibility(GV, RD);
198 
199   if (!CodeGenOpts.HiddenWeakVTables)
200     return;
201 
202   // We want to drop the visibility to hidden for weak type symbols.
203   // This isn't possible if there might be unresolved references
204   // elsewhere that rely on this symbol being visible.
205 
206   // This should be kept roughly in sync with setThunkVisibility
207   // in CGVTables.cpp.
208 
209   // Preconditions.
210   if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
211       GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
212     return;
213 
214   // Don't override an explicit visibility attribute.
215   if (RD->hasAttr<VisibilityAttr>())
216     return;
217 
218   switch (RD->getTemplateSpecializationKind()) {
219   // We have to disable the optimization if this is an EI definition
220   // because there might be EI declarations in other shared objects.
221   case TSK_ExplicitInstantiationDefinition:
222   case TSK_ExplicitInstantiationDeclaration:
223     return;
224 
225   // Every use of a non-template class's type information has to emit it.
226   case TSK_Undeclared:
227     break;
228 
229   // In theory, implicit instantiations can ignore the possibility of
230   // an explicit instantiation declaration because there necessarily
231   // must be an EI definition somewhere with default visibility.  In
232   // practice, it's possible to have an explicit instantiation for
233   // an arbitrary template class, and linkers aren't necessarily able
234   // to deal with mixed-visibility symbols.
235   case TSK_ExplicitSpecialization:
236   case TSK_ImplicitInstantiation:
237     if (!CodeGenOpts.HiddenWeakTemplateVTables)
238       return;
239     break;
240   }
241 
242   // If there's a key function, there may be translation units
243   // that don't have the key function's definition.  But ignore
244   // this if we're emitting RTTI under -fno-rtti.
245   if (!IsForRTTI || Features.RTTI)
246     if (Context.getKeyFunction(RD))
247       return;
248 
249   // Otherwise, drop the visibility to hidden.
250   GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
251   GV->setUnnamedAddr(true);
252 }
253 
254 llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
255   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
256 
257   llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
258   if (!Str.empty())
259     return Str;
260 
261   if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
262     IdentifierInfo *II = ND->getIdentifier();
263     assert(II && "Attempt to mangle unnamed decl.");
264 
265     Str = II->getName();
266     return Str;
267   }
268 
269   llvm::SmallString<256> Buffer;
270   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
271     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
272   else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
273     getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
274   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
275     getCXXABI().getMangleContext().mangleBlock(BD, Buffer);
276   else
277     getCXXABI().getMangleContext().mangleName(ND, Buffer);
278 
279   // Allocate space for the mangled name.
280   size_t Length = Buffer.size();
281   char *Name = MangledNamesAllocator.Allocate<char>(Length);
282   std::copy(Buffer.begin(), Buffer.end(), Name);
283 
284   Str = llvm::StringRef(Name, Length);
285 
286   return Str;
287 }
288 
289 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
290                                         const BlockDecl *BD) {
291   MangleContext &MangleCtx = getCXXABI().getMangleContext();
292   const Decl *D = GD.getDecl();
293   if (D == 0)
294     MangleCtx.mangleGlobalBlock(BD, Buffer.getBuffer());
295   else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
296     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Buffer.getBuffer());
297   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
298     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Buffer.getBuffer());
299   else
300     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Buffer.getBuffer());
301 }
302 
303 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
304   return getModule().getNamedValue(Name);
305 }
306 
307 /// AddGlobalCtor - Add a function to the list that will be called before
308 /// main() runs.
309 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
310   // FIXME: Type coercion of void()* types.
311   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
312 }
313 
314 /// AddGlobalDtor - Add a function to the list that will be called
315 /// when the module is unloaded.
316 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
317   // FIXME: Type coercion of void()* types.
318   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
319 }
320 
321 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
322   // Ctor function type is void()*.
323   llvm::FunctionType* CtorFTy =
324     llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
325   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
326 
327   // Get the type of a ctor entry, { i32, void ()* }.
328   llvm::StructType* CtorStructTy =
329     llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
330                           llvm::PointerType::getUnqual(CtorFTy), NULL);
331 
332   // Construct the constructor and destructor arrays.
333   std::vector<llvm::Constant*> Ctors;
334   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
335     std::vector<llvm::Constant*> S;
336     S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
337                 I->second, false));
338     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
339     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
340   }
341 
342   if (!Ctors.empty()) {
343     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
344     new llvm::GlobalVariable(TheModule, AT, false,
345                              llvm::GlobalValue::AppendingLinkage,
346                              llvm::ConstantArray::get(AT, Ctors),
347                              GlobalName);
348   }
349 }
350 
351 void CodeGenModule::EmitAnnotations() {
352   if (Annotations.empty())
353     return;
354 
355   // Create a new global variable for the ConstantStruct in the Module.
356   llvm::Constant *Array =
357   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
358                                                 Annotations.size()),
359                            Annotations);
360   llvm::GlobalValue *gv =
361   new llvm::GlobalVariable(TheModule, Array->getType(), false,
362                            llvm::GlobalValue::AppendingLinkage, Array,
363                            "llvm.global.annotations");
364   gv->setSection("llvm.metadata");
365 }
366 
367 llvm::GlobalValue::LinkageTypes
368 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
369   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
370 
371   if (Linkage == GVA_Internal)
372     return llvm::Function::InternalLinkage;
373 
374   if (D->hasAttr<DLLExportAttr>())
375     return llvm::Function::DLLExportLinkage;
376 
377   if (D->hasAttr<WeakAttr>())
378     return llvm::Function::WeakAnyLinkage;
379 
380   // In C99 mode, 'inline' functions are guaranteed to have a strong
381   // definition somewhere else, so we can use available_externally linkage.
382   if (Linkage == GVA_C99Inline)
383     return llvm::Function::AvailableExternallyLinkage;
384 
385   // In C++, the compiler has to emit a definition in every translation unit
386   // that references the function.  We should use linkonce_odr because
387   // a) if all references in this translation unit are optimized away, we
388   // don't need to codegen it.  b) if the function persists, it needs to be
389   // merged with other definitions. c) C++ has the ODR, so we know the
390   // definition is dependable.
391   if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
392     return llvm::Function::LinkOnceODRLinkage;
393 
394   // An explicit instantiation of a template has weak linkage, since
395   // explicit instantiations can occur in multiple translation units
396   // and must all be equivalent. However, we are not allowed to
397   // throw away these explicit instantiations.
398   if (Linkage == GVA_ExplicitTemplateInstantiation)
399     return llvm::Function::WeakODRLinkage;
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 (isa<NamedDecl>(D))
461     setGlobalVisibility(GV, cast<NamedDecl>(D));
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         if (KeyFunction->isInlined())
1092           return llvm::GlobalVariable::LinkOnceODRLinkage;
1093 
1094         return llvm::GlobalVariable::ExternalLinkage;
1095 
1096       case TSK_ImplicitInstantiation:
1097         return llvm::GlobalVariable::LinkOnceODRLinkage;
1098 
1099       case TSK_ExplicitInstantiationDefinition:
1100         return llvm::GlobalVariable::WeakODRLinkage;
1101 
1102       case TSK_ExplicitInstantiationDeclaration:
1103         // FIXME: Use available_externally linkage. However, this currently
1104         // breaks LLVM's build due to undefined symbols.
1105         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1106         return llvm::GlobalVariable::LinkOnceODRLinkage;
1107     }
1108   }
1109 
1110   switch (RD->getTemplateSpecializationKind()) {
1111   case TSK_Undeclared:
1112   case TSK_ExplicitSpecialization:
1113   case TSK_ImplicitInstantiation:
1114     return llvm::GlobalVariable::LinkOnceODRLinkage;
1115 
1116   case TSK_ExplicitInstantiationDefinition:
1117     return llvm::GlobalVariable::WeakODRLinkage;
1118 
1119   case TSK_ExplicitInstantiationDeclaration:
1120     // FIXME: Use available_externally linkage. However, this currently
1121     // breaks LLVM's build due to undefined symbols.
1122     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1123     return llvm::GlobalVariable::LinkOnceODRLinkage;
1124   }
1125 
1126   // Silence GCC warning.
1127   return llvm::GlobalVariable::LinkOnceODRLinkage;
1128 }
1129 
1130 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1131     return Context.toCharUnitsFromBits(
1132       TheTargetData.getTypeStoreSizeInBits(Ty));
1133 }
1134 
1135 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1136   llvm::Constant *Init = 0;
1137   QualType ASTTy = D->getType();
1138   bool NonConstInit = false;
1139 
1140   const Expr *InitExpr = D->getAnyInitializer();
1141 
1142   if (!InitExpr) {
1143     // This is a tentative definition; tentative definitions are
1144     // implicitly initialized with { 0 }.
1145     //
1146     // Note that tentative definitions are only emitted at the end of
1147     // a translation unit, so they should never have incomplete
1148     // type. In addition, EmitTentativeDefinition makes sure that we
1149     // never attempt to emit a tentative definition if a real one
1150     // exists. A use may still exists, however, so we still may need
1151     // to do a RAUW.
1152     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1153     Init = EmitNullConstant(D->getType());
1154   } else {
1155     Init = EmitConstantExpr(InitExpr, D->getType());
1156     if (!Init) {
1157       QualType T = InitExpr->getType();
1158       if (D->getType()->isReferenceType())
1159         T = D->getType();
1160 
1161       if (getLangOptions().CPlusPlus) {
1162         Init = EmitNullConstant(T);
1163         NonConstInit = true;
1164       } else {
1165         ErrorUnsupported(D, "static initializer");
1166         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1167       }
1168     } else {
1169       // We don't need an initializer, so remove the entry for the delayed
1170       // initializer position (just in case this entry was delayed).
1171       if (getLangOptions().CPlusPlus)
1172         DelayedCXXInitPosition.erase(D);
1173     }
1174   }
1175 
1176   const llvm::Type* InitType = Init->getType();
1177   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1178 
1179   // Strip off a bitcast if we got one back.
1180   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1181     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1182            // all zero index gep.
1183            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1184     Entry = CE->getOperand(0);
1185   }
1186 
1187   // Entry is now either a Function or GlobalVariable.
1188   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1189 
1190   // We have a definition after a declaration with the wrong type.
1191   // We must make a new GlobalVariable* and update everything that used OldGV
1192   // (a declaration or tentative definition) with the new GlobalVariable*
1193   // (which will be a definition).
1194   //
1195   // This happens if there is a prototype for a global (e.g.
1196   // "extern int x[];") and then a definition of a different type (e.g.
1197   // "int x[10];"). This also happens when an initializer has a different type
1198   // from the type of the global (this happens with unions).
1199   if (GV == 0 ||
1200       GV->getType()->getElementType() != InitType ||
1201       GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
1202 
1203     // Move the old entry aside so that we'll create a new one.
1204     Entry->setName(llvm::StringRef());
1205 
1206     // Make a new global with the correct type, this is now guaranteed to work.
1207     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1208 
1209     // Replace all uses of the old global with the new global
1210     llvm::Constant *NewPtrForOldDecl =
1211         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1212     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1213 
1214     // Erase the old global, since it is no longer used.
1215     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1216   }
1217 
1218   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1219     SourceManager &SM = Context.getSourceManager();
1220     AddAnnotation(EmitAnnotateAttr(GV, AA,
1221                               SM.getInstantiationLineNumber(D->getLocation())));
1222   }
1223 
1224   GV->setInitializer(Init);
1225 
1226   // If it is safe to mark the global 'constant', do so now.
1227   GV->setConstant(false);
1228   if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1229     GV->setConstant(true);
1230 
1231   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1232 
1233   // Set the llvm linkage type as appropriate.
1234   llvm::GlobalValue::LinkageTypes Linkage =
1235     GetLLVMLinkageVarDefinition(D, GV);
1236   GV->setLinkage(Linkage);
1237   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1238     // common vars aren't constant even if declared const.
1239     GV->setConstant(false);
1240 
1241   SetCommonAttributes(D, GV);
1242 
1243   // Emit the initializer function if necessary.
1244   if (NonConstInit)
1245     EmitCXXGlobalVarDeclInitFunc(D, GV);
1246 
1247   // Emit global variable debug information.
1248   if (CGDebugInfo *DI = getDebugInfo()) {
1249     DI->setLocation(D->getLocation());
1250     DI->EmitGlobalVariable(GV, D);
1251   }
1252 }
1253 
1254 llvm::GlobalValue::LinkageTypes
1255 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1256                                            llvm::GlobalVariable *GV) {
1257   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1258   if (Linkage == GVA_Internal)
1259     return llvm::Function::InternalLinkage;
1260   else if (D->hasAttr<DLLImportAttr>())
1261     return llvm::Function::DLLImportLinkage;
1262   else if (D->hasAttr<DLLExportAttr>())
1263     return llvm::Function::DLLExportLinkage;
1264   else if (D->hasAttr<WeakAttr>()) {
1265     if (GV->isConstant())
1266       return llvm::GlobalVariable::WeakODRLinkage;
1267     else
1268       return llvm::GlobalVariable::WeakAnyLinkage;
1269   } else if (Linkage == GVA_TemplateInstantiation ||
1270              Linkage == GVA_ExplicitTemplateInstantiation)
1271     // FIXME: It seems like we can provide more specific linkage here
1272     // (LinkOnceODR, WeakODR).
1273     return llvm::GlobalVariable::WeakAnyLinkage;
1274   else if (!getLangOptions().CPlusPlus &&
1275            ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1276              D->getAttr<CommonAttr>()) &&
1277            !D->hasExternalStorage() && !D->getInit() &&
1278            !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1279     // Thread local vars aren't considered common linkage.
1280     return llvm::GlobalVariable::CommonLinkage;
1281   }
1282   return llvm::GlobalVariable::ExternalLinkage;
1283 }
1284 
1285 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1286 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1287 /// existing call uses of the old function in the module, this adjusts them to
1288 /// call the new function directly.
1289 ///
1290 /// This is not just a cleanup: the always_inline pass requires direct calls to
1291 /// functions to be able to inline them.  If there is a bitcast in the way, it
1292 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1293 /// run at -O0.
1294 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1295                                                       llvm::Function *NewFn) {
1296   // If we're redefining a global as a function, don't transform it.
1297   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1298   if (OldFn == 0) return;
1299 
1300   const llvm::Type *NewRetTy = NewFn->getReturnType();
1301   llvm::SmallVector<llvm::Value*, 4> ArgList;
1302 
1303   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1304        UI != E; ) {
1305     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1306     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1307     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1308     if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1309     llvm::CallSite CS(CI);
1310     if (!CI || !CS.isCallee(I)) continue;
1311 
1312     // If the return types don't match exactly, and if the call isn't dead, then
1313     // we can't transform this call.
1314     if (CI->getType() != NewRetTy && !CI->use_empty())
1315       continue;
1316 
1317     // If the function was passed too few arguments, don't transform.  If extra
1318     // arguments were passed, we silently drop them.  If any of the types
1319     // mismatch, we don't transform.
1320     unsigned ArgNo = 0;
1321     bool DontTransform = false;
1322     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1323          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1324       if (CS.arg_size() == ArgNo ||
1325           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1326         DontTransform = true;
1327         break;
1328       }
1329     }
1330     if (DontTransform)
1331       continue;
1332 
1333     // Okay, we can transform this.  Create the new call instruction and copy
1334     // over the required information.
1335     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1336     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1337                                                      ArgList.end(), "", CI);
1338     ArgList.clear();
1339     if (!NewCall->getType()->isVoidTy())
1340       NewCall->takeName(CI);
1341     NewCall->setAttributes(CI->getAttributes());
1342     NewCall->setCallingConv(CI->getCallingConv());
1343 
1344     // Finally, remove the old call, replacing any uses with the new one.
1345     if (!CI->use_empty())
1346       CI->replaceAllUsesWith(NewCall);
1347 
1348     // Copy debug location attached to CI.
1349     if (!CI->getDebugLoc().isUnknown())
1350       NewCall->setDebugLoc(CI->getDebugLoc());
1351     CI->eraseFromParent();
1352   }
1353 }
1354 
1355 
1356 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1357   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1358   const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
1359   // Get or create the prototype for the function.
1360   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1361 
1362   // Strip off a bitcast if we got one back.
1363   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1364     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1365     Entry = CE->getOperand(0);
1366   }
1367 
1368 
1369   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1370     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1371 
1372     // If the types mismatch then we have to rewrite the definition.
1373     assert(OldFn->isDeclaration() &&
1374            "Shouldn't replace non-declaration");
1375 
1376     // F is the Function* for the one with the wrong type, we must make a new
1377     // Function* and update everything that used F (a declaration) with the new
1378     // Function* (which will be a definition).
1379     //
1380     // This happens if there is a prototype for a function
1381     // (e.g. "int f()") and then a definition of a different type
1382     // (e.g. "int f(int x)").  Move the old function aside so that it
1383     // doesn't interfere with GetAddrOfFunction.
1384     OldFn->setName(llvm::StringRef());
1385     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1386 
1387     // If this is an implementation of a function without a prototype, try to
1388     // replace any existing uses of the function (which may be calls) with uses
1389     // of the new function
1390     if (D->getType()->isFunctionNoProtoType()) {
1391       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1392       OldFn->removeDeadConstantUsers();
1393     }
1394 
1395     // Replace uses of F with the Function we will endow with a body.
1396     if (!Entry->use_empty()) {
1397       llvm::Constant *NewPtrForOldDecl =
1398         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1399       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1400     }
1401 
1402     // Ok, delete the old function now, which is dead.
1403     OldFn->eraseFromParent();
1404 
1405     Entry = NewFn;
1406   }
1407 
1408   // We need to set linkage and visibility on the function before
1409   // generating code for it because various parts of IR generation
1410   // want to propagate this information down (e.g. to local static
1411   // declarations).
1412   llvm::Function *Fn = cast<llvm::Function>(Entry);
1413   setFunctionLinkage(D, Fn);
1414 
1415   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1416   setGlobalVisibility(Fn, D);
1417 
1418   CodeGenFunction(*this).GenerateCode(D, Fn);
1419 
1420   SetFunctionDefinitionAttributes(D, Fn);
1421   SetLLVMFunctionAttributesForDefinition(D, Fn);
1422 
1423   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1424     AddGlobalCtor(Fn, CA->getPriority());
1425   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1426     AddGlobalDtor(Fn, DA->getPriority());
1427 }
1428 
1429 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1430   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1431   const AliasAttr *AA = D->getAttr<AliasAttr>();
1432   assert(AA && "Not an alias?");
1433 
1434   llvm::StringRef MangledName = getMangledName(GD);
1435 
1436   // If there is a definition in the module, then it wins over the alias.
1437   // This is dubious, but allow it to be safe.  Just ignore the alias.
1438   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1439   if (Entry && !Entry->isDeclaration())
1440     return;
1441 
1442   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1443 
1444   // Create a reference to the named value.  This ensures that it is emitted
1445   // if a deferred decl.
1446   llvm::Constant *Aliasee;
1447   if (isa<llvm::FunctionType>(DeclTy))
1448     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
1449   else
1450     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1451                                     llvm::PointerType::getUnqual(DeclTy), 0);
1452 
1453   // Create the new alias itself, but don't set a name yet.
1454   llvm::GlobalValue *GA =
1455     new llvm::GlobalAlias(Aliasee->getType(),
1456                           llvm::Function::ExternalLinkage,
1457                           "", Aliasee, &getModule());
1458 
1459   if (Entry) {
1460     assert(Entry->isDeclaration());
1461 
1462     // If there is a declaration in the module, then we had an extern followed
1463     // by the alias, as in:
1464     //   extern int test6();
1465     //   ...
1466     //   int test6() __attribute__((alias("test7")));
1467     //
1468     // Remove it and replace uses of it with the alias.
1469     GA->takeName(Entry);
1470 
1471     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1472                                                           Entry->getType()));
1473     Entry->eraseFromParent();
1474   } else {
1475     GA->setName(MangledName);
1476   }
1477 
1478   // Set attributes which are particular to an alias; this is a
1479   // specialization of the attributes which may be set on a global
1480   // variable/function.
1481   if (D->hasAttr<DLLExportAttr>()) {
1482     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1483       // The dllexport attribute is ignored for undefined symbols.
1484       if (FD->hasBody())
1485         GA->setLinkage(llvm::Function::DLLExportLinkage);
1486     } else {
1487       GA->setLinkage(llvm::Function::DLLExportLinkage);
1488     }
1489   } else if (D->hasAttr<WeakAttr>() ||
1490              D->hasAttr<WeakRefAttr>() ||
1491              D->hasAttr<WeakImportAttr>()) {
1492     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1493   }
1494 
1495   SetCommonAttributes(D, GA);
1496 }
1497 
1498 /// getBuiltinLibFunction - Given a builtin id for a function like
1499 /// "__builtin_fabsf", return a Function* for "fabsf".
1500 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1501                                                   unsigned BuiltinID) {
1502   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1503           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1504          "isn't a lib fn");
1505 
1506   // Get the name, skip over the __builtin_ prefix (if necessary).
1507   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1508   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1509     Name += 10;
1510 
1511   const llvm::FunctionType *Ty =
1512     cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1513 
1514   return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
1515 }
1516 
1517 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1518                                             unsigned NumTys) {
1519   return llvm::Intrinsic::getDeclaration(&getModule(),
1520                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
1521 }
1522 
1523 static llvm::StringMapEntry<llvm::Constant*> &
1524 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1525                          const StringLiteral *Literal,
1526                          bool TargetIsLSB,
1527                          bool &IsUTF16,
1528                          unsigned &StringLength) {
1529   llvm::StringRef String = Literal->getString();
1530   unsigned NumBytes = String.size();
1531 
1532   // Check for simple case.
1533   if (!Literal->containsNonAsciiOrNull()) {
1534     StringLength = NumBytes;
1535     return Map.GetOrCreateValue(String);
1536   }
1537 
1538   // Otherwise, convert the UTF8 literals into a byte string.
1539   llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1540   const UTF8 *FromPtr = (UTF8 *)String.data();
1541   UTF16 *ToPtr = &ToBuf[0];
1542 
1543   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1544                            &ToPtr, ToPtr + NumBytes,
1545                            strictConversion);
1546 
1547   // ConvertUTF8toUTF16 returns the length in ToPtr.
1548   StringLength = ToPtr - &ToBuf[0];
1549 
1550   // Render the UTF-16 string into a byte array and convert to the target byte
1551   // order.
1552   //
1553   // FIXME: This isn't something we should need to do here.
1554   llvm::SmallString<128> AsBytes;
1555   AsBytes.reserve(StringLength * 2);
1556   for (unsigned i = 0; i != StringLength; ++i) {
1557     unsigned short Val = ToBuf[i];
1558     if (TargetIsLSB) {
1559       AsBytes.push_back(Val & 0xFF);
1560       AsBytes.push_back(Val >> 8);
1561     } else {
1562       AsBytes.push_back(Val >> 8);
1563       AsBytes.push_back(Val & 0xFF);
1564     }
1565   }
1566   // Append one extra null character, the second is automatically added by our
1567   // caller.
1568   AsBytes.push_back(0);
1569 
1570   IsUTF16 = true;
1571   return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1572 }
1573 
1574 llvm::Constant *
1575 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1576   unsigned StringLength = 0;
1577   bool isUTF16 = false;
1578   llvm::StringMapEntry<llvm::Constant*> &Entry =
1579     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1580                              getTargetData().isLittleEndian(),
1581                              isUTF16, StringLength);
1582 
1583   if (llvm::Constant *C = Entry.getValue())
1584     return C;
1585 
1586   llvm::Constant *Zero =
1587       llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1588   llvm::Constant *Zeros[] = { Zero, Zero };
1589 
1590   // If we don't already have it, get __CFConstantStringClassReference.
1591   if (!CFConstantStringClassRef) {
1592     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1593     Ty = llvm::ArrayType::get(Ty, 0);
1594     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1595                                            "__CFConstantStringClassReference");
1596     // Decay array -> ptr
1597     CFConstantStringClassRef =
1598       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1599   }
1600 
1601   QualType CFTy = getContext().getCFConstantStringType();
1602 
1603   const llvm::StructType *STy =
1604     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1605 
1606   std::vector<llvm::Constant*> Fields(4);
1607 
1608   // Class pointer.
1609   Fields[0] = CFConstantStringClassRef;
1610 
1611   // Flags.
1612   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1613   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1614     llvm::ConstantInt::get(Ty, 0x07C8);
1615 
1616   // String pointer.
1617   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1618 
1619   llvm::GlobalValue::LinkageTypes Linkage;
1620   bool isConstant;
1621   if (isUTF16) {
1622     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1623     Linkage = llvm::GlobalValue::InternalLinkage;
1624     // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1625     // does make plain ascii ones writable.
1626     isConstant = true;
1627   } else {
1628     Linkage = llvm::GlobalValue::PrivateLinkage;
1629     isConstant = !Features.WritableStrings;
1630   }
1631 
1632   llvm::GlobalVariable *GV =
1633     new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1634                              ".str");
1635   GV->setUnnamedAddr(true);
1636   if (isUTF16) {
1637     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1638     GV->setAlignment(Align.getQuantity());
1639   }
1640   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1641 
1642   // String length.
1643   Ty = getTypes().ConvertType(getContext().LongTy);
1644   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1645 
1646   // The struct.
1647   C = llvm::ConstantStruct::get(STy, Fields);
1648   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1649                                 llvm::GlobalVariable::PrivateLinkage, C,
1650                                 "_unnamed_cfstring_");
1651   if (const char *Sect = getContext().Target.getCFStringSection())
1652     GV->setSection(Sect);
1653   Entry.setValue(GV);
1654 
1655   return GV;
1656 }
1657 
1658 llvm::Constant *
1659 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
1660   unsigned StringLength = 0;
1661   bool isUTF16 = false;
1662   llvm::StringMapEntry<llvm::Constant*> &Entry =
1663     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1664                              getTargetData().isLittleEndian(),
1665                              isUTF16, StringLength);
1666 
1667   if (llvm::Constant *C = Entry.getValue())
1668     return C;
1669 
1670   llvm::Constant *Zero =
1671   llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1672   llvm::Constant *Zeros[] = { Zero, Zero };
1673 
1674   // If we don't already have it, get _NSConstantStringClassReference.
1675   if (!ConstantStringClassRef) {
1676     std::string StringClass(getLangOptions().ObjCConstantStringClass);
1677     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1678     Ty = llvm::ArrayType::get(Ty, 0);
1679     llvm::Constant *GV;
1680     if (StringClass.empty())
1681       GV = CreateRuntimeVariable(Ty,
1682                                  Features.ObjCNonFragileABI ?
1683                                  "OBJC_CLASS_$_NSConstantString" :
1684                                  "_NSConstantStringClassReference");
1685     else {
1686       std::string str;
1687       if (Features.ObjCNonFragileABI)
1688         str = "OBJC_CLASS_$_" + StringClass;
1689       else
1690         str = "_" + StringClass + "ClassReference";
1691       GV = CreateRuntimeVariable(Ty, str);
1692     }
1693     // Decay array -> ptr
1694     ConstantStringClassRef =
1695     llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1696   }
1697 
1698   QualType NSTy = getContext().getNSConstantStringType();
1699 
1700   const llvm::StructType *STy =
1701   cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1702 
1703   std::vector<llvm::Constant*> Fields(3);
1704 
1705   // Class pointer.
1706   Fields[0] = ConstantStringClassRef;
1707 
1708   // String pointer.
1709   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1710 
1711   llvm::GlobalValue::LinkageTypes Linkage;
1712   bool isConstant;
1713   if (isUTF16) {
1714     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1715     Linkage = llvm::GlobalValue::InternalLinkage;
1716     // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1717     // does make plain ascii ones writable.
1718     isConstant = true;
1719   } else {
1720     Linkage = llvm::GlobalValue::PrivateLinkage;
1721     isConstant = !Features.WritableStrings;
1722   }
1723 
1724   llvm::GlobalVariable *GV =
1725   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1726                            ".str");
1727   GV->setUnnamedAddr(true);
1728   if (isUTF16) {
1729     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1730     GV->setAlignment(Align.getQuantity());
1731   }
1732   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1733 
1734   // String length.
1735   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1736   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1737 
1738   // The struct.
1739   C = llvm::ConstantStruct::get(STy, Fields);
1740   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1741                                 llvm::GlobalVariable::PrivateLinkage, C,
1742                                 "_unnamed_nsstring_");
1743   // FIXME. Fix section.
1744   if (const char *Sect =
1745         Features.ObjCNonFragileABI
1746           ? getContext().Target.getNSStringNonFragileABISection()
1747           : getContext().Target.getNSStringSection())
1748     GV->setSection(Sect);
1749   Entry.setValue(GV);
1750 
1751   return GV;
1752 }
1753 
1754 /// GetStringForStringLiteral - Return the appropriate bytes for a
1755 /// string literal, properly padded to match the literal type.
1756 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1757   const ASTContext &Context = getContext();
1758   const ConstantArrayType *CAT =
1759     Context.getAsConstantArrayType(E->getType());
1760   assert(CAT && "String isn't pointer or array!");
1761 
1762   // Resize the string to the right size.
1763   uint64_t RealLen = CAT->getSize().getZExtValue();
1764 
1765   if (E->isWide())
1766     RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
1767 
1768   std::string Str = E->getString().str();
1769   Str.resize(RealLen, '\0');
1770 
1771   return Str;
1772 }
1773 
1774 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1775 /// constant array for the given string literal.
1776 llvm::Constant *
1777 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1778   // FIXME: This can be more efficient.
1779   // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1780   llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1781   if (S->isWide()) {
1782     llvm::Type *DestTy =
1783         llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1784     C = llvm::ConstantExpr::getBitCast(C, DestTy);
1785   }
1786   return C;
1787 }
1788 
1789 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1790 /// array for the given ObjCEncodeExpr node.
1791 llvm::Constant *
1792 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1793   std::string Str;
1794   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1795 
1796   return GetAddrOfConstantCString(Str);
1797 }
1798 
1799 
1800 /// GenerateWritableString -- Creates storage for a string literal.
1801 static llvm::Constant *GenerateStringLiteral(const std::string &str,
1802                                              bool constant,
1803                                              CodeGenModule &CGM,
1804                                              const char *GlobalName) {
1805   // Create Constant for this string literal. Don't add a '\0'.
1806   llvm::Constant *C =
1807       llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1808 
1809   // Create a global variable for this string
1810   llvm::GlobalVariable *GV =
1811     new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1812                              llvm::GlobalValue::PrivateLinkage,
1813                              C, GlobalName);
1814   GV->setUnnamedAddr(true);
1815   return GV;
1816 }
1817 
1818 /// GetAddrOfConstantString - Returns a pointer to a character array
1819 /// containing the literal. This contents are exactly that of the
1820 /// given string, i.e. it will not be null terminated automatically;
1821 /// see GetAddrOfConstantCString. Note that whether the result is
1822 /// actually a pointer to an LLVM constant depends on
1823 /// Feature.WriteableStrings.
1824 ///
1825 /// The result has pointer to array type.
1826 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1827                                                        const char *GlobalName) {
1828   bool IsConstant = !Features.WritableStrings;
1829 
1830   // Get the default prefix if a name wasn't specified.
1831   if (!GlobalName)
1832     GlobalName = ".str";
1833 
1834   // Don't share any string literals if strings aren't constant.
1835   if (!IsConstant)
1836     return GenerateStringLiteral(str, false, *this, GlobalName);
1837 
1838   llvm::StringMapEntry<llvm::Constant *> &Entry =
1839     ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1840 
1841   if (Entry.getValue())
1842     return Entry.getValue();
1843 
1844   // Create a global variable for this.
1845   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1846   Entry.setValue(C);
1847   return C;
1848 }
1849 
1850 /// GetAddrOfConstantCString - Returns a pointer to a character
1851 /// array containing the literal and a terminating '\-'
1852 /// character. The result has pointer to array type.
1853 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1854                                                         const char *GlobalName){
1855   return GetAddrOfConstantString(str + '\0', GlobalName);
1856 }
1857 
1858 /// EmitObjCPropertyImplementations - Emit information for synthesized
1859 /// properties for an implementation.
1860 void CodeGenModule::EmitObjCPropertyImplementations(const
1861                                                     ObjCImplementationDecl *D) {
1862   for (ObjCImplementationDecl::propimpl_iterator
1863          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1864     ObjCPropertyImplDecl *PID = *i;
1865 
1866     // Dynamic is just for type-checking.
1867     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1868       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1869 
1870       // Determine which methods need to be implemented, some may have
1871       // been overridden. Note that ::isSynthesized is not the method
1872       // we want, that just indicates if the decl came from a
1873       // property. What we want to know is if the method is defined in
1874       // this implementation.
1875       if (!D->getInstanceMethod(PD->getGetterName()))
1876         CodeGenFunction(*this).GenerateObjCGetter(
1877                                  const_cast<ObjCImplementationDecl *>(D), PID);
1878       if (!PD->isReadOnly() &&
1879           !D->getInstanceMethod(PD->getSetterName()))
1880         CodeGenFunction(*this).GenerateObjCSetter(
1881                                  const_cast<ObjCImplementationDecl *>(D), PID);
1882     }
1883   }
1884 }
1885 
1886 /// EmitObjCIvarInitializations - Emit information for ivar initialization
1887 /// for an implementation.
1888 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1889   if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1890     return;
1891   DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1892   assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1893   IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1894   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1895   ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1896                                                   D->getLocation(),
1897                                                   D->getLocation(), cxxSelector,
1898                                                   getContext().VoidTy, 0,
1899                                                   DC, true, false, true, false,
1900                                                   ObjCMethodDecl::Required);
1901   D->addInstanceMethod(DTORMethod);
1902   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1903 
1904   II = &getContext().Idents.get(".cxx_construct");
1905   cxxSelector = getContext().Selectors.getSelector(0, &II);
1906   // The constructor returns 'self'.
1907   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1908                                                 D->getLocation(),
1909                                                 D->getLocation(), cxxSelector,
1910                                                 getContext().getObjCIdType(), 0,
1911                                                 DC, true, false, true, false,
1912                                                 ObjCMethodDecl::Required);
1913   D->addInstanceMethod(CTORMethod);
1914   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1915 
1916 
1917 }
1918 
1919 /// EmitNamespace - Emit all declarations in a namespace.
1920 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1921   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1922        I != E; ++I)
1923     EmitTopLevelDecl(*I);
1924 }
1925 
1926 // EmitLinkageSpec - Emit all declarations in a linkage spec.
1927 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1928   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1929       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1930     ErrorUnsupported(LSD, "linkage spec");
1931     return;
1932   }
1933 
1934   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1935        I != E; ++I)
1936     EmitTopLevelDecl(*I);
1937 }
1938 
1939 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1940 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1941   // If an error has occurred, stop code generation, but continue
1942   // parsing and semantic analysis (to ensure all warnings and errors
1943   // are emitted).
1944   if (Diags.hasErrorOccurred())
1945     return;
1946 
1947   // Ignore dependent declarations.
1948   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1949     return;
1950 
1951   switch (D->getKind()) {
1952   case Decl::CXXConversion:
1953   case Decl::CXXMethod:
1954   case Decl::Function:
1955     // Skip function templates
1956     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1957       return;
1958 
1959     EmitGlobal(cast<FunctionDecl>(D));
1960     break;
1961 
1962   case Decl::Var:
1963     EmitGlobal(cast<VarDecl>(D));
1964     break;
1965 
1966   // C++ Decls
1967   case Decl::Namespace:
1968     EmitNamespace(cast<NamespaceDecl>(D));
1969     break;
1970     // No code generation needed.
1971   case Decl::UsingShadow:
1972   case Decl::Using:
1973   case Decl::UsingDirective:
1974   case Decl::ClassTemplate:
1975   case Decl::FunctionTemplate:
1976   case Decl::NamespaceAlias:
1977     break;
1978   case Decl::CXXConstructor:
1979     // Skip function templates
1980     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1981       return;
1982 
1983     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1984     break;
1985   case Decl::CXXDestructor:
1986     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1987     break;
1988 
1989   case Decl::StaticAssert:
1990     // Nothing to do.
1991     break;
1992 
1993   // Objective-C Decls
1994 
1995   // Forward declarations, no (immediate) code generation.
1996   case Decl::ObjCClass:
1997   case Decl::ObjCForwardProtocol:
1998   case Decl::ObjCInterface:
1999     break;
2000 
2001     case Decl::ObjCCategory: {
2002       ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2003       if (CD->IsClassExtension() && CD->hasSynthBitfield())
2004         Context.ResetObjCLayout(CD->getClassInterface());
2005       break;
2006     }
2007 
2008 
2009   case Decl::ObjCProtocol:
2010     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2011     break;
2012 
2013   case Decl::ObjCCategoryImpl:
2014     // Categories have properties but don't support synthesize so we
2015     // can ignore them here.
2016     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2017     break;
2018 
2019   case Decl::ObjCImplementation: {
2020     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2021     if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2022       Context.ResetObjCLayout(OMD->getClassInterface());
2023     EmitObjCPropertyImplementations(OMD);
2024     EmitObjCIvarInitializations(OMD);
2025     Runtime->GenerateClass(OMD);
2026     break;
2027   }
2028   case Decl::ObjCMethod: {
2029     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2030     // If this is not a prototype, emit the body.
2031     if (OMD->getBody())
2032       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2033     break;
2034   }
2035   case Decl::ObjCCompatibleAlias:
2036     // compatibility-alias is a directive and has no code gen.
2037     break;
2038 
2039   case Decl::LinkageSpec:
2040     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2041     break;
2042 
2043   case Decl::FileScopeAsm: {
2044     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2045     llvm::StringRef AsmString = AD->getAsmString()->getString();
2046 
2047     const std::string &S = getModule().getModuleInlineAsm();
2048     if (S.empty())
2049       getModule().setModuleInlineAsm(AsmString);
2050     else
2051       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2052     break;
2053   }
2054 
2055   default:
2056     // Make sure we handled everything we should, every other kind is a
2057     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2058     // function. Need to recode Decl::Kind to do that easily.
2059     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2060   }
2061 }
2062 
2063 /// Turns the given pointer into a constant.
2064 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2065                                           const void *Ptr) {
2066   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2067   const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2068   return llvm::ConstantInt::get(i64, PtrInt);
2069 }
2070 
2071 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2072                                    llvm::NamedMDNode *&GlobalMetadata,
2073                                    GlobalDecl D,
2074                                    llvm::GlobalValue *Addr) {
2075   if (!GlobalMetadata)
2076     GlobalMetadata =
2077       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2078 
2079   // TODO: should we report variant information for ctors/dtors?
2080   llvm::Value *Ops[] = {
2081     Addr,
2082     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2083   };
2084   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2085 }
2086 
2087 /// Emits metadata nodes associating all the global values in the
2088 /// current module with the Decls they came from.  This is useful for
2089 /// projects using IR gen as a subroutine.
2090 ///
2091 /// Since there's currently no way to associate an MDNode directly
2092 /// with an llvm::GlobalValue, we create a global named metadata
2093 /// with the name 'clang.global.decl.ptrs'.
2094 void CodeGenModule::EmitDeclMetadata() {
2095   llvm::NamedMDNode *GlobalMetadata = 0;
2096 
2097   // StaticLocalDeclMap
2098   for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2099          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2100        I != E; ++I) {
2101     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2102     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2103   }
2104 }
2105 
2106 /// Emits metadata nodes for all the local variables in the current
2107 /// function.
2108 void CodeGenFunction::EmitDeclMetadata() {
2109   if (LocalDeclMap.empty()) return;
2110 
2111   llvm::LLVMContext &Context = getLLVMContext();
2112 
2113   // Find the unique metadata ID for this name.
2114   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2115 
2116   llvm::NamedMDNode *GlobalMetadata = 0;
2117 
2118   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2119          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2120     const Decl *D = I->first;
2121     llvm::Value *Addr = I->second;
2122 
2123     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2124       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2125       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2126     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2127       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2128       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2129     }
2130   }
2131 }
2132 
2133 ///@name Custom Runtime Function Interfaces
2134 ///@{
2135 //
2136 // FIXME: These can be eliminated once we can have clients just get the required
2137 // AST nodes from the builtin tables.
2138 
2139 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2140   if (BlockObjectDispose)
2141     return BlockObjectDispose;
2142 
2143   // If we saw an explicit decl, use that.
2144   if (BlockObjectDisposeDecl) {
2145     return BlockObjectDispose = GetAddrOfFunction(
2146       BlockObjectDisposeDecl,
2147       getTypes().GetFunctionType(BlockObjectDisposeDecl));
2148   }
2149 
2150   // Otherwise construct the function by hand.
2151   const llvm::FunctionType *FTy;
2152   std::vector<const llvm::Type*> ArgTys;
2153   const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2154   ArgTys.push_back(PtrToInt8Ty);
2155   ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2156   FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2157   return BlockObjectDispose =
2158     CreateRuntimeFunction(FTy, "_Block_object_dispose");
2159 }
2160 
2161 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2162   if (BlockObjectAssign)
2163     return BlockObjectAssign;
2164 
2165   // If we saw an explicit decl, use that.
2166   if (BlockObjectAssignDecl) {
2167     return BlockObjectAssign = GetAddrOfFunction(
2168       BlockObjectAssignDecl,
2169       getTypes().GetFunctionType(BlockObjectAssignDecl));
2170   }
2171 
2172   // Otherwise construct the function by hand.
2173   const llvm::FunctionType *FTy;
2174   std::vector<const llvm::Type*> ArgTys;
2175   const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2176   ArgTys.push_back(PtrToInt8Ty);
2177   ArgTys.push_back(PtrToInt8Ty);
2178   ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2179   FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2180   return BlockObjectAssign =
2181     CreateRuntimeFunction(FTy, "_Block_object_assign");
2182 }
2183 
2184 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2185   if (NSConcreteGlobalBlock)
2186     return NSConcreteGlobalBlock;
2187 
2188   // If we saw an explicit decl, use that.
2189   if (NSConcreteGlobalBlockDecl) {
2190     return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2191       NSConcreteGlobalBlockDecl,
2192       getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2193   }
2194 
2195   // Otherwise construct the variable by hand.
2196   return NSConcreteGlobalBlock = CreateRuntimeVariable(
2197     PtrToInt8Ty, "_NSConcreteGlobalBlock");
2198 }
2199 
2200 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2201   if (NSConcreteStackBlock)
2202     return NSConcreteStackBlock;
2203 
2204   // If we saw an explicit decl, use that.
2205   if (NSConcreteStackBlockDecl) {
2206     return NSConcreteStackBlock = GetAddrOfGlobalVar(
2207       NSConcreteStackBlockDecl,
2208       getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2209   }
2210 
2211   // Otherwise construct the variable by hand.
2212   return NSConcreteStackBlock = CreateRuntimeVariable(
2213     PtrToInt8Ty, "_NSConcreteStackBlock");
2214 }
2215 
2216 ///@}
2217