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