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