xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 2fd1d7aee3cc168e0d9b78ca53fb2c1fc6684705)
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       CXXThreadLocals.push_back(std::make_pair(D, GV));
1483       setTLSMode(GV, *D);
1484     }
1485   }
1486 
1487   if (AddrSpace != Ty->getAddressSpace())
1488     return llvm::ConstantExpr::getBitCast(GV, Ty);
1489   else
1490     return GV;
1491 }
1492 
1493 
1494 llvm::GlobalVariable *
1495 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1496                                       llvm::Type *Ty,
1497                                       llvm::GlobalValue::LinkageTypes Linkage) {
1498   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1499   llvm::GlobalVariable *OldGV = 0;
1500 
1501 
1502   if (GV) {
1503     // Check if the variable has the right type.
1504     if (GV->getType()->getElementType() == Ty)
1505       return GV;
1506 
1507     // Because C++ name mangling, the only way we can end up with an already
1508     // existing global with the same name is if it has been declared extern "C".
1509     assert(GV->isDeclaration() && "Declaration has wrong type!");
1510     OldGV = GV;
1511   }
1512 
1513   // Create a new variable.
1514   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1515                                 Linkage, 0, Name);
1516 
1517   if (OldGV) {
1518     // Replace occurrences of the old variable if needed.
1519     GV->takeName(OldGV);
1520 
1521     if (!OldGV->use_empty()) {
1522       llvm::Constant *NewPtrForOldDecl =
1523       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1524       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1525     }
1526 
1527     OldGV->eraseFromParent();
1528   }
1529 
1530   return GV;
1531 }
1532 
1533 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1534 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1535 /// then it will be created with the specified type instead of whatever the
1536 /// normal requested type would be.
1537 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1538                                                   llvm::Type *Ty) {
1539   assert(D->hasGlobalStorage() && "Not a global variable");
1540   QualType ASTTy = D->getType();
1541   if (Ty == 0)
1542     Ty = getTypes().ConvertTypeForMem(ASTTy);
1543 
1544   llvm::PointerType *PTy =
1545     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1546 
1547   StringRef MangledName = getMangledName(D);
1548   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1549 }
1550 
1551 /// CreateRuntimeVariable - Create a new runtime global variable with the
1552 /// specified type and name.
1553 llvm::Constant *
1554 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1555                                      StringRef Name) {
1556   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1557                                true);
1558 }
1559 
1560 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1561   assert(!D->getInit() && "Cannot emit definite definitions here!");
1562 
1563   if (MayDeferGeneration(D)) {
1564     // If we have not seen a reference to this variable yet, place it
1565     // into the deferred declarations table to be emitted if needed
1566     // later.
1567     StringRef MangledName = getMangledName(D);
1568     if (!GetGlobalValue(MangledName)) {
1569       DeferredDecls[MangledName] = D;
1570       return;
1571     }
1572   }
1573 
1574   // The tentative definition is the only definition.
1575   EmitGlobalVarDefinition(D);
1576 }
1577 
1578 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1579     return Context.toCharUnitsFromBits(
1580       TheDataLayout.getTypeStoreSizeInBits(Ty));
1581 }
1582 
1583 llvm::Constant *
1584 CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1585                                                        const Expr *rawInit) {
1586   ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1587   if (const ExprWithCleanups *withCleanups =
1588           dyn_cast<ExprWithCleanups>(rawInit)) {
1589     cleanups = withCleanups->getObjects();
1590     rawInit = withCleanups->getSubExpr();
1591   }
1592 
1593   const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1594   if (!init || !init->initializesStdInitializerList() ||
1595       init->getNumInits() == 0)
1596     return 0;
1597 
1598   ASTContext &ctx = getContext();
1599   unsigned numInits = init->getNumInits();
1600   // FIXME: This check is here because we would otherwise silently miscompile
1601   // nested global std::initializer_lists. Better would be to have a real
1602   // implementation.
1603   for (unsigned i = 0; i < numInits; ++i) {
1604     const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1605     if (inner && inner->initializesStdInitializerList()) {
1606       ErrorUnsupported(inner, "nested global std::initializer_list");
1607       return 0;
1608     }
1609   }
1610 
1611   // Synthesize a fake VarDecl for the array and initialize that.
1612   QualType elementType = init->getInit(0)->getType();
1613   llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1614   QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1615                                                 ArrayType::Normal, 0);
1616 
1617   IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1618   TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1619                                               arrayType, D->getLocation());
1620   VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1621                                                           D->getDeclContext()),
1622                                           D->getLocStart(), D->getLocation(),
1623                                           name, arrayType, sourceInfo,
1624                                           SC_Static);
1625   backingArray->setTLSKind(D->getTLSKind());
1626 
1627   // Now clone the InitListExpr to initialize the array instead.
1628   // Incredible hack: we want to use the existing InitListExpr here, so we need
1629   // to tell it that it no longer initializes a std::initializer_list.
1630   ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
1631                         init->getNumInits());
1632   Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
1633                                            init->getRBraceLoc());
1634   arrayInit->setType(arrayType);
1635 
1636   if (!cleanups.empty())
1637     arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1638 
1639   backingArray->setInit(arrayInit);
1640 
1641   // Emit the definition of the array.
1642   EmitGlobalVarDefinition(backingArray);
1643 
1644   // Inspect the initializer list to validate it and determine its type.
1645   // FIXME: doing this every time is probably inefficient; caching would be nice
1646   RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1647   RecordDecl::field_iterator field = record->field_begin();
1648   if (field == record->field_end()) {
1649     ErrorUnsupported(D, "weird std::initializer_list");
1650     return 0;
1651   }
1652   QualType elementPtr = ctx.getPointerType(elementType.withConst());
1653   // Start pointer.
1654   if (!ctx.hasSameType(field->getType(), elementPtr)) {
1655     ErrorUnsupported(D, "weird std::initializer_list");
1656     return 0;
1657   }
1658   ++field;
1659   if (field == record->field_end()) {
1660     ErrorUnsupported(D, "weird std::initializer_list");
1661     return 0;
1662   }
1663   bool isStartEnd = false;
1664   if (ctx.hasSameType(field->getType(), elementPtr)) {
1665     // End pointer.
1666     isStartEnd = true;
1667   } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1668     ErrorUnsupported(D, "weird std::initializer_list");
1669     return 0;
1670   }
1671 
1672   // Now build an APValue representing the std::initializer_list.
1673   APValue initListValue(APValue::UninitStruct(), 0, 2);
1674   APValue &startField = initListValue.getStructField(0);
1675   APValue::LValuePathEntry startOffsetPathEntry;
1676   startOffsetPathEntry.ArrayIndex = 0;
1677   startField = APValue(APValue::LValueBase(backingArray),
1678                        CharUnits::fromQuantity(0),
1679                        llvm::makeArrayRef(startOffsetPathEntry),
1680                        /*IsOnePastTheEnd=*/false, 0);
1681 
1682   if (isStartEnd) {
1683     APValue &endField = initListValue.getStructField(1);
1684     APValue::LValuePathEntry endOffsetPathEntry;
1685     endOffsetPathEntry.ArrayIndex = numInits;
1686     endField = APValue(APValue::LValueBase(backingArray),
1687                        ctx.getTypeSizeInChars(elementType) * numInits,
1688                        llvm::makeArrayRef(endOffsetPathEntry),
1689                        /*IsOnePastTheEnd=*/true, 0);
1690   } else {
1691     APValue &sizeField = initListValue.getStructField(1);
1692     sizeField = APValue(llvm::APSInt(numElements));
1693   }
1694 
1695   // Emit the constant for the initializer_list.
1696   llvm::Constant *llvmInit =
1697       EmitConstantValueForMemory(initListValue, D->getType());
1698   assert(llvmInit && "failed to initialize as constant");
1699   return llvmInit;
1700 }
1701 
1702 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1703                                                  unsigned AddrSpace) {
1704   if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1705     if (D->hasAttr<CUDAConstantAttr>())
1706       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1707     else if (D->hasAttr<CUDASharedAttr>())
1708       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1709     else
1710       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1711   }
1712 
1713   return AddrSpace;
1714 }
1715 
1716 template<typename SomeDecl>
1717 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1718                                                llvm::GlobalValue *GV) {
1719   if (!getLangOpts().CPlusPlus)
1720     return;
1721 
1722   // Must have 'used' attribute, or else inline assembly can't rely on
1723   // the name existing.
1724   if (!D->template hasAttr<UsedAttr>())
1725     return;
1726 
1727   // Must have internal linkage and an ordinary name.
1728   if (!D->getIdentifier() || D->getLinkage() != InternalLinkage)
1729     return;
1730 
1731   // Must be in an extern "C" context. Entities declared directly within
1732   // a record are not extern "C" even if the record is in such a context.
1733   const DeclContext *DC = D->getFirstDeclaration()->getDeclContext();
1734   if (DC->isRecord() || !DC->isExternCContext())
1735     return;
1736 
1737   // OK, this is an internal linkage entity inside an extern "C" linkage
1738   // specification. Make a note of that so we can give it the "expected"
1739   // mangled name if nothing else is using that name.
1740   std::pair<StaticExternCMap::iterator, bool> R =
1741       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1742 
1743   // If we have multiple internal linkage entities with the same name
1744   // in extern "C" regions, none of them gets that name.
1745   if (!R.second)
1746     R.first->second = 0;
1747 }
1748 
1749 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1750   llvm::Constant *Init = 0;
1751   QualType ASTTy = D->getType();
1752   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1753   bool NeedsGlobalCtor = false;
1754   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1755 
1756   const VarDecl *InitDecl;
1757   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1758 
1759   if (!InitExpr) {
1760     // This is a tentative definition; tentative definitions are
1761     // implicitly initialized with { 0 }.
1762     //
1763     // Note that tentative definitions are only emitted at the end of
1764     // a translation unit, so they should never have incomplete
1765     // type. In addition, EmitTentativeDefinition makes sure that we
1766     // never attempt to emit a tentative definition if a real one
1767     // exists. A use may still exists, however, so we still may need
1768     // to do a RAUW.
1769     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1770     Init = EmitNullConstant(D->getType());
1771   } else {
1772     // If this is a std::initializer_list, emit the special initializer.
1773     Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1774     // An empty init list will perform zero-initialization, which happens
1775     // to be exactly what we want.
1776     // FIXME: It does so in a global constructor, which is *not* what we
1777     // want.
1778 
1779     if (!Init) {
1780       initializedGlobalDecl = GlobalDecl(D);
1781       Init = EmitConstantInit(*InitDecl);
1782     }
1783     if (!Init) {
1784       QualType T = InitExpr->getType();
1785       if (D->getType()->isReferenceType())
1786         T = D->getType();
1787 
1788       if (getLangOpts().CPlusPlus) {
1789         Init = EmitNullConstant(T);
1790         NeedsGlobalCtor = true;
1791       } else {
1792         ErrorUnsupported(D, "static initializer");
1793         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1794       }
1795     } else {
1796       // We don't need an initializer, so remove the entry for the delayed
1797       // initializer position (just in case this entry was delayed) if we
1798       // also don't need to register a destructor.
1799       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1800         DelayedCXXInitPosition.erase(D);
1801     }
1802   }
1803 
1804   llvm::Type* InitType = Init->getType();
1805   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1806 
1807   // Strip off a bitcast if we got one back.
1808   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1809     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1810            // all zero index gep.
1811            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1812     Entry = CE->getOperand(0);
1813   }
1814 
1815   // Entry is now either a Function or GlobalVariable.
1816   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1817 
1818   // We have a definition after a declaration with the wrong type.
1819   // We must make a new GlobalVariable* and update everything that used OldGV
1820   // (a declaration or tentative definition) with the new GlobalVariable*
1821   // (which will be a definition).
1822   //
1823   // This happens if there is a prototype for a global (e.g.
1824   // "extern int x[];") and then a definition of a different type (e.g.
1825   // "int x[10];"). This also happens when an initializer has a different type
1826   // from the type of the global (this happens with unions).
1827   if (GV == 0 ||
1828       GV->getType()->getElementType() != InitType ||
1829       GV->getType()->getAddressSpace() !=
1830        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1831 
1832     // Move the old entry aside so that we'll create a new one.
1833     Entry->setName(StringRef());
1834 
1835     // Make a new global with the correct type, this is now guaranteed to work.
1836     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1837 
1838     // Replace all uses of the old global with the new global
1839     llvm::Constant *NewPtrForOldDecl =
1840         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1841     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1842 
1843     // Erase the old global, since it is no longer used.
1844     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1845   }
1846 
1847   MaybeHandleStaticInExternC(D, GV);
1848 
1849   if (D->hasAttr<AnnotateAttr>())
1850     AddGlobalAnnotations(D, GV);
1851 
1852   GV->setInitializer(Init);
1853 
1854   // If it is safe to mark the global 'constant', do so now.
1855   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1856                   isTypeConstant(D->getType(), true));
1857 
1858   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1859 
1860   // Set the llvm linkage type as appropriate.
1861   llvm::GlobalValue::LinkageTypes Linkage =
1862     GetLLVMLinkageVarDefinition(D, GV);
1863   GV->setLinkage(Linkage);
1864   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1865     // common vars aren't constant even if declared const.
1866     GV->setConstant(false);
1867 
1868   SetCommonAttributes(D, GV);
1869 
1870   // Emit the initializer function if necessary.
1871   if (NeedsGlobalCtor || NeedsGlobalDtor)
1872     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1873 
1874   // If we are compiling with ASan, add metadata indicating dynamically
1875   // initialized globals.
1876   if (SanOpts.Address && NeedsGlobalCtor) {
1877     llvm::Module &M = getModule();
1878 
1879     llvm::NamedMDNode *DynamicInitializers =
1880         M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1881     llvm::Value *GlobalToAdd[] = { GV };
1882     llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1883     DynamicInitializers->addOperand(ThisGlobal);
1884   }
1885 
1886   // Emit global variable debug information.
1887   if (CGDebugInfo *DI = getModuleDebugInfo())
1888     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1889       DI->EmitGlobalVariable(GV, D);
1890 }
1891 
1892 llvm::GlobalValue::LinkageTypes
1893 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1894                                            llvm::GlobalVariable *GV) {
1895   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1896   if (Linkage == GVA_Internal)
1897     return llvm::Function::InternalLinkage;
1898   else if (D->hasAttr<DLLImportAttr>())
1899     return llvm::Function::DLLImportLinkage;
1900   else if (D->hasAttr<DLLExportAttr>())
1901     return llvm::Function::DLLExportLinkage;
1902   else if (D->hasAttr<WeakAttr>()) {
1903     if (GV->isConstant())
1904       return llvm::GlobalVariable::WeakODRLinkage;
1905     else
1906       return llvm::GlobalVariable::WeakAnyLinkage;
1907   } else if (Linkage == GVA_TemplateInstantiation ||
1908              Linkage == GVA_ExplicitTemplateInstantiation)
1909     return llvm::GlobalVariable::WeakODRLinkage;
1910   else if (!getLangOpts().CPlusPlus &&
1911            ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1912              D->getAttr<CommonAttr>()) &&
1913            !D->hasExternalStorage() && !D->getInit() &&
1914            !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
1915            !D->getAttr<WeakImportAttr>()) {
1916     // Thread local vars aren't considered common linkage.
1917     return llvm::GlobalVariable::CommonLinkage;
1918   }
1919   return llvm::GlobalVariable::ExternalLinkage;
1920 }
1921 
1922 /// Replace the uses of a function that was declared with a non-proto type.
1923 /// We want to silently drop extra arguments from call sites
1924 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1925                                           llvm::Function *newFn) {
1926   // Fast path.
1927   if (old->use_empty()) return;
1928 
1929   llvm::Type *newRetTy = newFn->getReturnType();
1930   SmallVector<llvm::Value*, 4> newArgs;
1931 
1932   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1933          ui != ue; ) {
1934     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1935     llvm::User *user = *use;
1936 
1937     // Recognize and replace uses of bitcasts.  Most calls to
1938     // unprototyped functions will use bitcasts.
1939     if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1940       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1941         replaceUsesOfNonProtoConstant(bitcast, newFn);
1942       continue;
1943     }
1944 
1945     // Recognize calls to the function.
1946     llvm::CallSite callSite(user);
1947     if (!callSite) continue;
1948     if (!callSite.isCallee(use)) continue;
1949 
1950     // If the return types don't match exactly, then we can't
1951     // transform this call unless it's dead.
1952     if (callSite->getType() != newRetTy && !callSite->use_empty())
1953       continue;
1954 
1955     // Get the call site's attribute list.
1956     SmallVector<llvm::AttributeSet, 8> newAttrs;
1957     llvm::AttributeSet oldAttrs = callSite.getAttributes();
1958 
1959     // Collect any return attributes from the call.
1960     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
1961       newAttrs.push_back(
1962         llvm::AttributeSet::get(newFn->getContext(),
1963                                 oldAttrs.getRetAttributes()));
1964 
1965     // If the function was passed too few arguments, don't transform.
1966     unsigned newNumArgs = newFn->arg_size();
1967     if (callSite.arg_size() < newNumArgs) continue;
1968 
1969     // If extra arguments were passed, we silently drop them.
1970     // If any of the types mismatch, we don't transform.
1971     unsigned argNo = 0;
1972     bool dontTransform = false;
1973     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1974            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1975       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1976         dontTransform = true;
1977         break;
1978       }
1979 
1980       // Add any parameter attributes.
1981       if (oldAttrs.hasAttributes(argNo + 1))
1982         newAttrs.
1983           push_back(llvm::
1984                     AttributeSet::get(newFn->getContext(),
1985                                       oldAttrs.getParamAttributes(argNo + 1)));
1986     }
1987     if (dontTransform)
1988       continue;
1989 
1990     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
1991       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
1992                                                  oldAttrs.getFnAttributes()));
1993 
1994     // Okay, we can transform this.  Create the new call instruction and copy
1995     // over the required information.
1996     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
1997 
1998     llvm::CallSite newCall;
1999     if (callSite.isCall()) {
2000       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2001                                        callSite.getInstruction());
2002     } else {
2003       llvm::InvokeInst *oldInvoke =
2004         cast<llvm::InvokeInst>(callSite.getInstruction());
2005       newCall = llvm::InvokeInst::Create(newFn,
2006                                          oldInvoke->getNormalDest(),
2007                                          oldInvoke->getUnwindDest(),
2008                                          newArgs, "",
2009                                          callSite.getInstruction());
2010     }
2011     newArgs.clear(); // for the next iteration
2012 
2013     if (!newCall->getType()->isVoidTy())
2014       newCall->takeName(callSite.getInstruction());
2015     newCall.setAttributes(
2016                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2017     newCall.setCallingConv(callSite.getCallingConv());
2018 
2019     // Finally, remove the old call, replacing any uses with the new one.
2020     if (!callSite->use_empty())
2021       callSite->replaceAllUsesWith(newCall.getInstruction());
2022 
2023     // Copy debug location attached to CI.
2024     if (!callSite->getDebugLoc().isUnknown())
2025       newCall->setDebugLoc(callSite->getDebugLoc());
2026     callSite->eraseFromParent();
2027   }
2028 }
2029 
2030 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2031 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2032 /// existing call uses of the old function in the module, this adjusts them to
2033 /// call the new function directly.
2034 ///
2035 /// This is not just a cleanup: the always_inline pass requires direct calls to
2036 /// functions to be able to inline them.  If there is a bitcast in the way, it
2037 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2038 /// run at -O0.
2039 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2040                                                       llvm::Function *NewFn) {
2041   // If we're redefining a global as a function, don't transform it.
2042   if (!isa<llvm::Function>(Old)) return;
2043 
2044   replaceUsesOfNonProtoConstant(Old, NewFn);
2045 }
2046 
2047 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2048   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2049   // If we have a definition, this might be a deferred decl. If the
2050   // instantiation is explicit, make sure we emit it at the end.
2051   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2052     GetAddrOfGlobalVar(VD);
2053 
2054   EmitTopLevelDecl(VD);
2055 }
2056 
2057 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
2058   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2059 
2060   // Compute the function info and LLVM type.
2061   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2062   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2063 
2064   // Get or create the prototype for the function.
2065   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
2066 
2067   // Strip off a bitcast if we got one back.
2068   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2069     assert(CE->getOpcode() == llvm::Instruction::BitCast);
2070     Entry = CE->getOperand(0);
2071   }
2072 
2073 
2074   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2075     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
2076 
2077     // If the types mismatch then we have to rewrite the definition.
2078     assert(OldFn->isDeclaration() &&
2079            "Shouldn't replace non-declaration");
2080 
2081     // F is the Function* for the one with the wrong type, we must make a new
2082     // Function* and update everything that used F (a declaration) with the new
2083     // Function* (which will be a definition).
2084     //
2085     // This happens if there is a prototype for a function
2086     // (e.g. "int f()") and then a definition of a different type
2087     // (e.g. "int f(int x)").  Move the old function aside so that it
2088     // doesn't interfere with GetAddrOfFunction.
2089     OldFn->setName(StringRef());
2090     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2091 
2092     // This might be an implementation of a function without a
2093     // prototype, in which case, try to do special replacement of
2094     // calls which match the new prototype.  The really key thing here
2095     // is that we also potentially drop arguments from the call site
2096     // so as to make a direct call, which makes the inliner happier
2097     // and suppresses a number of optimizer warnings (!) about
2098     // dropping arguments.
2099     if (!OldFn->use_empty()) {
2100       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
2101       OldFn->removeDeadConstantUsers();
2102     }
2103 
2104     // Replace uses of F with the Function we will endow with a body.
2105     if (!Entry->use_empty()) {
2106       llvm::Constant *NewPtrForOldDecl =
2107         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2108       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2109     }
2110 
2111     // Ok, delete the old function now, which is dead.
2112     OldFn->eraseFromParent();
2113 
2114     Entry = NewFn;
2115   }
2116 
2117   // We need to set linkage and visibility on the function before
2118   // generating code for it because various parts of IR generation
2119   // want to propagate this information down (e.g. to local static
2120   // declarations).
2121   llvm::Function *Fn = cast<llvm::Function>(Entry);
2122   setFunctionLinkage(D, Fn);
2123 
2124   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
2125   setGlobalVisibility(Fn, D);
2126 
2127   MaybeHandleStaticInExternC(D, Fn);
2128 
2129   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2130 
2131   SetFunctionDefinitionAttributes(D, Fn);
2132   SetLLVMFunctionAttributesForDefinition(D, Fn);
2133 
2134   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2135     AddGlobalCtor(Fn, CA->getPriority());
2136   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2137     AddGlobalDtor(Fn, DA->getPriority());
2138   if (D->hasAttr<AnnotateAttr>())
2139     AddGlobalAnnotations(D, Fn);
2140 }
2141 
2142 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2143   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
2144   const AliasAttr *AA = D->getAttr<AliasAttr>();
2145   assert(AA && "Not an alias?");
2146 
2147   StringRef MangledName = getMangledName(GD);
2148 
2149   // If there is a definition in the module, then it wins over the alias.
2150   // This is dubious, but allow it to be safe.  Just ignore the alias.
2151   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2152   if (Entry && !Entry->isDeclaration())
2153     return;
2154 
2155   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2156 
2157   // Create a reference to the named value.  This ensures that it is emitted
2158   // if a deferred decl.
2159   llvm::Constant *Aliasee;
2160   if (isa<llvm::FunctionType>(DeclTy))
2161     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2162                                       /*ForVTable=*/false);
2163   else
2164     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2165                                     llvm::PointerType::getUnqual(DeclTy), 0);
2166 
2167   // Create the new alias itself, but don't set a name yet.
2168   llvm::GlobalValue *GA =
2169     new llvm::GlobalAlias(Aliasee->getType(),
2170                           llvm::Function::ExternalLinkage,
2171                           "", Aliasee, &getModule());
2172 
2173   if (Entry) {
2174     assert(Entry->isDeclaration());
2175 
2176     // If there is a declaration in the module, then we had an extern followed
2177     // by the alias, as in:
2178     //   extern int test6();
2179     //   ...
2180     //   int test6() __attribute__((alias("test7")));
2181     //
2182     // Remove it and replace uses of it with the alias.
2183     GA->takeName(Entry);
2184 
2185     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2186                                                           Entry->getType()));
2187     Entry->eraseFromParent();
2188   } else {
2189     GA->setName(MangledName);
2190   }
2191 
2192   // Set attributes which are particular to an alias; this is a
2193   // specialization of the attributes which may be set on a global
2194   // variable/function.
2195   if (D->hasAttr<DLLExportAttr>()) {
2196     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2197       // The dllexport attribute is ignored for undefined symbols.
2198       if (FD->hasBody())
2199         GA->setLinkage(llvm::Function::DLLExportLinkage);
2200     } else {
2201       GA->setLinkage(llvm::Function::DLLExportLinkage);
2202     }
2203   } else if (D->hasAttr<WeakAttr>() ||
2204              D->hasAttr<WeakRefAttr>() ||
2205              D->isWeakImported()) {
2206     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2207   }
2208 
2209   SetCommonAttributes(D, GA);
2210 }
2211 
2212 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2213                                             ArrayRef<llvm::Type*> Tys) {
2214   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2215                                          Tys);
2216 }
2217 
2218 static llvm::StringMapEntry<llvm::Constant*> &
2219 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2220                          const StringLiteral *Literal,
2221                          bool TargetIsLSB,
2222                          bool &IsUTF16,
2223                          unsigned &StringLength) {
2224   StringRef String = Literal->getString();
2225   unsigned NumBytes = String.size();
2226 
2227   // Check for simple case.
2228   if (!Literal->containsNonAsciiOrNull()) {
2229     StringLength = NumBytes;
2230     return Map.GetOrCreateValue(String);
2231   }
2232 
2233   // Otherwise, convert the UTF8 literals into a string of shorts.
2234   IsUTF16 = true;
2235 
2236   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2237   const UTF8 *FromPtr = (const UTF8 *)String.data();
2238   UTF16 *ToPtr = &ToBuf[0];
2239 
2240   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2241                            &ToPtr, ToPtr + NumBytes,
2242                            strictConversion);
2243 
2244   // ConvertUTF8toUTF16 returns the length in ToPtr.
2245   StringLength = ToPtr - &ToBuf[0];
2246 
2247   // Add an explicit null.
2248   *ToPtr = 0;
2249   return Map.
2250     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2251                                (StringLength + 1) * 2));
2252 }
2253 
2254 static llvm::StringMapEntry<llvm::Constant*> &
2255 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2256                        const StringLiteral *Literal,
2257                        unsigned &StringLength) {
2258   StringRef String = Literal->getString();
2259   StringLength = String.size();
2260   return Map.GetOrCreateValue(String);
2261 }
2262 
2263 llvm::Constant *
2264 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2265   unsigned StringLength = 0;
2266   bool isUTF16 = false;
2267   llvm::StringMapEntry<llvm::Constant*> &Entry =
2268     GetConstantCFStringEntry(CFConstantStringMap, Literal,
2269                              getDataLayout().isLittleEndian(),
2270                              isUTF16, StringLength);
2271 
2272   if (llvm::Constant *C = Entry.getValue())
2273     return C;
2274 
2275   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2276   llvm::Constant *Zeros[] = { Zero, Zero };
2277   llvm::Value *V;
2278 
2279   // If we don't already have it, get __CFConstantStringClassReference.
2280   if (!CFConstantStringClassRef) {
2281     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2282     Ty = llvm::ArrayType::get(Ty, 0);
2283     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2284                                            "__CFConstantStringClassReference");
2285     // Decay array -> ptr
2286     V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2287     CFConstantStringClassRef = V;
2288   }
2289   else
2290     V = CFConstantStringClassRef;
2291 
2292   QualType CFTy = getContext().getCFConstantStringType();
2293 
2294   llvm::StructType *STy =
2295     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2296 
2297   llvm::Constant *Fields[4];
2298 
2299   // Class pointer.
2300   Fields[0] = cast<llvm::ConstantExpr>(V);
2301 
2302   // Flags.
2303   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2304   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2305     llvm::ConstantInt::get(Ty, 0x07C8);
2306 
2307   // String pointer.
2308   llvm::Constant *C = 0;
2309   if (isUTF16) {
2310     ArrayRef<uint16_t> Arr =
2311       llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2312                                      const_cast<char *>(Entry.getKey().data())),
2313                                    Entry.getKey().size() / 2);
2314     C = llvm::ConstantDataArray::get(VMContext, Arr);
2315   } else {
2316     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2317   }
2318 
2319   llvm::GlobalValue::LinkageTypes Linkage;
2320   if (isUTF16)
2321     // FIXME: why do utf strings get "_" labels instead of "L" labels?
2322     Linkage = llvm::GlobalValue::InternalLinkage;
2323   else
2324     // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2325     // when using private linkage. It is not clear if this is a bug in ld
2326     // or a reasonable new restriction.
2327     Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2328 
2329   // Note: -fwritable-strings doesn't make the backing store strings of
2330   // CFStrings writable. (See <rdar://problem/10657500>)
2331   llvm::GlobalVariable *GV =
2332     new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2333                              Linkage, C, ".str");
2334   GV->setUnnamedAddr(true);
2335   if (isUTF16) {
2336     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2337     GV->setAlignment(Align.getQuantity());
2338   } else {
2339     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2340     GV->setAlignment(Align.getQuantity());
2341   }
2342 
2343   // String.
2344   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2345 
2346   if (isUTF16)
2347     // Cast the UTF16 string to the correct type.
2348     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2349 
2350   // String length.
2351   Ty = getTypes().ConvertType(getContext().LongTy);
2352   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2353 
2354   // The struct.
2355   C = llvm::ConstantStruct::get(STy, Fields);
2356   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2357                                 llvm::GlobalVariable::PrivateLinkage, C,
2358                                 "_unnamed_cfstring_");
2359   if (const char *Sect = getTarget().getCFStringSection())
2360     GV->setSection(Sect);
2361   Entry.setValue(GV);
2362 
2363   return GV;
2364 }
2365 
2366 static RecordDecl *
2367 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2368                  DeclContext *DC, IdentifierInfo *Id) {
2369   SourceLocation Loc;
2370   if (Ctx.getLangOpts().CPlusPlus)
2371     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2372   else
2373     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2374 }
2375 
2376 llvm::Constant *
2377 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2378   unsigned StringLength = 0;
2379   llvm::StringMapEntry<llvm::Constant*> &Entry =
2380     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2381 
2382   if (llvm::Constant *C = Entry.getValue())
2383     return C;
2384 
2385   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2386   llvm::Constant *Zeros[] = { Zero, Zero };
2387   llvm::Value *V;
2388   // If we don't already have it, get _NSConstantStringClassReference.
2389   if (!ConstantStringClassRef) {
2390     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2391     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2392     llvm::Constant *GV;
2393     if (LangOpts.ObjCRuntime.isNonFragile()) {
2394       std::string str =
2395         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2396                             : "OBJC_CLASS_$_" + StringClass;
2397       GV = getObjCRuntime().GetClassGlobal(str);
2398       // Make sure the result is of the correct type.
2399       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2400       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2401       ConstantStringClassRef = V;
2402     } else {
2403       std::string str =
2404         StringClass.empty() ? "_NSConstantStringClassReference"
2405                             : "_" + StringClass + "ClassReference";
2406       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2407       GV = CreateRuntimeVariable(PTy, str);
2408       // Decay array -> ptr
2409       V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2410       ConstantStringClassRef = V;
2411     }
2412   }
2413   else
2414     V = ConstantStringClassRef;
2415 
2416   if (!NSConstantStringType) {
2417     // Construct the type for a constant NSString.
2418     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2419                                      Context.getTranslationUnitDecl(),
2420                                    &Context.Idents.get("__builtin_NSString"));
2421     D->startDefinition();
2422 
2423     QualType FieldTypes[3];
2424 
2425     // const int *isa;
2426     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2427     // const char *str;
2428     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2429     // unsigned int length;
2430     FieldTypes[2] = Context.UnsignedIntTy;
2431 
2432     // Create fields
2433     for (unsigned i = 0; i < 3; ++i) {
2434       FieldDecl *Field = FieldDecl::Create(Context, D,
2435                                            SourceLocation(),
2436                                            SourceLocation(), 0,
2437                                            FieldTypes[i], /*TInfo=*/0,
2438                                            /*BitWidth=*/0,
2439                                            /*Mutable=*/false,
2440                                            ICIS_NoInit);
2441       Field->setAccess(AS_public);
2442       D->addDecl(Field);
2443     }
2444 
2445     D->completeDefinition();
2446     QualType NSTy = Context.getTagDeclType(D);
2447     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2448   }
2449 
2450   llvm::Constant *Fields[3];
2451 
2452   // Class pointer.
2453   Fields[0] = cast<llvm::ConstantExpr>(V);
2454 
2455   // String pointer.
2456   llvm::Constant *C =
2457     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2458 
2459   llvm::GlobalValue::LinkageTypes Linkage;
2460   bool isConstant;
2461   Linkage = llvm::GlobalValue::PrivateLinkage;
2462   isConstant = !LangOpts.WritableStrings;
2463 
2464   llvm::GlobalVariable *GV =
2465   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2466                            ".str");
2467   GV->setUnnamedAddr(true);
2468   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2469   GV->setAlignment(Align.getQuantity());
2470   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2471 
2472   // String length.
2473   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2474   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2475 
2476   // The struct.
2477   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2478   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2479                                 llvm::GlobalVariable::PrivateLinkage, C,
2480                                 "_unnamed_nsstring_");
2481   // FIXME. Fix section.
2482   if (const char *Sect =
2483         LangOpts.ObjCRuntime.isNonFragile()
2484           ? getTarget().getNSStringNonFragileABISection()
2485           : getTarget().getNSStringSection())
2486     GV->setSection(Sect);
2487   Entry.setValue(GV);
2488 
2489   return GV;
2490 }
2491 
2492 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2493   if (ObjCFastEnumerationStateType.isNull()) {
2494     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2495                                      Context.getTranslationUnitDecl(),
2496                       &Context.Idents.get("__objcFastEnumerationState"));
2497     D->startDefinition();
2498 
2499     QualType FieldTypes[] = {
2500       Context.UnsignedLongTy,
2501       Context.getPointerType(Context.getObjCIdType()),
2502       Context.getPointerType(Context.UnsignedLongTy),
2503       Context.getConstantArrayType(Context.UnsignedLongTy,
2504                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2505     };
2506 
2507     for (size_t i = 0; i < 4; ++i) {
2508       FieldDecl *Field = FieldDecl::Create(Context,
2509                                            D,
2510                                            SourceLocation(),
2511                                            SourceLocation(), 0,
2512                                            FieldTypes[i], /*TInfo=*/0,
2513                                            /*BitWidth=*/0,
2514                                            /*Mutable=*/false,
2515                                            ICIS_NoInit);
2516       Field->setAccess(AS_public);
2517       D->addDecl(Field);
2518     }
2519 
2520     D->completeDefinition();
2521     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2522   }
2523 
2524   return ObjCFastEnumerationStateType;
2525 }
2526 
2527 llvm::Constant *
2528 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2529   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2530 
2531   // Don't emit it as the address of the string, emit the string data itself
2532   // as an inline array.
2533   if (E->getCharByteWidth() == 1) {
2534     SmallString<64> Str(E->getString());
2535 
2536     // Resize the string to the right size, which is indicated by its type.
2537     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2538     Str.resize(CAT->getSize().getZExtValue());
2539     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2540   }
2541 
2542   llvm::ArrayType *AType =
2543     cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2544   llvm::Type *ElemTy = AType->getElementType();
2545   unsigned NumElements = AType->getNumElements();
2546 
2547   // Wide strings have either 2-byte or 4-byte elements.
2548   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2549     SmallVector<uint16_t, 32> Elements;
2550     Elements.reserve(NumElements);
2551 
2552     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2553       Elements.push_back(E->getCodeUnit(i));
2554     Elements.resize(NumElements);
2555     return llvm::ConstantDataArray::get(VMContext, Elements);
2556   }
2557 
2558   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2559   SmallVector<uint32_t, 32> Elements;
2560   Elements.reserve(NumElements);
2561 
2562   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2563     Elements.push_back(E->getCodeUnit(i));
2564   Elements.resize(NumElements);
2565   return llvm::ConstantDataArray::get(VMContext, Elements);
2566 }
2567 
2568 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2569 /// constant array for the given string literal.
2570 llvm::Constant *
2571 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2572   CharUnits Align = getContext().getTypeAlignInChars(S->getType());
2573   if (S->isAscii() || S->isUTF8()) {
2574     SmallString<64> Str(S->getString());
2575 
2576     // Resize the string to the right size, which is indicated by its type.
2577     const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2578     Str.resize(CAT->getSize().getZExtValue());
2579     return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2580   }
2581 
2582   // FIXME: the following does not memoize wide strings.
2583   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2584   llvm::GlobalVariable *GV =
2585     new llvm::GlobalVariable(getModule(),C->getType(),
2586                              !LangOpts.WritableStrings,
2587                              llvm::GlobalValue::PrivateLinkage,
2588                              C,".str");
2589 
2590   GV->setAlignment(Align.getQuantity());
2591   GV->setUnnamedAddr(true);
2592   return GV;
2593 }
2594 
2595 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2596 /// array for the given ObjCEncodeExpr node.
2597 llvm::Constant *
2598 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2599   std::string Str;
2600   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2601 
2602   return GetAddrOfConstantCString(Str);
2603 }
2604 
2605 
2606 /// GenerateWritableString -- Creates storage for a string literal.
2607 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2608                                              bool constant,
2609                                              CodeGenModule &CGM,
2610                                              const char *GlobalName,
2611                                              unsigned Alignment) {
2612   // Create Constant for this string literal. Don't add a '\0'.
2613   llvm::Constant *C =
2614       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2615 
2616   // Create a global variable for this string
2617   llvm::GlobalVariable *GV =
2618     new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2619                              llvm::GlobalValue::PrivateLinkage,
2620                              C, GlobalName);
2621   GV->setAlignment(Alignment);
2622   GV->setUnnamedAddr(true);
2623   return GV;
2624 }
2625 
2626 /// GetAddrOfConstantString - Returns a pointer to a character array
2627 /// containing the literal. This contents are exactly that of the
2628 /// given string, i.e. it will not be null terminated automatically;
2629 /// see GetAddrOfConstantCString. Note that whether the result is
2630 /// actually a pointer to an LLVM constant depends on
2631 /// Feature.WriteableStrings.
2632 ///
2633 /// The result has pointer to array type.
2634 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2635                                                        const char *GlobalName,
2636                                                        unsigned Alignment) {
2637   // Get the default prefix if a name wasn't specified.
2638   if (!GlobalName)
2639     GlobalName = ".str";
2640 
2641   // Don't share any string literals if strings aren't constant.
2642   if (LangOpts.WritableStrings)
2643     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2644 
2645   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2646     ConstantStringMap.GetOrCreateValue(Str);
2647 
2648   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2649     if (Alignment > GV->getAlignment()) {
2650       GV->setAlignment(Alignment);
2651     }
2652     return GV;
2653   }
2654 
2655   // Create a global variable for this.
2656   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2657                                                    Alignment);
2658   Entry.setValue(GV);
2659   return GV;
2660 }
2661 
2662 /// GetAddrOfConstantCString - Returns a pointer to a character
2663 /// array containing the literal and a terminating '\0'
2664 /// character. The result has pointer to array type.
2665 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2666                                                         const char *GlobalName,
2667                                                         unsigned Alignment) {
2668   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2669   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2670 }
2671 
2672 /// EmitObjCPropertyImplementations - Emit information for synthesized
2673 /// properties for an implementation.
2674 void CodeGenModule::EmitObjCPropertyImplementations(const
2675                                                     ObjCImplementationDecl *D) {
2676   for (ObjCImplementationDecl::propimpl_iterator
2677          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2678     ObjCPropertyImplDecl *PID = *i;
2679 
2680     // Dynamic is just for type-checking.
2681     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2682       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2683 
2684       // Determine which methods need to be implemented, some may have
2685       // been overridden. Note that ::isPropertyAccessor is not the method
2686       // we want, that just indicates if the decl came from a
2687       // property. What we want to know is if the method is defined in
2688       // this implementation.
2689       if (!D->getInstanceMethod(PD->getGetterName()))
2690         CodeGenFunction(*this).GenerateObjCGetter(
2691                                  const_cast<ObjCImplementationDecl *>(D), PID);
2692       if (!PD->isReadOnly() &&
2693           !D->getInstanceMethod(PD->getSetterName()))
2694         CodeGenFunction(*this).GenerateObjCSetter(
2695                                  const_cast<ObjCImplementationDecl *>(D), PID);
2696     }
2697   }
2698 }
2699 
2700 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2701   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2702   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2703        ivar; ivar = ivar->getNextIvar())
2704     if (ivar->getType().isDestructedType())
2705       return true;
2706 
2707   return false;
2708 }
2709 
2710 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2711 /// for an implementation.
2712 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2713   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2714   if (needsDestructMethod(D)) {
2715     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2716     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2717     ObjCMethodDecl *DTORMethod =
2718       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2719                              cxxSelector, getContext().VoidTy, 0, D,
2720                              /*isInstance=*/true, /*isVariadic=*/false,
2721                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2722                              /*isDefined=*/false, ObjCMethodDecl::Required);
2723     D->addInstanceMethod(DTORMethod);
2724     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2725     D->setHasDestructors(true);
2726   }
2727 
2728   // If the implementation doesn't have any ivar initializers, we don't need
2729   // a .cxx_construct.
2730   if (D->getNumIvarInitializers() == 0)
2731     return;
2732 
2733   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2734   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2735   // The constructor returns 'self'.
2736   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2737                                                 D->getLocation(),
2738                                                 D->getLocation(),
2739                                                 cxxSelector,
2740                                                 getContext().getObjCIdType(), 0,
2741                                                 D, /*isInstance=*/true,
2742                                                 /*isVariadic=*/false,
2743                                                 /*isPropertyAccessor=*/true,
2744                                                 /*isImplicitlyDeclared=*/true,
2745                                                 /*isDefined=*/false,
2746                                                 ObjCMethodDecl::Required);
2747   D->addInstanceMethod(CTORMethod);
2748   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2749   D->setHasNonZeroConstructors(true);
2750 }
2751 
2752 /// EmitNamespace - Emit all declarations in a namespace.
2753 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2754   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2755        I != E; ++I)
2756     EmitTopLevelDecl(*I);
2757 }
2758 
2759 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2760 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2761   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2762       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2763     ErrorUnsupported(LSD, "linkage spec");
2764     return;
2765   }
2766 
2767   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2768        I != E; ++I) {
2769     // Meta-data for ObjC class includes references to implemented methods.
2770     // Generate class's method definitions first.
2771     if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2772       for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2773            MEnd = OID->meth_end();
2774            M != MEnd; ++M)
2775         EmitTopLevelDecl(*M);
2776     }
2777     EmitTopLevelDecl(*I);
2778   }
2779 }
2780 
2781 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2782 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2783   // If an error has occurred, stop code generation, but continue
2784   // parsing and semantic analysis (to ensure all warnings and errors
2785   // are emitted).
2786   if (Diags.hasErrorOccurred())
2787     return;
2788 
2789   // Ignore dependent declarations.
2790   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2791     return;
2792 
2793   switch (D->getKind()) {
2794   case Decl::CXXConversion:
2795   case Decl::CXXMethod:
2796   case Decl::Function:
2797     // Skip function templates
2798     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2799         cast<FunctionDecl>(D)->isLateTemplateParsed())
2800       return;
2801 
2802     EmitGlobal(cast<FunctionDecl>(D));
2803     break;
2804 
2805   case Decl::Var:
2806     EmitGlobal(cast<VarDecl>(D));
2807     break;
2808 
2809   // Indirect fields from global anonymous structs and unions can be
2810   // ignored; only the actual variable requires IR gen support.
2811   case Decl::IndirectField:
2812     break;
2813 
2814   // C++ Decls
2815   case Decl::Namespace:
2816     EmitNamespace(cast<NamespaceDecl>(D));
2817     break;
2818     // No code generation needed.
2819   case Decl::UsingShadow:
2820   case Decl::Using:
2821   case Decl::UsingDirective:
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::CXXConstructor:
2830     // Skip function templates
2831     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2832         cast<FunctionDecl>(D)->isLateTemplateParsed())
2833       return;
2834 
2835     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2836     break;
2837   case Decl::CXXDestructor:
2838     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2839       return;
2840     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2841     break;
2842 
2843   case Decl::StaticAssert:
2844     // Nothing to do.
2845     break;
2846 
2847   // Objective-C Decls
2848 
2849   // Forward declarations, no (immediate) code generation.
2850   case Decl::ObjCInterface:
2851   case Decl::ObjCCategory:
2852     break;
2853 
2854   case Decl::ObjCProtocol: {
2855     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2856     if (Proto->isThisDeclarationADefinition())
2857       ObjCRuntime->GenerateProtocol(Proto);
2858     break;
2859   }
2860 
2861   case Decl::ObjCCategoryImpl:
2862     // Categories have properties but don't support synthesize so we
2863     // can ignore them here.
2864     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2865     break;
2866 
2867   case Decl::ObjCImplementation: {
2868     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2869     EmitObjCPropertyImplementations(OMD);
2870     EmitObjCIvarInitializations(OMD);
2871     ObjCRuntime->GenerateClass(OMD);
2872     // Emit global variable debug information.
2873     if (CGDebugInfo *DI = getModuleDebugInfo())
2874       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2875         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2876             OMD->getClassInterface()), OMD->getLocation());
2877     break;
2878   }
2879   case Decl::ObjCMethod: {
2880     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2881     // If this is not a prototype, emit the body.
2882     if (OMD->getBody())
2883       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2884     break;
2885   }
2886   case Decl::ObjCCompatibleAlias:
2887     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2888     break;
2889 
2890   case Decl::LinkageSpec:
2891     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2892     break;
2893 
2894   case Decl::FileScopeAsm: {
2895     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2896     StringRef AsmString = AD->getAsmString()->getString();
2897 
2898     const std::string &S = getModule().getModuleInlineAsm();
2899     if (S.empty())
2900       getModule().setModuleInlineAsm(AsmString);
2901     else if (S.end()[-1] == '\n')
2902       getModule().setModuleInlineAsm(S + AsmString.str());
2903     else
2904       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2905     break;
2906   }
2907 
2908   case Decl::Import: {
2909     ImportDecl *Import = cast<ImportDecl>(D);
2910 
2911     // Ignore import declarations that come from imported modules.
2912     if (clang::Module *Owner = Import->getOwningModule()) {
2913       if (getLangOpts().CurrentModule.empty() ||
2914           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
2915         break;
2916     }
2917 
2918     ImportedModules.insert(Import->getImportedModule());
2919     break;
2920  }
2921 
2922   default:
2923     // Make sure we handled everything we should, every other kind is a
2924     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2925     // function. Need to recode Decl::Kind to do that easily.
2926     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2927   }
2928 }
2929 
2930 /// Turns the given pointer into a constant.
2931 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2932                                           const void *Ptr) {
2933   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2934   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2935   return llvm::ConstantInt::get(i64, PtrInt);
2936 }
2937 
2938 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2939                                    llvm::NamedMDNode *&GlobalMetadata,
2940                                    GlobalDecl D,
2941                                    llvm::GlobalValue *Addr) {
2942   if (!GlobalMetadata)
2943     GlobalMetadata =
2944       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2945 
2946   // TODO: should we report variant information for ctors/dtors?
2947   llvm::Value *Ops[] = {
2948     Addr,
2949     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2950   };
2951   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2952 }
2953 
2954 /// For each function which is declared within an extern "C" region and marked
2955 /// as 'used', but has internal linkage, create an alias from the unmangled
2956 /// name to the mangled name if possible. People expect to be able to refer
2957 /// to such functions with an unmangled name from inline assembly within the
2958 /// same translation unit.
2959 void CodeGenModule::EmitStaticExternCAliases() {
2960   for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
2961                                   E = StaticExternCValues.end();
2962        I != E; ++I) {
2963     IdentifierInfo *Name = I->first;
2964     llvm::GlobalValue *Val = I->second;
2965     if (Val && !getModule().getNamedValue(Name->getName()))
2966       AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
2967                                           Name->getName(), Val, &getModule()));
2968   }
2969 }
2970 
2971 /// Emits metadata nodes associating all the global values in the
2972 /// current module with the Decls they came from.  This is useful for
2973 /// projects using IR gen as a subroutine.
2974 ///
2975 /// Since there's currently no way to associate an MDNode directly
2976 /// with an llvm::GlobalValue, we create a global named metadata
2977 /// with the name 'clang.global.decl.ptrs'.
2978 void CodeGenModule::EmitDeclMetadata() {
2979   llvm::NamedMDNode *GlobalMetadata = 0;
2980 
2981   // StaticLocalDeclMap
2982   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2983          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2984        I != E; ++I) {
2985     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2986     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2987   }
2988 }
2989 
2990 /// Emits metadata nodes for all the local variables in the current
2991 /// function.
2992 void CodeGenFunction::EmitDeclMetadata() {
2993   if (LocalDeclMap.empty()) return;
2994 
2995   llvm::LLVMContext &Context = getLLVMContext();
2996 
2997   // Find the unique metadata ID for this name.
2998   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2999 
3000   llvm::NamedMDNode *GlobalMetadata = 0;
3001 
3002   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3003          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3004     const Decl *D = I->first;
3005     llvm::Value *Addr = I->second;
3006 
3007     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3008       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3009       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3010     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3011       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3012       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3013     }
3014   }
3015 }
3016 
3017 void CodeGenModule::EmitCoverageFile() {
3018   if (!getCodeGenOpts().CoverageFile.empty()) {
3019     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3020       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3021       llvm::LLVMContext &Ctx = TheModule.getContext();
3022       llvm::MDString *CoverageFile =
3023           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3024       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3025         llvm::MDNode *CU = CUNode->getOperand(i);
3026         llvm::Value *node[] = { CoverageFile, CU };
3027         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3028         GCov->addOperand(N);
3029       }
3030     }
3031   }
3032 }
3033 
3034 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3035                                                      QualType GuidType) {
3036   // Sema has checked that all uuid strings are of the form
3037   // "12345678-1234-1234-1234-1234567890ab".
3038   assert(Uuid.size() == 36);
3039   const char *Uuidstr = Uuid.data();
3040   for (int i = 0; i < 36; ++i) {
3041     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
3042     else                                         assert(isHexDigit(Uuidstr[i]));
3043   }
3044 
3045   llvm::APInt Field0(32, StringRef(Uuidstr     , 8), 16);
3046   llvm::APInt Field1(16, StringRef(Uuidstr +  9, 4), 16);
3047   llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
3048   static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3049 
3050   APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
3051   InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
3052   InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
3053   InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
3054   APValue& Arr = InitStruct.getStructField(3);
3055   Arr = APValue(APValue::UninitArray(), 8, 8);
3056   for (int t = 0; t < 8; ++t)
3057     Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
3058           llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
3059 
3060   return EmitConstantValue(InitStruct, GuidType);
3061 }
3062