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