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