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