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