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