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