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