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