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