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