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