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