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