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