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 "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Module.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Analysis/Verifier.h"
27 using namespace clang;
28 using namespace CodeGen;
29 
30 
31 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
32                              llvm::Module &M, const llvm::TargetData &TD,
33                              Diagnostic &diags, bool GenerateDebugInfo,
34                              bool UseMacObjCRuntime)
35   : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
36     Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
37     CFConstantStringClassRef(0) {
38 
39   if (Features.ObjC1) {
40     // TODO: Make this selectable at runtime
41     if (UseMacObjCRuntime) {
42       Runtime = CreateMacObjCRuntime(*this);
43     } else {
44       Runtime = CreateGNUObjCRuntime(*this);
45     }
46   }
47 
48   // If debug info generation is enabled, create the CGDebugInfo object.
49   DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
50 }
51 
52 CodeGenModule::~CodeGenModule() {
53   delete Runtime;
54   delete DebugInfo;
55 }
56 
57 void CodeGenModule::Release() {
58   EmitStatics();
59   if (Runtime)
60     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
61       AddGlobalCtor(ObjCInitFunction);
62   EmitCtorList(GlobalCtors, "llvm.global_ctors");
63   EmitCtorList(GlobalDtors, "llvm.global_dtors");
64   EmitAnnotations();
65   // Run the verifier to check that the generated code is consistent.
66   assert(!verifyModule(TheModule));
67 }
68 
69 /// WarnUnsupported - Print out a warning that codegen doesn't support the
70 /// specified stmt yet.
71 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
72   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
73                                                "cannot codegen this %0 yet");
74   SourceRange Range = S->getSourceRange();
75   std::string Msg = Type;
76   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
77                     &Msg, 1, &Range, 1);
78 }
79 
80 /// WarnUnsupported - Print out a warning that codegen doesn't support the
81 /// specified decl yet.
82 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
83   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
84                                                "cannot codegen this %0 yet");
85   std::string Msg = Type;
86   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
87                     &Msg, 1);
88 }
89 
90 /// setVisibility - Set the visibility for the given LLVM GlobalValue
91 /// according to the given clang AST visibility value.
92 void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
93                                   VisibilityAttr::VisibilityTypes Vis) {
94   switch (Vis) {
95   default: assert(0 && "Unknown visibility!");
96   case VisibilityAttr::DefaultVisibility:
97     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
98     break;
99   case VisibilityAttr::HiddenVisibility:
100     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
101     break;
102   case VisibilityAttr::ProtectedVisibility:
103     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
104     break;
105   }
106 }
107 
108 /// AddGlobalCtor - Add a function to the list that will be called before
109 /// main() runs.
110 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
111   // TODO: Type coercion of void()* types.
112   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
113 }
114 
115 /// AddGlobalDtor - Add a function to the list that will be called
116 /// when the module is unloaded.
117 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
118   // TODO: Type coercion of void()* types.
119   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
120 }
121 
122 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
123   // Ctor function type is void()*.
124   llvm::FunctionType* CtorFTy =
125     llvm::FunctionType::get(llvm::Type::VoidTy,
126                             std::vector<const llvm::Type*>(),
127                             false);
128   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
129 
130   // Get the type of a ctor entry, { i32, void ()* }.
131   llvm::StructType* CtorStructTy =
132     llvm::StructType::get(llvm::Type::Int32Ty,
133                           llvm::PointerType::getUnqual(CtorFTy), NULL);
134 
135   // Construct the constructor and destructor arrays.
136   std::vector<llvm::Constant*> Ctors;
137   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
138     std::vector<llvm::Constant*> S;
139     S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
140     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
141     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
142   }
143 
144   if (!Ctors.empty()) {
145     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
146     new llvm::GlobalVariable(AT, false,
147                              llvm::GlobalValue::AppendingLinkage,
148                              llvm::ConstantArray::get(AT, Ctors),
149                              GlobalName,
150                              &TheModule);
151   }
152 }
153 
154 void CodeGenModule::EmitAnnotations() {
155   if (Annotations.empty())
156     return;
157 
158   // Create a new global variable for the ConstantStruct in the Module.
159   llvm::Constant *Array =
160   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
161                                                 Annotations.size()),
162                            Annotations);
163   llvm::GlobalValue *gv =
164   new llvm::GlobalVariable(Array->getType(), false,
165                            llvm::GlobalValue::AppendingLinkage, Array,
166                            "llvm.global.annotations", &TheModule);
167   gv->setSection("llvm.metadata");
168 }
169 
170 bool hasAggregateLLVMType(QualType T) {
171   return !T->isRealType() && !T->isPointerLikeType() &&
172          !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
173 }
174 
175 void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
176                                              llvm::GlobalValue *GV) {
177   // TODO: Set up linkage and many other things.  Note, this is a simple
178   // approximation of what we really want.
179   if (FD->getStorageClass() == FunctionDecl::Static)
180     GV->setLinkage(llvm::Function::InternalLinkage);
181   else if (FD->getAttr<DLLImportAttr>())
182     GV->setLinkage(llvm::Function::DLLImportLinkage);
183   else if (FD->getAttr<DLLExportAttr>())
184     GV->setLinkage(llvm::Function::DLLExportLinkage);
185   else if (FD->getAttr<WeakAttr>() || FD->isInline())
186     GV->setLinkage(llvm::Function::WeakLinkage);
187 
188   if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
189     CodeGenModule::setVisibility(GV, attr->getVisibility());
190   // FIXME: else handle -fvisibility
191 
192   if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
193     // Prefaced with special LLVM marker to indicate that the name
194     // should not be munged.
195     GV->setName("\01" + ALA->getLabel());
196   }
197 }
198 
199 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
200                                           llvm::Function *F,
201                                           const llvm::FunctionType *FTy) {
202   unsigned FuncAttrs = 0;
203   if (FD->getAttr<NoThrowAttr>())
204     FuncAttrs |= llvm::ParamAttr::NoUnwind;
205   if (FD->getAttr<NoReturnAttr>())
206     FuncAttrs |= llvm::ParamAttr::NoReturn;
207 
208   llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
209   if (FuncAttrs)
210     ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
211   // Note that there is parallel code in CodeGenFunction::EmitCallExpr
212   bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
213   if (AggregateReturn)
214     ParamAttrList.push_back(
215         llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
216   unsigned increment = AggregateReturn ? 2 : 1;
217   const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
218   if (FTP) {
219     for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
220       QualType ParamType = FTP->getArgType(i);
221       unsigned ParamAttrs = 0;
222       if (ParamType->isRecordType())
223         ParamAttrs |= llvm::ParamAttr::ByVal;
224       if (ParamType->isSignedIntegerType() &&
225           ParamType->isPromotableIntegerType())
226         ParamAttrs |= llvm::ParamAttr::SExt;
227       if (ParamType->isUnsignedIntegerType() &&
228           ParamType->isPromotableIntegerType())
229         ParamAttrs |= llvm::ParamAttr::ZExt;
230       if (ParamAttrs)
231         ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
232                                                                ParamAttrs));
233     }
234   }
235 
236   F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
237                                         ParamAttrList.size()));
238 
239   // Set the appropriate calling convention for the Function.
240   if (FD->getAttr<FastCallAttr>())
241     F->setCallingConv(llvm::CallingConv::Fast);
242 
243   SetGlobalValueAttributes(FD, F);
244 }
245 
246 void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
247   // If this is not a prototype, emit the body.
248   if (OMD->getBody())
249     CodeGenFunction(*this).GenerateObjCMethod(OMD);
250 }
251 void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
252   llvm::SmallVector<std::string, 16> Protocols;
253   for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
254        E = PD->protocol_end(); PI != E; ++PI)
255     Protocols.push_back((*PI)->getName());
256   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
257   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
258   for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
259        E = PD->instmeth_end(); iter != E; iter++) {
260     std::string TypeStr;
261     Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
262     InstanceMethodNames.push_back(
263         GetAddrOfConstantString((*iter)->getSelector().getName()));
264     InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
265   }
266   // Collect information about class methods:
267   llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
268   llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
269   for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
270       endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
271     std::string TypeStr;
272     Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
273     ClassMethodNames.push_back(
274         GetAddrOfConstantString((*iter)->getSelector().getName()));
275     ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
276   }
277   Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
278       InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
279 }
280 
281 void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
282 
283   // Collect information about instance methods
284   llvm::SmallVector<Selector, 16> InstanceMethodSels;
285   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
286   for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
287       endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
288     InstanceMethodSels.push_back((*iter)->getSelector());
289     std::string TypeStr;
290     Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
291     InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
292   }
293 
294   // Collect information about class methods
295   llvm::SmallVector<Selector, 16> ClassMethodSels;
296   llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
297   for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
298       endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
299     ClassMethodSels.push_back((*iter)->getSelector());
300     std::string TypeStr;
301     Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
302     ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
303   }
304 
305   // Collect the names of referenced protocols
306   llvm::SmallVector<std::string, 16> Protocols;
307   const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
308   const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
309   for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
310        E = Protos.end(); I != E; ++I)
311     Protocols.push_back((*I)->getName());
312 
313   // Generate the category
314   Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
315       OCD->getName(), InstanceMethodSels, InstanceMethodTypes,
316       ClassMethodSels, ClassMethodTypes, Protocols);
317 }
318 
319 void CodeGenModule::EmitObjCClassImplementation(
320     const ObjCImplementationDecl *OID) {
321   // Get the superclass name.
322   const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
323   const char * SCName = NULL;
324   if (SCDecl) {
325     SCName = SCDecl->getName();
326   }
327 
328   // Get the class name
329   ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
330   const char * ClassName = ClassDecl->getName();
331 
332   // Get the size of instances.  For runtimes that support late-bound instances
333   // this should probably be something different (size just of instance
334   // varaibles in this class, not superclasses?).
335   int instanceSize = 0;
336   const llvm::Type *ObjTy;
337   if (!Runtime->LateBoundIVars()) {
338     ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
339     instanceSize = TheTargetData.getABITypeSize(ObjTy);
340   }
341 
342   // Collect information about instance variables.
343   llvm::SmallVector<llvm::Constant*, 16> IvarNames;
344   llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
345   llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
346   const llvm::StructLayout *Layout =
347     TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
348   ObjTy = llvm::PointerType::getUnqual(ObjTy);
349   for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
350       endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
351       // Store the name
352       IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
353       // Get the type encoding for this ivar
354       std::string TypeStr;
355       llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
356       Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
357                                      EncodingRecordTypes);
358       IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
359       // Get the offset
360       int offset =
361         (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
362       IvarOffsets.push_back(
363           llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
364   }
365 
366   // Collect information about instance methods
367   llvm::SmallVector<Selector, 16> InstanceMethodSels;
368   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
369   for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
370       endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
371     InstanceMethodSels.push_back((*iter)->getSelector());
372     std::string TypeStr;
373     Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
374     InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
375   }
376 
377   // Collect information about class methods
378   llvm::SmallVector<Selector, 16> ClassMethodSels;
379   llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
380   for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
381       endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
382     ClassMethodSels.push_back((*iter)->getSelector());
383     std::string TypeStr;
384     Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
385     ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
386   }
387   // Collect the names of referenced protocols
388   llvm::SmallVector<std::string, 16> Protocols;
389   const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
390   for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
391        E = Protos.end(); I != E; ++I)
392     Protocols.push_back((*I)->getName());
393 
394   // Generate the category
395   Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
396                          IvarOffsets, InstanceMethodSels, InstanceMethodTypes,
397                          ClassMethodSels, ClassMethodTypes, Protocols);
398 }
399 
400 void CodeGenModule::EmitStatics() {
401   // Emit code for each used static decl encountered.  Since a previously unused
402   // static decl may become used during the generation of code for a static
403   // function, iterate until no changes are made.
404   bool Changed;
405   do {
406     Changed = false;
407     for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
408       const ValueDecl *D = StaticDecls[i];
409 
410       // Check if we have used a decl with the same name
411       // FIXME: The AST should have some sort of aggregate decls or
412       // global symbol map.
413       if (!GlobalDeclMap.count(D->getName()))
414         continue;
415 
416       // Emit the definition.
417       EmitGlobalDefinition(D);
418 
419       // Erase the used decl from the list.
420       StaticDecls[i] = StaticDecls.back();
421       StaticDecls.pop_back();
422       --i;
423       --e;
424 
425       // Remember that we made a change.
426       Changed = true;
427     }
428   } while (Changed);
429 }
430 
431 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
432 /// annotation information for a given GlobalValue.  The annotation struct is
433 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
434 /// GlobalValue being annotated.  The second field is the constant string
435 /// created from the AnnotateAttr's annotation.  The third field is a constant
436 /// string containing the name of the translation unit.  The fourth field is
437 /// the line number in the file of the annotated value declaration.
438 ///
439 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
440 ///        appears to.
441 ///
442 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
443                                                 const AnnotateAttr *AA,
444                                                 unsigned LineNo) {
445   llvm::Module *M = &getModule();
446 
447   // get [N x i8] constants for the annotation string, and the filename string
448   // which are the 2nd and 3rd elements of the global annotation structure.
449   const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
450   llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
451   llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
452                                                   true);
453 
454   // Get the two global values corresponding to the ConstantArrays we just
455   // created to hold the bytes of the strings.
456   llvm::GlobalValue *annoGV =
457   new llvm::GlobalVariable(anno->getType(), false,
458                            llvm::GlobalValue::InternalLinkage, anno,
459                            GV->getName() + ".str", M);
460   // translation unit name string, emitted into the llvm.metadata section.
461   llvm::GlobalValue *unitGV =
462   new llvm::GlobalVariable(unit->getType(), false,
463                            llvm::GlobalValue::InternalLinkage, unit, ".str", M);
464 
465   // Create the ConstantStruct that is the global annotion.
466   llvm::Constant *Fields[4] = {
467     llvm::ConstantExpr::getBitCast(GV, SBP),
468     llvm::ConstantExpr::getBitCast(annoGV, SBP),
469     llvm::ConstantExpr::getBitCast(unitGV, SBP),
470     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
471   };
472   return llvm::ConstantStruct::get(Fields, 4, false);
473 }
474 
475 void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
476   bool isDef, isStatic;
477 
478   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
479     isDef = (FD->isThisDeclarationADefinition() ||
480              FD->getAttr<AliasAttr>());
481     isStatic = FD->getStorageClass() == FunctionDecl::Static;
482   } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
483     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
484 
485     isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
486     isStatic = VD->getStorageClass() == VarDecl::Static;
487   } else {
488     assert(0 && "Invalid argument to EmitGlobal");
489     return;
490   }
491 
492   // Forward declarations are emitted lazily on first use.
493   if (!isDef)
494     return;
495 
496   // If the global is a static, defer code generation until later so
497   // we can easily omit unused statics.
498   if (isStatic) {
499     StaticDecls.push_back(Global);
500     return;
501   }
502 
503   // Otherwise emit the definition.
504   EmitGlobalDefinition(Global);
505 }
506 
507 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
508   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
509     EmitGlobalFunctionDefinition(FD);
510   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
511     EmitGlobalVarDefinition(VD);
512   } else {
513     assert(0 && "Invalid argument to EmitGlobalDefinition()");
514   }
515 }
516 
517  llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
518   assert(D->hasGlobalStorage() && "Not a global variable");
519 
520   QualType ASTTy = D->getType();
521   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
522   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
523 
524   // Lookup the entry, lazily creating it if necessary.
525   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
526   if (!Entry)
527     Entry = new llvm::GlobalVariable(Ty, false,
528                                      llvm::GlobalValue::ExternalLinkage,
529                                      0, D->getName(), &getModule(), 0,
530                                      ASTTy.getAddressSpace());
531 
532   // Make sure the result is of the correct type.
533   return llvm::ConstantExpr::getBitCast(Entry, PTy);
534 }
535 
536 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
537   llvm::Constant *Init = 0;
538   QualType ASTTy = D->getType();
539   const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
540 
541   if (D->getInit() == 0) {
542     // This is a tentative definition; tentative definitions are
543     // implicitly initialized with { 0 }
544     const llvm::Type* InitTy;
545     if (ASTTy->isIncompleteArrayType()) {
546       // An incomplete array is normally [ TYPE x 0 ], but we need
547       // to fix it to [ TYPE x 1 ].
548       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
549       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
550     } else {
551       InitTy = VarTy;
552     }
553     Init = llvm::Constant::getNullValue(InitTy);
554   } else {
555     Init = EmitConstantExpr(D->getInit());
556   }
557   const llvm::Type* InitType = Init->getType();
558 
559   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
560   llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
561 
562   if (!GV) {
563     GV = new llvm::GlobalVariable(InitType, false,
564                                   llvm::GlobalValue::ExternalLinkage,
565                                   0, D->getName(), &getModule(), 0,
566                                   ASTTy.getAddressSpace());
567   } else if (GV->getType() !=
568              llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
569     // We have a definition after a prototype with the wrong type.
570     // We must make a new GlobalVariable* and update everything that used OldGV
571     // (a declaration or tentative definition) with the new GlobalVariable*
572     // (which will be a definition).
573     //
574     // This happens if there is a prototype for a global (e.g. "extern int x[];")
575     // and then a definition of a different type (e.g. "int x[10];"). This also
576     // happens when an initializer has a different type from the type of the
577     // global (this happens with unions).
578     //
579     // FIXME: This also ends up happening if there's a definition followed by
580     // a tentative definition!  (Although Sema rejects that construct
581     // at the moment.)
582 
583     // Save the old global
584     llvm::GlobalVariable *OldGV = GV;
585 
586     // Make a new global with the correct type
587     GV = new llvm::GlobalVariable(InitType, false,
588                                   llvm::GlobalValue::ExternalLinkage,
589                                   0, D->getName(), &getModule(), 0,
590                                   ASTTy.getAddressSpace());
591     // Steal the name of the old global
592     GV->takeName(OldGV);
593 
594     // Replace all uses of the old global with the new global
595     llvm::Constant *NewPtrForOldDecl =
596         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
597     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
598 
599     // Erase the old global, since it is no longer used.
600     OldGV->eraseFromParent();
601   }
602 
603   Entry = GV;
604 
605   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
606     SourceManager &SM = Context.getSourceManager();
607     AddAnnotation(EmitAnnotateAttr(GV, AA,
608                                    SM.getLogicalLineNumber(D->getLocation())));
609   }
610 
611   GV->setInitializer(Init);
612 
613   // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
614   unsigned Align;
615   if (const IncompleteArrayType* IAT =
616         Context.getAsIncompleteArrayType(D->getType()))
617     Align = Context.getTypeAlign(IAT->getElementType());
618   else
619     Align = Context.getTypeAlign(D->getType());
620   if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
621     Align = std::max(Align, AA->getAlignment());
622   }
623   GV->setAlignment(Align / 8);
624 
625   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
626     setVisibility(GV, attr->getVisibility());
627   // FIXME: else handle -fvisibility
628 
629   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
630     // Prefaced with special LLVM marker to indicate that the name
631     // should not be munged.
632     GV->setName("\01" + ALA->getLabel());
633   }
634 
635   // Set the llvm linkage type as appropriate.
636   if (D->getStorageClass() == VarDecl::Static)
637     GV->setLinkage(llvm::Function::InternalLinkage);
638   else if (D->getAttr<DLLImportAttr>())
639     GV->setLinkage(llvm::Function::DLLImportLinkage);
640   else if (D->getAttr<DLLExportAttr>())
641     GV->setLinkage(llvm::Function::DLLExportLinkage);
642   else if (D->getAttr<WeakAttr>())
643     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
644   else {
645     // FIXME: This isn't right.  This should handle common linkage and other
646     // stuff.
647     switch (D->getStorageClass()) {
648     case VarDecl::Static: assert(0 && "This case handled above");
649     case VarDecl::Auto:
650     case VarDecl::Register:
651       assert(0 && "Can't have auto or register globals");
652     case VarDecl::None:
653       if (!D->getInit())
654         GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
655       break;
656     case VarDecl::Extern:
657     case VarDecl::PrivateExtern:
658       // todo: common
659       break;
660     }
661   }
662 
663   // Emit global variable debug information.
664   CGDebugInfo *DI = getDebugInfo();
665   if(DI) {
666     if(D->getLocation().isValid())
667       DI->setLocation(D->getLocation());
668     DI->EmitGlobalVariable(GV, D);
669   }
670 }
671 
672 llvm::GlobalValue *
673 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
674   // FIXME: param attributes for sext/zext etc.
675   if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
676     assert(!D->getBody() && "Unexpected alias attr on function with body.");
677 
678     const std::string& aliaseeName = AA->getAliasee();
679     llvm::Function *aliasee = getModule().getFunction(aliaseeName);
680     llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
681                                               llvm::Function::ExternalLinkage,
682                                                      D->getName(),
683                                                      aliasee,
684                                                      &getModule());
685     SetGlobalValueAttributes(D, alias);
686     return alias;
687   } else {
688     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
689     const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
690     llvm::Function *F = llvm::Function::Create(FTy,
691                                                llvm::Function::ExternalLinkage,
692                                                D->getName(), &getModule());
693 
694     SetFunctionAttributes(D, F, FTy);
695     return F;
696   }
697 }
698 
699 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
700   QualType ASTTy = D->getType();
701   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
702   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
703 
704   // Lookup the entry, lazily creating it if necessary.
705   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
706   if (!Entry)
707     Entry = EmitForwardFunctionDefinition(D);
708 
709   return llvm::ConstantExpr::getBitCast(Entry, PTy);
710 }
711 
712 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
713   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
714   if (!Entry) {
715     Entry = EmitForwardFunctionDefinition(D);
716   } else {
717     // If the types mismatch then we have to rewrite the definition.
718     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
719     if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
720       // Otherwise, we have a definition after a prototype with the wrong type.
721       // F is the Function* for the one with the wrong type, we must make a new
722       // Function* and update everything that used F (a declaration) with the new
723       // Function* (which will be a definition).
724       //
725       // This happens if there is a prototype for a function (e.g. "int f()") and
726       // then a definition of a different type (e.g. "int f(int x)").  Start by
727       // making a new function of the correct type, RAUW, then steal the name.
728       llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
729       NewFn->takeName(Entry);
730 
731       // Replace uses of F with the Function we will endow with a body.
732       llvm::Constant *NewPtrForOldDecl =
733         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
734       Entry->replaceAllUsesWith(NewPtrForOldDecl);
735 
736       // Ok, delete the old function now, which is dead.
737       // FIXME: Add GlobalValue->eraseFromParent().
738       assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
739       if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
740         F->eraseFromParent();
741       } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
742         GA->eraseFromParent();
743       } else {
744         assert(0 && "Invalid global variable type.");
745       }
746 
747       Entry = NewFn;
748     }
749   }
750 
751   if (D->getAttr<AliasAttr>()) {
752     ;
753   } else {
754     llvm::Function *Fn = cast<llvm::Function>(Entry);
755     CodeGenFunction(*this).GenerateCode(D, Fn);
756 
757     // Set attributes specific to definition.
758     // FIXME: This needs to be cleaned up by clearly emitting the
759     // declaration / definition at separate times.
760     if (!Features.Exceptions)
761       Fn->addParamAttr(0, llvm::ParamAttr::NoUnwind);
762 
763     if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
764       AddGlobalCtor(Fn, CA->getPriority());
765     } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
766       AddGlobalDtor(Fn, DA->getPriority());
767     }
768   }
769 }
770 
771 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
772   // Make sure that this type is translated.
773   Types.UpdateCompletedType(TD);
774 }
775 
776 
777 /// getBuiltinLibFunction
778 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
779   if (BuiltinID > BuiltinFunctions.size())
780     BuiltinFunctions.resize(BuiltinID);
781 
782   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
783   // a slot for it.
784   assert(BuiltinID && "Invalid Builtin ID");
785   llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
786   if (FunctionSlot)
787     return FunctionSlot;
788 
789   assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
790 
791   // Get the name, skip over the __builtin_ prefix.
792   const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
793 
794   // Get the type for the builtin.
795   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
796   const llvm::FunctionType *Ty =
797     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
798 
799   // FIXME: This has a serious problem with code like this:
800   //  void abs() {}
801   //    ... __builtin_abs(x);
802   // The two versions of abs will collide.  The fix is for the builtin to win,
803   // and for the existing one to be turned into a constantexpr cast of the
804   // builtin.  In the case where the existing one is a static function, it
805   // should just be renamed.
806   if (llvm::Function *Existing = getModule().getFunction(Name)) {
807     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
808       return FunctionSlot = Existing;
809     assert(Existing == 0 && "FIXME: Name collision");
810   }
811 
812   // FIXME: param attributes for sext/zext etc.
813   return FunctionSlot =
814     llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
815                            &getModule());
816 }
817 
818 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
819                                             unsigned NumTys) {
820   return llvm::Intrinsic::getDeclaration(&getModule(),
821                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
822 }
823 
824 llvm::Function *CodeGenModule::getMemCpyFn() {
825   if (MemCpyFn) return MemCpyFn;
826   llvm::Intrinsic::ID IID;
827   switch (Context.Target.getPointerWidth(0)) {
828   default: assert(0 && "Unknown ptr width");
829   case 32: IID = llvm::Intrinsic::memcpy_i32; break;
830   case 64: IID = llvm::Intrinsic::memcpy_i64; break;
831   }
832   return MemCpyFn = getIntrinsic(IID);
833 }
834 
835 llvm::Function *CodeGenModule::getMemMoveFn() {
836   if (MemMoveFn) return MemMoveFn;
837   llvm::Intrinsic::ID IID;
838   switch (Context.Target.getPointerWidth(0)) {
839   default: assert(0 && "Unknown ptr width");
840   case 32: IID = llvm::Intrinsic::memmove_i32; break;
841   case 64: IID = llvm::Intrinsic::memmove_i64; break;
842   }
843   return MemMoveFn = getIntrinsic(IID);
844 }
845 
846 llvm::Function *CodeGenModule::getMemSetFn() {
847   if (MemSetFn) return MemSetFn;
848   llvm::Intrinsic::ID IID;
849   switch (Context.Target.getPointerWidth(0)) {
850   default: assert(0 && "Unknown ptr width");
851   case 32: IID = llvm::Intrinsic::memset_i32; break;
852   case 64: IID = llvm::Intrinsic::memset_i64; break;
853   }
854   return MemSetFn = getIntrinsic(IID);
855 }
856 
857 // FIXME: This needs moving into an Apple Objective-C runtime class
858 llvm::Constant *CodeGenModule::
859 GetAddrOfConstantCFString(const std::string &str) {
860   llvm::StringMapEntry<llvm::Constant *> &Entry =
861     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
862 
863   if (Entry.getValue())
864     return Entry.getValue();
865 
866   std::vector<llvm::Constant*> Fields;
867 
868   if (!CFConstantStringClassRef) {
869     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
870     Ty = llvm::ArrayType::get(Ty, 0);
871 
872     CFConstantStringClassRef =
873       new llvm::GlobalVariable(Ty, false,
874                                llvm::GlobalVariable::ExternalLinkage, 0,
875                                "__CFConstantStringClassReference",
876                                &getModule());
877   }
878 
879   // Class pointer.
880   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
881   llvm::Constant *Zeros[] = { Zero, Zero };
882   llvm::Constant *C =
883     llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
884   Fields.push_back(C);
885 
886   // Flags.
887   const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
888   Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
889 
890   // String pointer.
891   C = llvm::ConstantArray::get(str);
892   C = new llvm::GlobalVariable(C->getType(), true,
893                                llvm::GlobalValue::InternalLinkage,
894                                C, ".str", &getModule());
895 
896   C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
897   Fields.push_back(C);
898 
899   // String length.
900   Ty = getTypes().ConvertType(getContext().LongTy);
901   Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
902 
903   // The struct.
904   Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
905   C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
906   llvm::GlobalVariable *GV =
907     new llvm::GlobalVariable(C->getType(), true,
908                              llvm::GlobalVariable::InternalLinkage,
909                              C, "", &getModule());
910   GV->setSection("__DATA,__cfstring");
911   Entry.setValue(GV);
912   return GV;
913 }
914 
915 /// getStringForStringLiteral - Return the appropriate bytes for a
916 /// string literal, properly padded to match the literal type.
917 std::string CodeGenModule::getStringForStringLiteral(const StringLiteral *E) {
918   assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
919   const char *StrData = E->getStrData();
920   unsigned Len = E->getByteLength();
921 
922   const ConstantArrayType *CAT =
923     getContext().getAsConstantArrayType(E->getType());
924   assert(CAT && "String isn't pointer or array!");
925 
926   // Resize the string to the right size
927   // FIXME: What about wchar_t strings?
928   std::string Str(StrData, StrData+Len);
929   uint64_t RealLen = CAT->getSize().getZExtValue();
930   Str.resize(RealLen, '\0');
931 
932   return Str;
933 }
934 
935 /// GenerateWritableString -- Creates storage for a string literal.
936 static llvm::Constant *GenerateStringLiteral(const std::string &str,
937                                              bool constant,
938                                              CodeGenModule &CGM) {
939   // Create Constant for this string literal
940   llvm::Constant *C = llvm::ConstantArray::get(str);
941 
942   // Create a global variable for this string
943   C = new llvm::GlobalVariable(C->getType(), constant,
944                                llvm::GlobalValue::InternalLinkage,
945                                C, ".str", &CGM.getModule());
946   return C;
947 }
948 
949 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
950 /// array containing the literal.  The result is pointer to array type.
951 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
952   // Don't share any string literals if writable-strings is turned on.
953   if (Features.WritableStrings)
954     return GenerateStringLiteral(str, false, *this);
955 
956   llvm::StringMapEntry<llvm::Constant *> &Entry =
957   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
958 
959   if (Entry.getValue())
960       return Entry.getValue();
961 
962   // Create a global variable for this.
963   llvm::Constant *C = GenerateStringLiteral(str, true, *this);
964   Entry.setValue(C);
965   return C;
966 }
967