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