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