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