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