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