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