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