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