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