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