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