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