xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 60a9fbf92152293b0ddfd8dae9bc612c92811a49)
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->setTLSKind(D->getTLSKind());
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   }
1920   return llvm::GlobalVariable::ExternalLinkage;
1921 }
1922 
1923 /// Replace the uses of a function that was declared with a non-proto type.
1924 /// We want to silently drop extra arguments from call sites
1925 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1926                                           llvm::Function *newFn) {
1927   // Fast path.
1928   if (old->use_empty()) return;
1929 
1930   llvm::Type *newRetTy = newFn->getReturnType();
1931   SmallVector<llvm::Value*, 4> newArgs;
1932 
1933   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1934          ui != ue; ) {
1935     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1936     llvm::User *user = *use;
1937 
1938     // Recognize and replace uses of bitcasts.  Most calls to
1939     // unprototyped functions will use bitcasts.
1940     if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1941       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1942         replaceUsesOfNonProtoConstant(bitcast, newFn);
1943       continue;
1944     }
1945 
1946     // Recognize calls to the function.
1947     llvm::CallSite callSite(user);
1948     if (!callSite) continue;
1949     if (!callSite.isCallee(use)) continue;
1950 
1951     // If the return types don't match exactly, then we can't
1952     // transform this call unless it's dead.
1953     if (callSite->getType() != newRetTy && !callSite->use_empty())
1954       continue;
1955 
1956     // Get the call site's attribute list.
1957     SmallVector<llvm::AttributeSet, 8> newAttrs;
1958     llvm::AttributeSet oldAttrs = callSite.getAttributes();
1959 
1960     // Collect any return attributes from the call.
1961     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
1962       newAttrs.push_back(
1963         llvm::AttributeSet::get(newFn->getContext(),
1964                                 oldAttrs.getRetAttributes()));
1965 
1966     // If the function was passed too few arguments, don't transform.
1967     unsigned newNumArgs = newFn->arg_size();
1968     if (callSite.arg_size() < newNumArgs) continue;
1969 
1970     // If extra arguments were passed, we silently drop them.
1971     // If any of the types mismatch, we don't transform.
1972     unsigned argNo = 0;
1973     bool dontTransform = false;
1974     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1975            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1976       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1977         dontTransform = true;
1978         break;
1979       }
1980 
1981       // Add any parameter attributes.
1982       if (oldAttrs.hasAttributes(argNo + 1))
1983         newAttrs.
1984           push_back(llvm::
1985                     AttributeSet::get(newFn->getContext(),
1986                                       oldAttrs.getParamAttributes(argNo + 1)));
1987     }
1988     if (dontTransform)
1989       continue;
1990 
1991     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
1992       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
1993                                                  oldAttrs.getFnAttributes()));
1994 
1995     // Okay, we can transform this.  Create the new call instruction and copy
1996     // over the required information.
1997     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
1998 
1999     llvm::CallSite newCall;
2000     if (callSite.isCall()) {
2001       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2002                                        callSite.getInstruction());
2003     } else {
2004       llvm::InvokeInst *oldInvoke =
2005         cast<llvm::InvokeInst>(callSite.getInstruction());
2006       newCall = llvm::InvokeInst::Create(newFn,
2007                                          oldInvoke->getNormalDest(),
2008                                          oldInvoke->getUnwindDest(),
2009                                          newArgs, "",
2010                                          callSite.getInstruction());
2011     }
2012     newArgs.clear(); // for the next iteration
2013 
2014     if (!newCall->getType()->isVoidTy())
2015       newCall->takeName(callSite.getInstruction());
2016     newCall.setAttributes(
2017                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2018     newCall.setCallingConv(callSite.getCallingConv());
2019 
2020     // Finally, remove the old call, replacing any uses with the new one.
2021     if (!callSite->use_empty())
2022       callSite->replaceAllUsesWith(newCall.getInstruction());
2023 
2024     // Copy debug location attached to CI.
2025     if (!callSite->getDebugLoc().isUnknown())
2026       newCall->setDebugLoc(callSite->getDebugLoc());
2027     callSite->eraseFromParent();
2028   }
2029 }
2030 
2031 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2032 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2033 /// existing call uses of the old function in the module, this adjusts them to
2034 /// call the new function directly.
2035 ///
2036 /// This is not just a cleanup: the always_inline pass requires direct calls to
2037 /// functions to be able to inline them.  If there is a bitcast in the way, it
2038 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2039 /// run at -O0.
2040 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2041                                                       llvm::Function *NewFn) {
2042   // If we're redefining a global as a function, don't transform it.
2043   if (!isa<llvm::Function>(Old)) return;
2044 
2045   replaceUsesOfNonProtoConstant(Old, NewFn);
2046 }
2047 
2048 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2049   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2050   // If we have a definition, this might be a deferred decl. If the
2051   // instantiation is explicit, make sure we emit it at the end.
2052   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2053     GetAddrOfGlobalVar(VD);
2054 
2055   EmitTopLevelDecl(VD);
2056 }
2057 
2058 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
2059   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2060 
2061   // Compute the function info and LLVM type.
2062   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2063   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2064 
2065   // Get or create the prototype for the function.
2066   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
2067 
2068   // Strip off a bitcast if we got one back.
2069   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2070     assert(CE->getOpcode() == llvm::Instruction::BitCast);
2071     Entry = CE->getOperand(0);
2072   }
2073 
2074 
2075   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2076     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
2077 
2078     // If the types mismatch then we have to rewrite the definition.
2079     assert(OldFn->isDeclaration() &&
2080            "Shouldn't replace non-declaration");
2081 
2082     // F is the Function* for the one with the wrong type, we must make a new
2083     // Function* and update everything that used F (a declaration) with the new
2084     // Function* (which will be a definition).
2085     //
2086     // This happens if there is a prototype for a function
2087     // (e.g. "int f()") and then a definition of a different type
2088     // (e.g. "int f(int x)").  Move the old function aside so that it
2089     // doesn't interfere with GetAddrOfFunction.
2090     OldFn->setName(StringRef());
2091     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2092 
2093     // This might be an implementation of a function without a
2094     // prototype, in which case, try to do special replacement of
2095     // calls which match the new prototype.  The really key thing here
2096     // is that we also potentially drop arguments from the call site
2097     // so as to make a direct call, which makes the inliner happier
2098     // and suppresses a number of optimizer warnings (!) about
2099     // dropping arguments.
2100     if (!OldFn->use_empty()) {
2101       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
2102       OldFn->removeDeadConstantUsers();
2103     }
2104 
2105     // Replace uses of F with the Function we will endow with a body.
2106     if (!Entry->use_empty()) {
2107       llvm::Constant *NewPtrForOldDecl =
2108         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2109       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2110     }
2111 
2112     // Ok, delete the old function now, which is dead.
2113     OldFn->eraseFromParent();
2114 
2115     Entry = NewFn;
2116   }
2117 
2118   // We need to set linkage and visibility on the function before
2119   // generating code for it because various parts of IR generation
2120   // want to propagate this information down (e.g. to local static
2121   // declarations).
2122   llvm::Function *Fn = cast<llvm::Function>(Entry);
2123   setFunctionLinkage(D, Fn);
2124 
2125   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
2126   setGlobalVisibility(Fn, D);
2127 
2128   MaybeHandleStaticInExternC(D, Fn);
2129 
2130   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2131 
2132   SetFunctionDefinitionAttributes(D, Fn);
2133   SetLLVMFunctionAttributesForDefinition(D, Fn);
2134 
2135   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2136     AddGlobalCtor(Fn, CA->getPriority());
2137   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2138     AddGlobalDtor(Fn, DA->getPriority());
2139   if (D->hasAttr<AnnotateAttr>())
2140     AddGlobalAnnotations(D, Fn);
2141 }
2142 
2143 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2144   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
2145   const AliasAttr *AA = D->getAttr<AliasAttr>();
2146   assert(AA && "Not an alias?");
2147 
2148   StringRef MangledName = getMangledName(GD);
2149 
2150   // If there is a definition in the module, then it wins over the alias.
2151   // This is dubious, but allow it to be safe.  Just ignore the alias.
2152   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2153   if (Entry && !Entry->isDeclaration())
2154     return;
2155 
2156   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2157 
2158   // Create a reference to the named value.  This ensures that it is emitted
2159   // if a deferred decl.
2160   llvm::Constant *Aliasee;
2161   if (isa<llvm::FunctionType>(DeclTy))
2162     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2163                                       /*ForVTable=*/false);
2164   else
2165     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2166                                     llvm::PointerType::getUnqual(DeclTy), 0);
2167 
2168   // Create the new alias itself, but don't set a name yet.
2169   llvm::GlobalValue *GA =
2170     new llvm::GlobalAlias(Aliasee->getType(),
2171                           llvm::Function::ExternalLinkage,
2172                           "", Aliasee, &getModule());
2173 
2174   if (Entry) {
2175     assert(Entry->isDeclaration());
2176 
2177     // If there is a declaration in the module, then we had an extern followed
2178     // by the alias, as in:
2179     //   extern int test6();
2180     //   ...
2181     //   int test6() __attribute__((alias("test7")));
2182     //
2183     // Remove it and replace uses of it with the alias.
2184     GA->takeName(Entry);
2185 
2186     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2187                                                           Entry->getType()));
2188     Entry->eraseFromParent();
2189   } else {
2190     GA->setName(MangledName);
2191   }
2192 
2193   // Set attributes which are particular to an alias; this is a
2194   // specialization of the attributes which may be set on a global
2195   // variable/function.
2196   if (D->hasAttr<DLLExportAttr>()) {
2197     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2198       // The dllexport attribute is ignored for undefined symbols.
2199       if (FD->hasBody())
2200         GA->setLinkage(llvm::Function::DLLExportLinkage);
2201     } else {
2202       GA->setLinkage(llvm::Function::DLLExportLinkage);
2203     }
2204   } else if (D->hasAttr<WeakAttr>() ||
2205              D->hasAttr<WeakRefAttr>() ||
2206              D->isWeakImported()) {
2207     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2208   }
2209 
2210   SetCommonAttributes(D, GA);
2211 }
2212 
2213 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2214                                             ArrayRef<llvm::Type*> Tys) {
2215   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2216                                          Tys);
2217 }
2218 
2219 static llvm::StringMapEntry<llvm::Constant*> &
2220 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2221                          const StringLiteral *Literal,
2222                          bool TargetIsLSB,
2223                          bool &IsUTF16,
2224                          unsigned &StringLength) {
2225   StringRef String = Literal->getString();
2226   unsigned NumBytes = String.size();
2227 
2228   // Check for simple case.
2229   if (!Literal->containsNonAsciiOrNull()) {
2230     StringLength = NumBytes;
2231     return Map.GetOrCreateValue(String);
2232   }
2233 
2234   // Otherwise, convert the UTF8 literals into a string of shorts.
2235   IsUTF16 = true;
2236 
2237   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2238   const UTF8 *FromPtr = (const UTF8 *)String.data();
2239   UTF16 *ToPtr = &ToBuf[0];
2240 
2241   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2242                            &ToPtr, ToPtr + NumBytes,
2243                            strictConversion);
2244 
2245   // ConvertUTF8toUTF16 returns the length in ToPtr.
2246   StringLength = ToPtr - &ToBuf[0];
2247 
2248   // Add an explicit null.
2249   *ToPtr = 0;
2250   return Map.
2251     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2252                                (StringLength + 1) * 2));
2253 }
2254 
2255 static llvm::StringMapEntry<llvm::Constant*> &
2256 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2257                        const StringLiteral *Literal,
2258                        unsigned &StringLength) {
2259   StringRef String = Literal->getString();
2260   StringLength = String.size();
2261   return Map.GetOrCreateValue(String);
2262 }
2263 
2264 llvm::Constant *
2265 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2266   unsigned StringLength = 0;
2267   bool isUTF16 = false;
2268   llvm::StringMapEntry<llvm::Constant*> &Entry =
2269     GetConstantCFStringEntry(CFConstantStringMap, Literal,
2270                              getDataLayout().isLittleEndian(),
2271                              isUTF16, StringLength);
2272 
2273   if (llvm::Constant *C = Entry.getValue())
2274     return C;
2275 
2276   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2277   llvm::Constant *Zeros[] = { Zero, Zero };
2278   llvm::Value *V;
2279 
2280   // If we don't already have it, get __CFConstantStringClassReference.
2281   if (!CFConstantStringClassRef) {
2282     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2283     Ty = llvm::ArrayType::get(Ty, 0);
2284     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2285                                            "__CFConstantStringClassReference");
2286     // Decay array -> ptr
2287     V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2288     CFConstantStringClassRef = V;
2289   }
2290   else
2291     V = CFConstantStringClassRef;
2292 
2293   QualType CFTy = getContext().getCFConstantStringType();
2294 
2295   llvm::StructType *STy =
2296     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2297 
2298   llvm::Constant *Fields[4];
2299 
2300   // Class pointer.
2301   Fields[0] = cast<llvm::ConstantExpr>(V);
2302 
2303   // Flags.
2304   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2305   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2306     llvm::ConstantInt::get(Ty, 0x07C8);
2307 
2308   // String pointer.
2309   llvm::Constant *C = 0;
2310   if (isUTF16) {
2311     ArrayRef<uint16_t> Arr =
2312       llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2313                                      const_cast<char *>(Entry.getKey().data())),
2314                                    Entry.getKey().size() / 2);
2315     C = llvm::ConstantDataArray::get(VMContext, Arr);
2316   } else {
2317     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2318   }
2319 
2320   llvm::GlobalValue::LinkageTypes Linkage;
2321   if (isUTF16)
2322     // FIXME: why do utf strings get "_" labels instead of "L" labels?
2323     Linkage = llvm::GlobalValue::InternalLinkage;
2324   else
2325     // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2326     // when using private linkage. It is not clear if this is a bug in ld
2327     // or a reasonable new restriction.
2328     Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2329 
2330   // Note: -fwritable-strings doesn't make the backing store strings of
2331   // CFStrings writable. (See <rdar://problem/10657500>)
2332   llvm::GlobalVariable *GV =
2333     new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2334                              Linkage, C, ".str");
2335   GV->setUnnamedAddr(true);
2336   if (isUTF16) {
2337     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2338     GV->setAlignment(Align.getQuantity());
2339   } else {
2340     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2341     GV->setAlignment(Align.getQuantity());
2342   }
2343 
2344   // String.
2345   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2346 
2347   if (isUTF16)
2348     // Cast the UTF16 string to the correct type.
2349     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2350 
2351   // String length.
2352   Ty = getTypes().ConvertType(getContext().LongTy);
2353   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2354 
2355   // The struct.
2356   C = llvm::ConstantStruct::get(STy, Fields);
2357   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2358                                 llvm::GlobalVariable::PrivateLinkage, C,
2359                                 "_unnamed_cfstring_");
2360   if (const char *Sect = getTarget().getCFStringSection())
2361     GV->setSection(Sect);
2362   Entry.setValue(GV);
2363 
2364   return GV;
2365 }
2366 
2367 static RecordDecl *
2368 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2369                  DeclContext *DC, IdentifierInfo *Id) {
2370   SourceLocation Loc;
2371   if (Ctx.getLangOpts().CPlusPlus)
2372     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2373   else
2374     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2375 }
2376 
2377 llvm::Constant *
2378 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2379   unsigned StringLength = 0;
2380   llvm::StringMapEntry<llvm::Constant*> &Entry =
2381     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2382 
2383   if (llvm::Constant *C = Entry.getValue())
2384     return C;
2385 
2386   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2387   llvm::Constant *Zeros[] = { Zero, Zero };
2388   llvm::Value *V;
2389   // If we don't already have it, get _NSConstantStringClassReference.
2390   if (!ConstantStringClassRef) {
2391     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2392     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2393     llvm::Constant *GV;
2394     if (LangOpts.ObjCRuntime.isNonFragile()) {
2395       std::string str =
2396         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2397                             : "OBJC_CLASS_$_" + StringClass;
2398       GV = getObjCRuntime().GetClassGlobal(str);
2399       // Make sure the result is of the correct type.
2400       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2401       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2402       ConstantStringClassRef = V;
2403     } else {
2404       std::string str =
2405         StringClass.empty() ? "_NSConstantStringClassReference"
2406                             : "_" + StringClass + "ClassReference";
2407       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2408       GV = CreateRuntimeVariable(PTy, str);
2409       // Decay array -> ptr
2410       V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2411       ConstantStringClassRef = V;
2412     }
2413   }
2414   else
2415     V = ConstantStringClassRef;
2416 
2417   if (!NSConstantStringType) {
2418     // Construct the type for a constant NSString.
2419     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2420                                      Context.getTranslationUnitDecl(),
2421                                    &Context.Idents.get("__builtin_NSString"));
2422     D->startDefinition();
2423 
2424     QualType FieldTypes[3];
2425 
2426     // const int *isa;
2427     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2428     // const char *str;
2429     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2430     // unsigned int length;
2431     FieldTypes[2] = Context.UnsignedIntTy;
2432 
2433     // Create fields
2434     for (unsigned i = 0; i < 3; ++i) {
2435       FieldDecl *Field = FieldDecl::Create(Context, D,
2436                                            SourceLocation(),
2437                                            SourceLocation(), 0,
2438                                            FieldTypes[i], /*TInfo=*/0,
2439                                            /*BitWidth=*/0,
2440                                            /*Mutable=*/false,
2441                                            ICIS_NoInit);
2442       Field->setAccess(AS_public);
2443       D->addDecl(Field);
2444     }
2445 
2446     D->completeDefinition();
2447     QualType NSTy = Context.getTagDeclType(D);
2448     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2449   }
2450 
2451   llvm::Constant *Fields[3];
2452 
2453   // Class pointer.
2454   Fields[0] = cast<llvm::ConstantExpr>(V);
2455 
2456   // String pointer.
2457   llvm::Constant *C =
2458     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2459 
2460   llvm::GlobalValue::LinkageTypes Linkage;
2461   bool isConstant;
2462   Linkage = llvm::GlobalValue::PrivateLinkage;
2463   isConstant = !LangOpts.WritableStrings;
2464 
2465   llvm::GlobalVariable *GV =
2466   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2467                            ".str");
2468   GV->setUnnamedAddr(true);
2469   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2470   GV->setAlignment(Align.getQuantity());
2471   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2472 
2473   // String length.
2474   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2475   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2476 
2477   // The struct.
2478   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2479   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2480                                 llvm::GlobalVariable::PrivateLinkage, C,
2481                                 "_unnamed_nsstring_");
2482   // FIXME. Fix section.
2483   if (const char *Sect =
2484         LangOpts.ObjCRuntime.isNonFragile()
2485           ? getTarget().getNSStringNonFragileABISection()
2486           : getTarget().getNSStringSection())
2487     GV->setSection(Sect);
2488   Entry.setValue(GV);
2489 
2490   return GV;
2491 }
2492 
2493 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2494   if (ObjCFastEnumerationStateType.isNull()) {
2495     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2496                                      Context.getTranslationUnitDecl(),
2497                       &Context.Idents.get("__objcFastEnumerationState"));
2498     D->startDefinition();
2499 
2500     QualType FieldTypes[] = {
2501       Context.UnsignedLongTy,
2502       Context.getPointerType(Context.getObjCIdType()),
2503       Context.getPointerType(Context.UnsignedLongTy),
2504       Context.getConstantArrayType(Context.UnsignedLongTy,
2505                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2506     };
2507 
2508     for (size_t i = 0; i < 4; ++i) {
2509       FieldDecl *Field = FieldDecl::Create(Context,
2510                                            D,
2511                                            SourceLocation(),
2512                                            SourceLocation(), 0,
2513                                            FieldTypes[i], /*TInfo=*/0,
2514                                            /*BitWidth=*/0,
2515                                            /*Mutable=*/false,
2516                                            ICIS_NoInit);
2517       Field->setAccess(AS_public);
2518       D->addDecl(Field);
2519     }
2520 
2521     D->completeDefinition();
2522     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2523   }
2524 
2525   return ObjCFastEnumerationStateType;
2526 }
2527 
2528 llvm::Constant *
2529 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2530   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2531 
2532   // Don't emit it as the address of the string, emit the string data itself
2533   // as an inline array.
2534   if (E->getCharByteWidth() == 1) {
2535     SmallString<64> Str(E->getString());
2536 
2537     // Resize the string to the right size, which is indicated by its type.
2538     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2539     Str.resize(CAT->getSize().getZExtValue());
2540     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2541   }
2542 
2543   llvm::ArrayType *AType =
2544     cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2545   llvm::Type *ElemTy = AType->getElementType();
2546   unsigned NumElements = AType->getNumElements();
2547 
2548   // Wide strings have either 2-byte or 4-byte elements.
2549   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2550     SmallVector<uint16_t, 32> Elements;
2551     Elements.reserve(NumElements);
2552 
2553     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2554       Elements.push_back(E->getCodeUnit(i));
2555     Elements.resize(NumElements);
2556     return llvm::ConstantDataArray::get(VMContext, Elements);
2557   }
2558 
2559   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2560   SmallVector<uint32_t, 32> Elements;
2561   Elements.reserve(NumElements);
2562 
2563   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2564     Elements.push_back(E->getCodeUnit(i));
2565   Elements.resize(NumElements);
2566   return llvm::ConstantDataArray::get(VMContext, Elements);
2567 }
2568 
2569 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2570 /// constant array for the given string literal.
2571 llvm::Constant *
2572 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2573   CharUnits Align = getContext().getTypeAlignInChars(S->getType());
2574   if (S->isAscii() || S->isUTF8()) {
2575     SmallString<64> Str(S->getString());
2576 
2577     // Resize the string to the right size, which is indicated by its type.
2578     const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2579     Str.resize(CAT->getSize().getZExtValue());
2580     return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2581   }
2582 
2583   // FIXME: the following does not memoize wide strings.
2584   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2585   llvm::GlobalVariable *GV =
2586     new llvm::GlobalVariable(getModule(),C->getType(),
2587                              !LangOpts.WritableStrings,
2588                              llvm::GlobalValue::PrivateLinkage,
2589                              C,".str");
2590 
2591   GV->setAlignment(Align.getQuantity());
2592   GV->setUnnamedAddr(true);
2593   return GV;
2594 }
2595 
2596 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2597 /// array for the given ObjCEncodeExpr node.
2598 llvm::Constant *
2599 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2600   std::string Str;
2601   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2602 
2603   return GetAddrOfConstantCString(Str);
2604 }
2605 
2606 
2607 /// GenerateWritableString -- Creates storage for a string literal.
2608 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2609                                              bool constant,
2610                                              CodeGenModule &CGM,
2611                                              const char *GlobalName,
2612                                              unsigned Alignment) {
2613   // Create Constant for this string literal. Don't add a '\0'.
2614   llvm::Constant *C =
2615       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2616 
2617   // Create a global variable for this string
2618   llvm::GlobalVariable *GV =
2619     new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2620                              llvm::GlobalValue::PrivateLinkage,
2621                              C, GlobalName);
2622   GV->setAlignment(Alignment);
2623   GV->setUnnamedAddr(true);
2624   return GV;
2625 }
2626 
2627 /// GetAddrOfConstantString - Returns a pointer to a character array
2628 /// containing the literal. This contents are exactly that of the
2629 /// given string, i.e. it will not be null terminated automatically;
2630 /// see GetAddrOfConstantCString. Note that whether the result is
2631 /// actually a pointer to an LLVM constant depends on
2632 /// Feature.WriteableStrings.
2633 ///
2634 /// The result has pointer to array type.
2635 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2636                                                        const char *GlobalName,
2637                                                        unsigned Alignment) {
2638   // Get the default prefix if a name wasn't specified.
2639   if (!GlobalName)
2640     GlobalName = ".str";
2641 
2642   // Don't share any string literals if strings aren't constant.
2643   if (LangOpts.WritableStrings)
2644     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2645 
2646   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2647     ConstantStringMap.GetOrCreateValue(Str);
2648 
2649   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2650     if (Alignment > GV->getAlignment()) {
2651       GV->setAlignment(Alignment);
2652     }
2653     return GV;
2654   }
2655 
2656   // Create a global variable for this.
2657   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2658                                                    Alignment);
2659   Entry.setValue(GV);
2660   return GV;
2661 }
2662 
2663 /// GetAddrOfConstantCString - Returns a pointer to a character
2664 /// array containing the literal and a terminating '\0'
2665 /// character. The result has pointer to array type.
2666 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2667                                                         const char *GlobalName,
2668                                                         unsigned Alignment) {
2669   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2670   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2671 }
2672 
2673 /// EmitObjCPropertyImplementations - Emit information for synthesized
2674 /// properties for an implementation.
2675 void CodeGenModule::EmitObjCPropertyImplementations(const
2676                                                     ObjCImplementationDecl *D) {
2677   for (ObjCImplementationDecl::propimpl_iterator
2678          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2679     ObjCPropertyImplDecl *PID = *i;
2680 
2681     // Dynamic is just for type-checking.
2682     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2683       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2684 
2685       // Determine which methods need to be implemented, some may have
2686       // been overridden. Note that ::isPropertyAccessor is not the method
2687       // we want, that just indicates if the decl came from a
2688       // property. What we want to know is if the method is defined in
2689       // this implementation.
2690       if (!D->getInstanceMethod(PD->getGetterName()))
2691         CodeGenFunction(*this).GenerateObjCGetter(
2692                                  const_cast<ObjCImplementationDecl *>(D), PID);
2693       if (!PD->isReadOnly() &&
2694           !D->getInstanceMethod(PD->getSetterName()))
2695         CodeGenFunction(*this).GenerateObjCSetter(
2696                                  const_cast<ObjCImplementationDecl *>(D), PID);
2697     }
2698   }
2699 }
2700 
2701 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2702   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2703   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2704        ivar; ivar = ivar->getNextIvar())
2705     if (ivar->getType().isDestructedType())
2706       return true;
2707 
2708   return false;
2709 }
2710 
2711 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2712 /// for an implementation.
2713 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2714   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2715   if (needsDestructMethod(D)) {
2716     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2717     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2718     ObjCMethodDecl *DTORMethod =
2719       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2720                              cxxSelector, getContext().VoidTy, 0, D,
2721                              /*isInstance=*/true, /*isVariadic=*/false,
2722                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2723                              /*isDefined=*/false, ObjCMethodDecl::Required);
2724     D->addInstanceMethod(DTORMethod);
2725     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2726     D->setHasDestructors(true);
2727   }
2728 
2729   // If the implementation doesn't have any ivar initializers, we don't need
2730   // a .cxx_construct.
2731   if (D->getNumIvarInitializers() == 0)
2732     return;
2733 
2734   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2735   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2736   // The constructor returns 'self'.
2737   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2738                                                 D->getLocation(),
2739                                                 D->getLocation(),
2740                                                 cxxSelector,
2741                                                 getContext().getObjCIdType(), 0,
2742                                                 D, /*isInstance=*/true,
2743                                                 /*isVariadic=*/false,
2744                                                 /*isPropertyAccessor=*/true,
2745                                                 /*isImplicitlyDeclared=*/true,
2746                                                 /*isDefined=*/false,
2747                                                 ObjCMethodDecl::Required);
2748   D->addInstanceMethod(CTORMethod);
2749   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2750   D->setHasNonZeroConstructors(true);
2751 }
2752 
2753 /// EmitNamespace - Emit all declarations in a namespace.
2754 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2755   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2756        I != E; ++I)
2757     EmitTopLevelDecl(*I);
2758 }
2759 
2760 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2761 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2762   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2763       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2764     ErrorUnsupported(LSD, "linkage spec");
2765     return;
2766   }
2767 
2768   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2769        I != E; ++I) {
2770     // Meta-data for ObjC class includes references to implemented methods.
2771     // Generate class's method definitions first.
2772     if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2773       for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2774            MEnd = OID->meth_end();
2775            M != MEnd; ++M)
2776         EmitTopLevelDecl(*M);
2777     }
2778     EmitTopLevelDecl(*I);
2779   }
2780 }
2781 
2782 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2783 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2784   // If an error has occurred, stop code generation, but continue
2785   // parsing and semantic analysis (to ensure all warnings and errors
2786   // are emitted).
2787   if (Diags.hasErrorOccurred())
2788     return;
2789 
2790   // Ignore dependent declarations.
2791   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2792     return;
2793 
2794   switch (D->getKind()) {
2795   case Decl::CXXConversion:
2796   case Decl::CXXMethod:
2797   case Decl::Function:
2798     // Skip function templates
2799     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2800         cast<FunctionDecl>(D)->isLateTemplateParsed())
2801       return;
2802 
2803     EmitGlobal(cast<FunctionDecl>(D));
2804     break;
2805 
2806   case Decl::Var:
2807     EmitGlobal(cast<VarDecl>(D));
2808     break;
2809 
2810   // Indirect fields from global anonymous structs and unions can be
2811   // ignored; only the actual variable requires IR gen support.
2812   case Decl::IndirectField:
2813     break;
2814 
2815   // C++ Decls
2816   case Decl::Namespace:
2817     EmitNamespace(cast<NamespaceDecl>(D));
2818     break;
2819     // No code generation needed.
2820   case Decl::UsingShadow:
2821   case Decl::Using:
2822   case Decl::ClassTemplate:
2823   case Decl::FunctionTemplate:
2824   case Decl::TypeAliasTemplate:
2825   case Decl::NamespaceAlias:
2826   case Decl::Block:
2827   case Decl::Empty:
2828     break;
2829   case Decl::UsingDirective: // using namespace X; [C++]
2830     if (CGDebugInfo *DI = getModuleDebugInfo())
2831       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2832     return;
2833   case Decl::CXXConstructor:
2834     // Skip function templates
2835     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2836         cast<FunctionDecl>(D)->isLateTemplateParsed())
2837       return;
2838 
2839     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2840     break;
2841   case Decl::CXXDestructor:
2842     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2843       return;
2844     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2845     break;
2846 
2847   case Decl::StaticAssert:
2848     // Nothing to do.
2849     break;
2850 
2851   // Objective-C Decls
2852 
2853   // Forward declarations, no (immediate) code generation.
2854   case Decl::ObjCInterface:
2855   case Decl::ObjCCategory:
2856     break;
2857 
2858   case Decl::ObjCProtocol: {
2859     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2860     if (Proto->isThisDeclarationADefinition())
2861       ObjCRuntime->GenerateProtocol(Proto);
2862     break;
2863   }
2864 
2865   case Decl::ObjCCategoryImpl:
2866     // Categories have properties but don't support synthesize so we
2867     // can ignore them here.
2868     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2869     break;
2870 
2871   case Decl::ObjCImplementation: {
2872     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2873     EmitObjCPropertyImplementations(OMD);
2874     EmitObjCIvarInitializations(OMD);
2875     ObjCRuntime->GenerateClass(OMD);
2876     // Emit global variable debug information.
2877     if (CGDebugInfo *DI = getModuleDebugInfo())
2878       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2879         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2880             OMD->getClassInterface()), OMD->getLocation());
2881     break;
2882   }
2883   case Decl::ObjCMethod: {
2884     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2885     // If this is not a prototype, emit the body.
2886     if (OMD->getBody())
2887       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2888     break;
2889   }
2890   case Decl::ObjCCompatibleAlias:
2891     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2892     break;
2893 
2894   case Decl::LinkageSpec:
2895     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2896     break;
2897 
2898   case Decl::FileScopeAsm: {
2899     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2900     StringRef AsmString = AD->getAsmString()->getString();
2901 
2902     const std::string &S = getModule().getModuleInlineAsm();
2903     if (S.empty())
2904       getModule().setModuleInlineAsm(AsmString);
2905     else if (S.end()[-1] == '\n')
2906       getModule().setModuleInlineAsm(S + AsmString.str());
2907     else
2908       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2909     break;
2910   }
2911 
2912   case Decl::Import: {
2913     ImportDecl *Import = cast<ImportDecl>(D);
2914 
2915     // Ignore import declarations that come from imported modules.
2916     if (clang::Module *Owner = Import->getOwningModule()) {
2917       if (getLangOpts().CurrentModule.empty() ||
2918           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
2919         break;
2920     }
2921 
2922     ImportedModules.insert(Import->getImportedModule());
2923     break;
2924  }
2925 
2926   default:
2927     // Make sure we handled everything we should, every other kind is a
2928     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2929     // function. Need to recode Decl::Kind to do that easily.
2930     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2931   }
2932 }
2933 
2934 /// Turns the given pointer into a constant.
2935 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2936                                           const void *Ptr) {
2937   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2938   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2939   return llvm::ConstantInt::get(i64, PtrInt);
2940 }
2941 
2942 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2943                                    llvm::NamedMDNode *&GlobalMetadata,
2944                                    GlobalDecl D,
2945                                    llvm::GlobalValue *Addr) {
2946   if (!GlobalMetadata)
2947     GlobalMetadata =
2948       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2949 
2950   // TODO: should we report variant information for ctors/dtors?
2951   llvm::Value *Ops[] = {
2952     Addr,
2953     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2954   };
2955   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2956 }
2957 
2958 /// For each function which is declared within an extern "C" region and marked
2959 /// as 'used', but has internal linkage, create an alias from the unmangled
2960 /// name to the mangled name if possible. People expect to be able to refer
2961 /// to such functions with an unmangled name from inline assembly within the
2962 /// same translation unit.
2963 void CodeGenModule::EmitStaticExternCAliases() {
2964   for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
2965                                   E = StaticExternCValues.end();
2966        I != E; ++I) {
2967     IdentifierInfo *Name = I->first;
2968     llvm::GlobalValue *Val = I->second;
2969     if (Val && !getModule().getNamedValue(Name->getName()))
2970       AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
2971                                           Name->getName(), Val, &getModule()));
2972   }
2973 }
2974 
2975 /// Emits metadata nodes associating all the global values in the
2976 /// current module with the Decls they came from.  This is useful for
2977 /// projects using IR gen as a subroutine.
2978 ///
2979 /// Since there's currently no way to associate an MDNode directly
2980 /// with an llvm::GlobalValue, we create a global named metadata
2981 /// with the name 'clang.global.decl.ptrs'.
2982 void CodeGenModule::EmitDeclMetadata() {
2983   llvm::NamedMDNode *GlobalMetadata = 0;
2984 
2985   // StaticLocalDeclMap
2986   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2987          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2988        I != E; ++I) {
2989     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2990     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2991   }
2992 }
2993 
2994 /// Emits metadata nodes for all the local variables in the current
2995 /// function.
2996 void CodeGenFunction::EmitDeclMetadata() {
2997   if (LocalDeclMap.empty()) return;
2998 
2999   llvm::LLVMContext &Context = getLLVMContext();
3000 
3001   // Find the unique metadata ID for this name.
3002   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3003 
3004   llvm::NamedMDNode *GlobalMetadata = 0;
3005 
3006   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3007          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3008     const Decl *D = I->first;
3009     llvm::Value *Addr = I->second;
3010 
3011     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3012       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3013       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3014     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3015       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3016       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3017     }
3018   }
3019 }
3020 
3021 void CodeGenModule::EmitCoverageFile() {
3022   if (!getCodeGenOpts().CoverageFile.empty()) {
3023     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3024       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3025       llvm::LLVMContext &Ctx = TheModule.getContext();
3026       llvm::MDString *CoverageFile =
3027           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3028       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3029         llvm::MDNode *CU = CUNode->getOperand(i);
3030         llvm::Value *node[] = { CoverageFile, CU };
3031         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3032         GCov->addOperand(N);
3033       }
3034     }
3035   }
3036 }
3037 
3038 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3039                                                      QualType GuidType) {
3040   // Sema has checked that all uuid strings are of the form
3041   // "12345678-1234-1234-1234-1234567890ab".
3042   assert(Uuid.size() == 36);
3043   const char *Uuidstr = Uuid.data();
3044   for (int i = 0; i < 36; ++i) {
3045     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
3046     else                                         assert(isHexDigit(Uuidstr[i]));
3047   }
3048 
3049   llvm::APInt Field0(32, StringRef(Uuidstr     , 8), 16);
3050   llvm::APInt Field1(16, StringRef(Uuidstr +  9, 4), 16);
3051   llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
3052   static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3053 
3054   APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
3055   InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
3056   InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
3057   InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
3058   APValue& Arr = InitStruct.getStructField(3);
3059   Arr = APValue(APValue::UninitArray(), 8, 8);
3060   for (int t = 0; t < 8; ++t)
3061     Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
3062           llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
3063 
3064   return EmitConstantValue(InitStruct, GuidType);
3065 }
3066