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