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