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