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