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