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