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->getStorageClass() == VarDecl::Static) {
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   // Static variables get internal linkage.
987   if (VD->getStorageClass() == VarDecl::Static)
988     return CodeGenModule::GVA_Internal;
989 
990   return CodeGenModule::GVA_StrongExternal;
991 }
992 
993 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
994   llvm::Constant *Init = 0;
995   QualType ASTTy = D->getType();
996 
997   if (D->getInit() == 0) {
998     // This is a tentative definition; tentative definitions are
999     // implicitly initialized with { 0 }.
1000     //
1001     // Note that tentative definitions are only emitted at the end of
1002     // a translation unit, so they should never have incomplete
1003     // type. In addition, EmitTentativeDefinition makes sure that we
1004     // never attempt to emit a tentative definition if a real one
1005     // exists. A use may still exists, however, so we still may need
1006     // to do a RAUW.
1007     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1008     Init = EmitNullConstant(D->getType());
1009   } else {
1010     Init = EmitConstantExpr(D->getInit(), D->getType());
1011 
1012     if (!Init) {
1013       QualType T = D->getInit()->getType();
1014       if (getLangOptions().CPlusPlus) {
1015         CXXGlobalInits.push_back(D);
1016         Init = EmitNullConstant(T);
1017       } else {
1018         ErrorUnsupported(D, "static initializer");
1019         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1020       }
1021     }
1022   }
1023 
1024   const llvm::Type* InitType = Init->getType();
1025   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1026 
1027   // Strip off a bitcast if we got one back.
1028   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1029     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1030            // all zero index gep.
1031            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1032     Entry = CE->getOperand(0);
1033   }
1034 
1035   // Entry is now either a Function or GlobalVariable.
1036   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1037 
1038   // We have a definition after a declaration with the wrong type.
1039   // We must make a new GlobalVariable* and update everything that used OldGV
1040   // (a declaration or tentative definition) with the new GlobalVariable*
1041   // (which will be a definition).
1042   //
1043   // This happens if there is a prototype for a global (e.g.
1044   // "extern int x[];") and then a definition of a different type (e.g.
1045   // "int x[10];"). This also happens when an initializer has a different type
1046   // from the type of the global (this happens with unions).
1047   if (GV == 0 ||
1048       GV->getType()->getElementType() != InitType ||
1049       GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
1050 
1051     // Remove the old entry from GlobalDeclMap so that we'll create a new one.
1052     GlobalDeclMap.erase(getMangledName(D));
1053 
1054     // Make a new global with the correct type, this is now guaranteed to work.
1055     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1056     GV->takeName(cast<llvm::GlobalValue>(Entry));
1057 
1058     // Replace all uses of the old global with the new global
1059     llvm::Constant *NewPtrForOldDecl =
1060         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1061     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1062 
1063     // Erase the old global, since it is no longer used.
1064     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1065   }
1066 
1067   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1068     SourceManager &SM = Context.getSourceManager();
1069     AddAnnotation(EmitAnnotateAttr(GV, AA,
1070                               SM.getInstantiationLineNumber(D->getLocation())));
1071   }
1072 
1073   GV->setInitializer(Init);
1074 
1075   // If it is safe to mark the global 'constant', do so now.
1076   GV->setConstant(false);
1077   if (D->getType().isConstant(Context)) {
1078     // FIXME: In C++, if the variable has a non-trivial ctor/dtor or any mutable
1079     // members, it cannot be declared "LLVM const".
1080     GV->setConstant(true);
1081   }
1082 
1083   GV->setAlignment(getContext().getDeclAlignInBytes(D));
1084 
1085   // Set the llvm linkage type as appropriate.
1086   GVALinkage Linkage = GetLinkageForVariable(getContext(), D);
1087   if (Linkage == GVA_Internal)
1088     GV->setLinkage(llvm::Function::InternalLinkage);
1089   else if (D->hasAttr<DLLImportAttr>())
1090     GV->setLinkage(llvm::Function::DLLImportLinkage);
1091   else if (D->hasAttr<DLLExportAttr>())
1092     GV->setLinkage(llvm::Function::DLLExportLinkage);
1093   else if (D->hasAttr<WeakAttr>()) {
1094     if (GV->isConstant())
1095       GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
1096     else
1097       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1098   } else if (Linkage == GVA_TemplateInstantiation)
1099     GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1100   else if (!CodeGenOpts.NoCommon &&
1101            !D->hasExternalStorage() && !D->getInit() &&
1102            !D->getAttr<SectionAttr>()) {
1103     GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
1104     // common vars aren't constant even if declared const.
1105     GV->setConstant(false);
1106   } else
1107     GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
1108 
1109   SetCommonAttributes(D, GV);
1110 
1111   // Emit global variable debug information.
1112   if (CGDebugInfo *DI = getDebugInfo()) {
1113     DI->setLocation(D->getLocation());
1114     DI->EmitGlobalVariable(GV, D);
1115   }
1116 }
1117 
1118 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1119 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1120 /// existing call uses of the old function in the module, this adjusts them to
1121 /// call the new function directly.
1122 ///
1123 /// This is not just a cleanup: the always_inline pass requires direct calls to
1124 /// functions to be able to inline them.  If there is a bitcast in the way, it
1125 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1126 /// run at -O0.
1127 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1128                                                       llvm::Function *NewFn) {
1129   // If we're redefining a global as a function, don't transform it.
1130   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1131   if (OldFn == 0) return;
1132 
1133   const llvm::Type *NewRetTy = NewFn->getReturnType();
1134   llvm::SmallVector<llvm::Value*, 4> ArgList;
1135 
1136   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1137        UI != E; ) {
1138     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1139     unsigned OpNo = UI.getOperandNo();
1140     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++);
1141     if (!CI || OpNo != 0) continue;
1142 
1143     // If the return types don't match exactly, and if the call isn't dead, then
1144     // we can't transform this call.
1145     if (CI->getType() != NewRetTy && !CI->use_empty())
1146       continue;
1147 
1148     // If the function was passed too few arguments, don't transform.  If extra
1149     // arguments were passed, we silently drop them.  If any of the types
1150     // mismatch, we don't transform.
1151     unsigned ArgNo = 0;
1152     bool DontTransform = false;
1153     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1154          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1155       if (CI->getNumOperands()-1 == ArgNo ||
1156           CI->getOperand(ArgNo+1)->getType() != AI->getType()) {
1157         DontTransform = true;
1158         break;
1159       }
1160     }
1161     if (DontTransform)
1162       continue;
1163 
1164     // Okay, we can transform this.  Create the new call instruction and copy
1165     // over the required information.
1166     ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo);
1167     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1168                                                      ArgList.end(), "", CI);
1169     ArgList.clear();
1170     if (!NewCall->getType()->isVoidTy())
1171       NewCall->takeName(CI);
1172     NewCall->setAttributes(CI->getAttributes());
1173     NewCall->setCallingConv(CI->getCallingConv());
1174 
1175     // Finally, remove the old call, replacing any uses with the new one.
1176     if (!CI->use_empty())
1177       CI->replaceAllUsesWith(NewCall);
1178 
1179     // Copy any custom metadata attached with CI.
1180     llvm::MetadataContext &TheMetadata = CI->getContext().getMetadata();
1181     TheMetadata.copyMD(CI, NewCall);
1182 
1183     CI->eraseFromParent();
1184   }
1185 }
1186 
1187 
1188 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1189   const llvm::FunctionType *Ty;
1190   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1191 
1192   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1193     bool isVariadic = D->getType()->getAs<FunctionProtoType>()->isVariadic();
1194 
1195     Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
1196   } else {
1197     Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
1198 
1199     // As a special case, make sure that definitions of K&R function
1200     // "type foo()" aren't declared as varargs (which forces the backend
1201     // to do unnecessary work).
1202     if (D->getType()->isFunctionNoProtoType()) {
1203       assert(Ty->isVarArg() && "Didn't lower type as expected");
1204       // Due to stret, the lowered function could have arguments.
1205       // Just create the same type as was lowered by ConvertType
1206       // but strip off the varargs bit.
1207       std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
1208       Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
1209     }
1210   }
1211 
1212   // Get or create the prototype for the function.
1213   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1214 
1215   // Strip off a bitcast if we got one back.
1216   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1217     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1218     Entry = CE->getOperand(0);
1219   }
1220 
1221 
1222   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1223     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1224 
1225     // If the types mismatch then we have to rewrite the definition.
1226     assert(OldFn->isDeclaration() &&
1227            "Shouldn't replace non-declaration");
1228 
1229     // F is the Function* for the one with the wrong type, we must make a new
1230     // Function* and update everything that used F (a declaration) with the new
1231     // Function* (which will be a definition).
1232     //
1233     // This happens if there is a prototype for a function
1234     // (e.g. "int f()") and then a definition of a different type
1235     // (e.g. "int f(int x)").  Start by making a new function of the
1236     // correct type, RAUW, then steal the name.
1237     GlobalDeclMap.erase(getMangledName(D));
1238     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1239     NewFn->takeName(OldFn);
1240 
1241     // If this is an implementation of a function without a prototype, try to
1242     // replace any existing uses of the function (which may be calls) with uses
1243     // of the new function
1244     if (D->getType()->isFunctionNoProtoType()) {
1245       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1246       OldFn->removeDeadConstantUsers();
1247     }
1248 
1249     // Replace uses of F with the Function we will endow with a body.
1250     if (!Entry->use_empty()) {
1251       llvm::Constant *NewPtrForOldDecl =
1252         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1253       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1254     }
1255 
1256     // Ok, delete the old function now, which is dead.
1257     OldFn->eraseFromParent();
1258 
1259     Entry = NewFn;
1260   }
1261 
1262   llvm::Function *Fn = cast<llvm::Function>(Entry);
1263 
1264   CodeGenFunction(*this).GenerateCode(D, Fn);
1265 
1266   SetFunctionDefinitionAttributes(D, Fn);
1267   SetLLVMFunctionAttributesForDefinition(D, Fn);
1268 
1269   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1270     AddGlobalCtor(Fn, CA->getPriority());
1271   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1272     AddGlobalDtor(Fn, DA->getPriority());
1273 }
1274 
1275 void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
1276   const AliasAttr *AA = D->getAttr<AliasAttr>();
1277   assert(AA && "Not an alias?");
1278 
1279   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1280 
1281   // Unique the name through the identifier table.
1282   const char *AliaseeName = AA->getAliasee().c_str();
1283   AliaseeName = getContext().Idents.get(AliaseeName).getNameStart();
1284 
1285   // Create a reference to the named value.  This ensures that it is emitted
1286   // if a deferred decl.
1287   llvm::Constant *Aliasee;
1288   if (isa<llvm::FunctionType>(DeclTy))
1289     Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
1290   else
1291     Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
1292                                     llvm::PointerType::getUnqual(DeclTy), 0);
1293 
1294   // Create the new alias itself, but don't set a name yet.
1295   llvm::GlobalValue *GA =
1296     new llvm::GlobalAlias(Aliasee->getType(),
1297                           llvm::Function::ExternalLinkage,
1298                           "", Aliasee, &getModule());
1299 
1300   // See if there is already something with the alias' name in the module.
1301   const char *MangledName = getMangledName(D);
1302   llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
1303 
1304   if (Entry && !Entry->isDeclaration()) {
1305     // If there is a definition in the module, then it wins over the alias.
1306     // This is dubious, but allow it to be safe.  Just ignore the alias.
1307     GA->eraseFromParent();
1308     return;
1309   }
1310 
1311   if (Entry) {
1312     // If there is a declaration in the module, then we had an extern followed
1313     // by the alias, as in:
1314     //   extern int test6();
1315     //   ...
1316     //   int test6() __attribute__((alias("test7")));
1317     //
1318     // Remove it and replace uses of it with the alias.
1319 
1320     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1321                                                           Entry->getType()));
1322     Entry->eraseFromParent();
1323   }
1324 
1325   // Now we know that there is no conflict, set the name.
1326   Entry = GA;
1327   GA->setName(MangledName);
1328 
1329   // Set attributes which are particular to an alias; this is a
1330   // specialization of the attributes which may be set on a global
1331   // variable/function.
1332   if (D->hasAttr<DLLExportAttr>()) {
1333     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1334       // The dllexport attribute is ignored for undefined symbols.
1335       if (FD->getBody())
1336         GA->setLinkage(llvm::Function::DLLExportLinkage);
1337     } else {
1338       GA->setLinkage(llvm::Function::DLLExportLinkage);
1339     }
1340   } else if (D->hasAttr<WeakAttr>() ||
1341              D->hasAttr<WeakImportAttr>()) {
1342     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1343   }
1344 
1345   SetCommonAttributes(D, GA);
1346 }
1347 
1348 /// getBuiltinLibFunction - Given a builtin id for a function like
1349 /// "__builtin_fabsf", return a Function* for "fabsf".
1350 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1351                                                   unsigned BuiltinID) {
1352   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1353           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1354          "isn't a lib fn");
1355 
1356   // Get the name, skip over the __builtin_ prefix (if necessary).
1357   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1358   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1359     Name += 10;
1360 
1361   // Get the type for the builtin.
1362   ASTContext::GetBuiltinTypeError Error;
1363   QualType Type = Context.GetBuiltinType(BuiltinID, Error);
1364   assert(Error == ASTContext::GE_None && "Can't get builtin type");
1365 
1366   const llvm::FunctionType *Ty =
1367     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
1368 
1369   // Unique the name through the identifier table.
1370   Name = getContext().Idents.get(Name).getNameStart();
1371   return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
1372 }
1373 
1374 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1375                                             unsigned NumTys) {
1376   return llvm::Intrinsic::getDeclaration(&getModule(),
1377                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
1378 }
1379 
1380 llvm::Function *CodeGenModule::getMemCpyFn() {
1381   if (MemCpyFn) return MemCpyFn;
1382   const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
1383   return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
1384 }
1385 
1386 llvm::Function *CodeGenModule::getMemMoveFn() {
1387   if (MemMoveFn) return MemMoveFn;
1388   const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
1389   return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
1390 }
1391 
1392 llvm::Function *CodeGenModule::getMemSetFn() {
1393   if (MemSetFn) return MemSetFn;
1394   const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
1395   return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
1396 }
1397 
1398 static llvm::StringMapEntry<llvm::Constant*> &
1399 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1400                          const StringLiteral *Literal,
1401                          bool TargetIsLSB,
1402                          bool &IsUTF16,
1403                          unsigned &StringLength) {
1404   unsigned NumBytes = Literal->getByteLength();
1405 
1406   // Check for simple case.
1407   if (!Literal->containsNonAsciiOrNull()) {
1408     StringLength = NumBytes;
1409     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1410                                                 StringLength));
1411   }
1412 
1413   // Otherwise, convert the UTF8 literals into a byte string.
1414   llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1415   const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1416   UTF16 *ToPtr = &ToBuf[0];
1417 
1418   ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1419                                                &ToPtr, ToPtr + NumBytes,
1420                                                strictConversion);
1421 
1422   // Check for conversion failure.
1423   if (Result != conversionOK) {
1424     // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1425     // this duplicate code.
1426     assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
1427     StringLength = NumBytes;
1428     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1429                                                 StringLength));
1430   }
1431 
1432   // ConvertUTF8toUTF16 returns the length in ToPtr.
1433   StringLength = ToPtr - &ToBuf[0];
1434 
1435   // Render the UTF-16 string into a byte array and convert to the target byte
1436   // order.
1437   //
1438   // FIXME: This isn't something we should need to do here.
1439   llvm::SmallString<128> AsBytes;
1440   AsBytes.reserve(StringLength * 2);
1441   for (unsigned i = 0; i != StringLength; ++i) {
1442     unsigned short Val = ToBuf[i];
1443     if (TargetIsLSB) {
1444       AsBytes.push_back(Val & 0xFF);
1445       AsBytes.push_back(Val >> 8);
1446     } else {
1447       AsBytes.push_back(Val >> 8);
1448       AsBytes.push_back(Val & 0xFF);
1449     }
1450   }
1451   // Append one extra null character, the second is automatically added by our
1452   // caller.
1453   AsBytes.push_back(0);
1454 
1455   IsUTF16 = true;
1456   return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1457 }
1458 
1459 llvm::Constant *
1460 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1461   unsigned StringLength = 0;
1462   bool isUTF16 = false;
1463   llvm::StringMapEntry<llvm::Constant*> &Entry =
1464     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1465                              getTargetData().isLittleEndian(),
1466                              isUTF16, StringLength);
1467 
1468   if (llvm::Constant *C = Entry.getValue())
1469     return C;
1470 
1471   llvm::Constant *Zero =
1472       llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1473   llvm::Constant *Zeros[] = { Zero, Zero };
1474 
1475   // If we don't already have it, get __CFConstantStringClassReference.
1476   if (!CFConstantStringClassRef) {
1477     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1478     Ty = llvm::ArrayType::get(Ty, 0);
1479     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1480                                            "__CFConstantStringClassReference");
1481     // Decay array -> ptr
1482     CFConstantStringClassRef =
1483       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1484   }
1485 
1486   QualType CFTy = getContext().getCFConstantStringType();
1487 
1488   const llvm::StructType *STy =
1489     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1490 
1491   std::vector<llvm::Constant*> Fields(4);
1492 
1493   // Class pointer.
1494   Fields[0] = CFConstantStringClassRef;
1495 
1496   // Flags.
1497   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1498   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1499     llvm::ConstantInt::get(Ty, 0x07C8);
1500 
1501   // String pointer.
1502   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1503 
1504   const char *Sect = 0;
1505   llvm::GlobalValue::LinkageTypes Linkage;
1506   bool isConstant;
1507   if (isUTF16) {
1508     Sect = getContext().Target.getUnicodeStringSection();
1509     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1510     Linkage = llvm::GlobalValue::InternalLinkage;
1511     // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1512     // does make plain ascii ones writable.
1513     isConstant = true;
1514   } else {
1515     Linkage = llvm::GlobalValue::PrivateLinkage;
1516     isConstant = !Features.WritableStrings;
1517   }
1518 
1519   llvm::GlobalVariable *GV =
1520     new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1521                              ".str");
1522   if (Sect)
1523     GV->setSection(Sect);
1524   if (isUTF16) {
1525     unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8;
1526     GV->setAlignment(Align);
1527   }
1528   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1529 
1530   // String length.
1531   Ty = getTypes().ConvertType(getContext().LongTy);
1532   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1533 
1534   // The struct.
1535   C = llvm::ConstantStruct::get(STy, Fields);
1536   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1537                                 llvm::GlobalVariable::PrivateLinkage, C,
1538                                 "_unnamed_cfstring_");
1539   if (const char *Sect = getContext().Target.getCFStringSection())
1540     GV->setSection(Sect);
1541   Entry.setValue(GV);
1542 
1543   return GV;
1544 }
1545 
1546 /// GetStringForStringLiteral - Return the appropriate bytes for a
1547 /// string literal, properly padded to match the literal type.
1548 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1549   const char *StrData = E->getStrData();
1550   unsigned Len = E->getByteLength();
1551 
1552   const ConstantArrayType *CAT =
1553     getContext().getAsConstantArrayType(E->getType());
1554   assert(CAT && "String isn't pointer or array!");
1555 
1556   // Resize the string to the right size.
1557   std::string Str(StrData, StrData+Len);
1558   uint64_t RealLen = CAT->getSize().getZExtValue();
1559 
1560   if (E->isWide())
1561     RealLen *= getContext().Target.getWCharWidth()/8;
1562 
1563   Str.resize(RealLen, '\0');
1564 
1565   return Str;
1566 }
1567 
1568 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1569 /// constant array for the given string literal.
1570 llvm::Constant *
1571 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1572   // FIXME: This can be more efficient.
1573   // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1574   llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1575   if (S->isWide()) {
1576     llvm::Type *DestTy =
1577         llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1578     C = llvm::ConstantExpr::getBitCast(C, DestTy);
1579   }
1580   return C;
1581 }
1582 
1583 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1584 /// array for the given ObjCEncodeExpr node.
1585 llvm::Constant *
1586 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1587   std::string Str;
1588   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1589 
1590   return GetAddrOfConstantCString(Str);
1591 }
1592 
1593 
1594 /// GenerateWritableString -- Creates storage for a string literal.
1595 static llvm::Constant *GenerateStringLiteral(const std::string &str,
1596                                              bool constant,
1597                                              CodeGenModule &CGM,
1598                                              const char *GlobalName) {
1599   // Create Constant for this string literal. Don't add a '\0'.
1600   llvm::Constant *C =
1601       llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1602 
1603   // Create a global variable for this string
1604   return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1605                                   llvm::GlobalValue::PrivateLinkage,
1606                                   C, GlobalName);
1607 }
1608 
1609 /// GetAddrOfConstantString - Returns a pointer to a character array
1610 /// containing the literal. This contents are exactly that of the
1611 /// given string, i.e. it will not be null terminated automatically;
1612 /// see GetAddrOfConstantCString. Note that whether the result is
1613 /// actually a pointer to an LLVM constant depends on
1614 /// Feature.WriteableStrings.
1615 ///
1616 /// The result has pointer to array type.
1617 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1618                                                        const char *GlobalName) {
1619   bool IsConstant = !Features.WritableStrings;
1620 
1621   // Get the default prefix if a name wasn't specified.
1622   if (!GlobalName)
1623     GlobalName = ".str";
1624 
1625   // Don't share any string literals if strings aren't constant.
1626   if (!IsConstant)
1627     return GenerateStringLiteral(str, false, *this, GlobalName);
1628 
1629   llvm::StringMapEntry<llvm::Constant *> &Entry =
1630     ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1631 
1632   if (Entry.getValue())
1633     return Entry.getValue();
1634 
1635   // Create a global variable for this.
1636   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1637   Entry.setValue(C);
1638   return C;
1639 }
1640 
1641 /// GetAddrOfConstantCString - Returns a pointer to a character
1642 /// array containing the literal and a terminating '\-'
1643 /// character. The result has pointer to array type.
1644 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1645                                                         const char *GlobalName){
1646   return GetAddrOfConstantString(str + '\0', GlobalName);
1647 }
1648 
1649 /// EmitObjCPropertyImplementations - Emit information for synthesized
1650 /// properties for an implementation.
1651 void CodeGenModule::EmitObjCPropertyImplementations(const
1652                                                     ObjCImplementationDecl *D) {
1653   for (ObjCImplementationDecl::propimpl_iterator
1654          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1655     ObjCPropertyImplDecl *PID = *i;
1656 
1657     // Dynamic is just for type-checking.
1658     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1659       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1660 
1661       // Determine which methods need to be implemented, some may have
1662       // been overridden. Note that ::isSynthesized is not the method
1663       // we want, that just indicates if the decl came from a
1664       // property. What we want to know is if the method is defined in
1665       // this implementation.
1666       if (!D->getInstanceMethod(PD->getGetterName()))
1667         CodeGenFunction(*this).GenerateObjCGetter(
1668                                  const_cast<ObjCImplementationDecl *>(D), PID);
1669       if (!PD->isReadOnly() &&
1670           !D->getInstanceMethod(PD->getSetterName()))
1671         CodeGenFunction(*this).GenerateObjCSetter(
1672                                  const_cast<ObjCImplementationDecl *>(D), PID);
1673     }
1674   }
1675 }
1676 
1677 /// EmitNamespace - Emit all declarations in a namespace.
1678 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1679   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1680        I != E; ++I)
1681     EmitTopLevelDecl(*I);
1682 }
1683 
1684 // EmitLinkageSpec - Emit all declarations in a linkage spec.
1685 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1686   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1687       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1688     ErrorUnsupported(LSD, "linkage spec");
1689     return;
1690   }
1691 
1692   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1693        I != E; ++I)
1694     EmitTopLevelDecl(*I);
1695 }
1696 
1697 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1698 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1699   // If an error has occurred, stop code generation, but continue
1700   // parsing and semantic analysis (to ensure all warnings and errors
1701   // are emitted).
1702   if (Diags.hasErrorOccurred())
1703     return;
1704 
1705   // Ignore dependent declarations.
1706   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1707     return;
1708 
1709   switch (D->getKind()) {
1710   case Decl::CXXConversion:
1711   case Decl::CXXMethod:
1712   case Decl::Function:
1713     // Skip function templates
1714     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1715       return;
1716 
1717     EmitGlobal(cast<FunctionDecl>(D));
1718     break;
1719 
1720   case Decl::Var:
1721     EmitGlobal(cast<VarDecl>(D));
1722     break;
1723 
1724   // C++ Decls
1725   case Decl::Namespace:
1726     EmitNamespace(cast<NamespaceDecl>(D));
1727     break;
1728     // No code generation needed.
1729   case Decl::UsingShadow:
1730   case Decl::Using:
1731   case Decl::UsingDirective:
1732   case Decl::ClassTemplate:
1733   case Decl::FunctionTemplate:
1734   case Decl::NamespaceAlias:
1735     break;
1736   case Decl::CXXConstructor:
1737     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1738     break;
1739   case Decl::CXXDestructor:
1740     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1741     break;
1742 
1743   case Decl::StaticAssert:
1744     // Nothing to do.
1745     break;
1746 
1747   // Objective-C Decls
1748 
1749   // Forward declarations, no (immediate) code generation.
1750   case Decl::ObjCClass:
1751   case Decl::ObjCForwardProtocol:
1752   case Decl::ObjCCategory:
1753   case Decl::ObjCInterface:
1754     break;
1755 
1756   case Decl::ObjCProtocol:
1757     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1758     break;
1759 
1760   case Decl::ObjCCategoryImpl:
1761     // Categories have properties but don't support synthesize so we
1762     // can ignore them here.
1763     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1764     break;
1765 
1766   case Decl::ObjCImplementation: {
1767     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1768     EmitObjCPropertyImplementations(OMD);
1769     Runtime->GenerateClass(OMD);
1770     break;
1771   }
1772   case Decl::ObjCMethod: {
1773     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1774     // If this is not a prototype, emit the body.
1775     if (OMD->getBody())
1776       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1777     break;
1778   }
1779   case Decl::ObjCCompatibleAlias:
1780     // compatibility-alias is a directive and has no code gen.
1781     break;
1782 
1783   case Decl::LinkageSpec:
1784     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
1785     break;
1786 
1787   case Decl::FileScopeAsm: {
1788     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1789     std::string AsmString(AD->getAsmString()->getStrData(),
1790                           AD->getAsmString()->getByteLength());
1791 
1792     const std::string &S = getModule().getModuleInlineAsm();
1793     if (S.empty())
1794       getModule().setModuleInlineAsm(AsmString);
1795     else
1796       getModule().setModuleInlineAsm(S + '\n' + AsmString);
1797     break;
1798   }
1799 
1800   default:
1801     // Make sure we handled everything we should, every other kind is a
1802     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
1803     // function. Need to recode Decl::Kind to do that easily.
1804     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1805   }
1806 }
1807