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