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