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