blob: d17a6c88e41a1ba9c7f668ea479fd5c395a7b63c [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000019#include "clang/Basic/Diagnostic.h"
Chris Lattnerdb6be562007-11-28 05:34:05 +000020#include "clang/Basic/LangOptions.h"
Nate Begeman8a704172008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000023#include "llvm/CallingConv.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000029#include "llvm/Analysis/Verifier.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000030#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000031using namespace clang;
32using namespace CodeGen;
33
34
Chris Lattnerdb6be562007-11-28 05:34:05 +000035CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000036 llvm::Module &M, const llvm::TargetData &TD,
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000037 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000038 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Eli Friedman8f08a252008-05-26 12:59:39 +000039 Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
40 CFConstantStringClassRef(0) {
Chris Lattnercbfb5512008-03-01 08:45:05 +000041 //TODO: Make this selectable at runtime
Chris Lattner547907c2008-06-26 04:19:03 +000042 Runtime = CreateObjCRuntime(*this);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000043
44 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000045 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000046}
47
48CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000049 delete Runtime;
50 delete DebugInfo;
51}
52
53void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000054 EmitStatics();
Chris Lattnerb326b172008-03-30 23:03:07 +000055 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000056 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000057 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000058 EmitCtorList(GlobalCtors, "llvm.global_ctors");
59 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000060 EmitAnnotations();
Chris Lattnerb033c4a2008-04-30 16:05:42 +000061 // Run the verifier to check that the generated code is consistent.
62 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000063}
Chris Lattner4b009652007-07-25 00:24:17 +000064
Chris Lattnercf9c9d02007-12-02 07:19:18 +000065/// WarnUnsupported - Print out a warning that codegen doesn't support the
66/// specified stmt yet.
67void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
68 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
69 "cannot codegen this %0 yet");
70 SourceRange Range = S->getSourceRange();
71 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000072 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000073 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000074}
Chris Lattner0e4755d2007-12-02 06:27:33 +000075
Chris Lattner806a5f52008-01-12 07:05:38 +000076/// WarnUnsupported - Print out a warning that codegen doesn't support the
77/// specified decl yet.
78void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
79 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
80 "cannot codegen this %0 yet");
81 std::string Msg = Type;
82 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
83 &Msg, 1);
84}
85
Dan Gohman4751a3a2008-05-22 00:50:06 +000086/// setVisibility - Set the visibility for the given LLVM GlobalValue
87/// according to the given clang AST visibility value.
88void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
89 VisibilityAttr::VisibilityTypes Vis) {
90 switch (Vis) {
91 default: assert(0 && "Unknown visibility!");
92 case VisibilityAttr::DefaultVisibility:
93 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
94 break;
95 case VisibilityAttr::HiddenVisibility:
96 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
97 break;
98 case VisibilityAttr::ProtectedVisibility:
99 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
100 break;
101 }
102}
103
Chris Lattner753d2592008-03-14 17:18:18 +0000104/// AddGlobalCtor - Add a function to the list that will be called before
105/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000106void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000107 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000108 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000109}
110
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000111/// AddGlobalDtor - Add a function to the list that will be called
112/// when the module is unloaded.
113void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
114 // TODO: Type coercion of void()* types.
115 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
116}
117
118void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
119 // Ctor function type is void()*.
120 llvm::FunctionType* CtorFTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy,
122 std::vector<const llvm::Type*>(),
123 false);
124 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
125
126 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000127 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000128 llvm::StructType::get(llvm::Type::Int32Ty,
129 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000130
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000131 // Construct the constructor and destructor arrays.
132 std::vector<llvm::Constant*> Ctors;
133 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
134 std::vector<llvm::Constant*> S;
135 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
136 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
137 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000138 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000139
140 if (!Ctors.empty()) {
141 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
142 new llvm::GlobalVariable(AT, false,
143 llvm::GlobalValue::AppendingLinkage,
144 llvm::ConstantArray::get(AT, Ctors),
145 GlobalName,
146 &TheModule);
147 }
Chris Lattner753d2592008-03-14 17:18:18 +0000148}
149
Nate Begeman52da5c72008-04-18 23:43:57 +0000150void CodeGenModule::EmitAnnotations() {
151 if (Annotations.empty())
152 return;
153
154 // Create a new global variable for the ConstantStruct in the Module.
155 llvm::Constant *Array =
156 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
157 Annotations.size()),
158 Annotations);
159 llvm::GlobalValue *gv =
160 new llvm::GlobalVariable(Array->getType(), false,
161 llvm::GlobalValue::AppendingLinkage, Array,
162 "llvm.global.annotations", &TheModule);
163 gv->setSection("llvm.metadata");
164}
165
Eli Friedman9be42212008-06-01 15:54:49 +0000166bool hasAggregateLLVMType(QualType T) {
167 return !T->isRealType() && !T->isPointerLikeType() &&
168 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
169}
170
Nuno Lopes78534382008-06-08 15:45:52 +0000171void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
172 llvm::GlobalValue *GV) {
173 // TODO: Set up linkage and many other things. Note, this is a simple
174 // approximation of what we really want.
175 if (FD->getStorageClass() == FunctionDecl::Static)
176 GV->setLinkage(llvm::Function::InternalLinkage);
177 else if (FD->getAttr<DLLImportAttr>())
178 GV->setLinkage(llvm::Function::DLLImportLinkage);
179 else if (FD->getAttr<DLLExportAttr>())
180 GV->setLinkage(llvm::Function::DLLExportLinkage);
181 else if (FD->getAttr<WeakAttr>() || FD->isInline())
182 GV->setLinkage(llvm::Function::WeakLinkage);
183
184 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
185 CodeGenModule::setVisibility(GV, attr->getVisibility());
186 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000187
188 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
189 // Prefaced with special LLVM marker to indicate that the name
190 // should not be munged.
191 GV->setName("\01" + ALA->getLabel());
192 }
Nuno Lopes78534382008-06-08 15:45:52 +0000193}
194
Eli Friedman9be42212008-06-01 15:54:49 +0000195void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
196 llvm::Function *F,
197 const llvm::FunctionType *FTy) {
198 unsigned FuncAttrs = 0;
199 if (FD->getAttr<NoThrowAttr>())
200 FuncAttrs |= llvm::ParamAttr::NoUnwind;
201 if (FD->getAttr<NoReturnAttr>())
202 FuncAttrs |= llvm::ParamAttr::NoReturn;
203
204 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
205 if (FuncAttrs)
206 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
207 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
208 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
209 if (AggregateReturn)
210 ParamAttrList.push_back(
211 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
212 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000213 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
214 if (FTP) {
215 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
216 QualType ParamType = FTP->getArgType(i);
217 unsigned ParamAttrs = 0;
218 if (ParamType->isRecordType())
219 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattner578279d2008-06-26 05:08:00 +0000220 if (ParamType->isSignedIntegerType() &&
221 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000222 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattner578279d2008-06-26 05:08:00 +0000223 if (ParamType->isUnsignedIntegerType() &&
224 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000225 ParamAttrs |= llvm::ParamAttr::ZExt;
226 if (ParamAttrs)
227 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
228 ParamAttrs));
229 }
Eli Friedman9be42212008-06-01 15:54:49 +0000230 }
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000231
Eli Friedman9be42212008-06-01 15:54:49 +0000232 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
233 ParamAttrList.size()));
234
235 // Set the appropriate calling convention for the Function.
236 if (FD->getAttr<FastCallAttr>())
237 F->setCallingConv(llvm::CallingConv::Fast);
238
Nuno Lopes78534382008-06-08 15:45:52 +0000239 SetGlobalValueAttributes(FD, F);
Eli Friedman9be42212008-06-01 15:54:49 +0000240}
241
Chris Lattnerb326b172008-03-30 23:03:07 +0000242void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
243 // If this is not a prototype, emit the body.
244 if (OMD->getBody())
245 CodeGenFunction(*this).GenerateObjCMethod(OMD);
246}
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000247void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
248 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner0be08822008-07-21 21:32:27 +0000249 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
250 E = PD->protocol_end(); PI != E; ++PI)
251 Protocols.push_back((*PI)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000252 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
253 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
254 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
Chris Lattner0be08822008-07-21 21:32:27 +0000255 E = PD->instmeth_end(); iter != E; iter++) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000256 std::string TypeStr;
Chris Lattner0be08822008-07-21 21:32:27 +0000257 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000258 InstanceMethodNames.push_back(
259 GetAddrOfConstantString((*iter)->getSelector().getName()));
260 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
261 }
262 // Collect information about class methods:
263 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
264 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
265 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
266 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
267 std::string TypeStr;
268 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
269 ClassMethodNames.push_back(
270 GetAddrOfConstantString((*iter)->getSelector().getName()));
271 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
272 }
273 Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
274 InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
275}
276
277void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
278
279 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000280 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000281 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
282 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
283 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000284 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000285 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000286 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000287 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
288 }
289
290 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000291 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000292 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
293 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
294 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000295 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000296 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000297 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000298 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
299 }
300
301 // Collect the names of referenced protocols
302 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000303 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
304 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
305 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
306 E = Protos.end(); I != E; ++I)
307 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000308
309 // Generate the category
310 Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
Chris Lattner578279d2008-06-26 05:08:00 +0000311 OCD->getName(), InstanceMethodSels, InstanceMethodTypes,
312 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000313}
314
315void CodeGenModule::EmitObjCClassImplementation(
316 const ObjCImplementationDecl *OID) {
317 // Get the superclass name.
318 const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
319 const char * SCName = NULL;
320 if (SCDecl) {
321 SCName = SCDecl->getName();
322 }
323
324 // Get the class name
325 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
326 const char * ClassName = ClassDecl->getName();
327
328 // Get the size of instances. For runtimes that support late-bound instances
329 // this should probably be something different (size just of instance
330 // varaibles in this class, not superclasses?).
331 int instanceSize = 0;
332 const llvm::Type *ObjTy;
333 if (!Runtime->LateBoundIVars()) {
334 ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
335 instanceSize = TheTargetData.getABITypeSize(ObjTy);
336 }
337
338 // Collect information about instance variables.
339 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
340 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
341 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
342 const llvm::StructLayout *Layout =
343 TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
344 ObjTy = llvm::PointerType::getUnqual(ObjTy);
345 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
346 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
347 // Store the name
348 IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
349 // Get the type encoding for this ivar
350 std::string TypeStr;
351 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
352 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
353 EncodingRecordTypes);
354 IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
355 // Get the offset
356 int offset =
357 (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
358 IvarOffsets.push_back(
359 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
360 }
361
362 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000363 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000364 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
365 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
366 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000367 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000368 std::string TypeStr;
369 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000370 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
371 }
372
373 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000374 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000375 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
376 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
377 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000378 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000379 std::string TypeStr;
380 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000381 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
382 }
383 // Collect the names of referenced protocols
384 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000385 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
386 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
387 E = Protos.end(); I != E; ++I)
388 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000389
390 // Generate the category
391 Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
Chris Lattner578279d2008-06-26 05:08:00 +0000392 IvarOffsets, InstanceMethodSels, InstanceMethodTypes,
393 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000394}
395
Nate Begemanad320b62008-04-20 06:29:50 +0000396void CodeGenModule::EmitStatics() {
397 // Emit code for each used static decl encountered. Since a previously unused
398 // static decl may become used during the generation of code for a static
399 // function, iterate until no changes are made.
400 bool Changed;
401 do {
402 Changed = false;
403 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000404 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000405
406 // Check if we have used a decl with the same name
407 // FIXME: The AST should have some sort of aggregate decls or
408 // global symbol map.
Daniel Dunbarced89142008-08-06 00:03:29 +0000409 if (!GlobalDeclMap.count(D->getName()))
410 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000411
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000412 // Emit the definition.
413 EmitGlobalDefinition(D);
414
Nate Begemanad320b62008-04-20 06:29:50 +0000415 // Erase the used decl from the list.
416 StaticDecls[i] = StaticDecls.back();
417 StaticDecls.pop_back();
418 --i;
419 --e;
420
421 // Remember that we made a change.
422 Changed = true;
423 }
424 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000425}
426
Nate Begeman8a704172008-04-19 04:17:09 +0000427/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
428/// annotation information for a given GlobalValue. The annotation struct is
429/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000430/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000431/// created from the AnnotateAttr's annotation. The third field is a constant
432/// string containing the name of the translation unit. The fourth field is
433/// the line number in the file of the annotated value declaration.
434///
435/// FIXME: this does not unique the annotation string constants, as llvm-gcc
436/// appears to.
437///
438llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
439 const AnnotateAttr *AA,
440 unsigned LineNo) {
441 llvm::Module *M = &getModule();
442
443 // get [N x i8] constants for the annotation string, and the filename string
444 // which are the 2nd and 3rd elements of the global annotation structure.
445 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
446 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
447 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
448 true);
449
450 // Get the two global values corresponding to the ConstantArrays we just
451 // created to hold the bytes of the strings.
452 llvm::GlobalValue *annoGV =
453 new llvm::GlobalVariable(anno->getType(), false,
454 llvm::GlobalValue::InternalLinkage, anno,
455 GV->getName() + ".str", M);
456 // translation unit name string, emitted into the llvm.metadata section.
457 llvm::GlobalValue *unitGV =
458 new llvm::GlobalVariable(unit->getType(), false,
459 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
460
461 // Create the ConstantStruct that is the global annotion.
462 llvm::Constant *Fields[4] = {
463 llvm::ConstantExpr::getBitCast(GV, SBP),
464 llvm::ConstantExpr::getBitCast(annoGV, SBP),
465 llvm::ConstantExpr::getBitCast(unitGV, SBP),
466 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
467 };
468 return llvm::ConstantStruct::get(Fields, 4, false);
469}
470
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000471void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
472 bool isDef, isStatic;
473
474 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
475 isDef = (FD->isThisDeclarationADefinition() ||
476 FD->getAttr<AliasAttr>());
477 isStatic = FD->getStorageClass() == FunctionDecl::Static;
478 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
479 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
480
481 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
482 isStatic = VD->getStorageClass() == VarDecl::Static;
483 } else {
484 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000485 return;
486 }
487
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000488 // Forward declarations are emitted lazily on first use.
489 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000490 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000491
492 // If the global is a static, defer code generation until later so
493 // we can easily omit unused statics.
494 if (isStatic) {
495 StaticDecls.push_back(Global);
496 return;
497 }
498
499 // Otherwise emit the definition.
500 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000501}
502
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000503void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
504 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
505 EmitGlobalFunctionDefinition(FD);
506 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
507 EmitGlobalVarDefinition(VD);
508 } else {
509 assert(0 && "Invalid argument to EmitGlobalDefinition()");
510 }
511}
512
Daniel Dunbar2188c532008-07-30 16:32:24 +0000513 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000514 assert(D->hasGlobalStorage() && "Not a global variable");
515
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000516 QualType ASTTy = D->getType();
517 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000518 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000519
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000520 // Lookup the entry, lazily creating it if necessary.
521 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
522 if (!Entry)
523 Entry = new llvm::GlobalVariable(Ty, false,
524 llvm::GlobalValue::ExternalLinkage,
525 0, D->getName(), &getModule(), 0,
526 ASTTy.getAddressSpace());
527
Daniel Dunbar2188c532008-07-30 16:32:24 +0000528 // Make sure the result is of the correct type.
529 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000530}
531
532void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000533 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000534 QualType ASTTy = D->getType();
535 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000536
Chris Lattner4b009652007-07-25 00:24:17 +0000537 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000538 // This is a tentative definition; tentative definitions are
539 // implicitly initialized with { 0 }
540 const llvm::Type* InitTy;
541 if (ASTTy->isIncompleteArrayType()) {
542 // An incomplete array is normally [ TYPE x 0 ], but we need
543 // to fix it to [ TYPE x 1 ].
544 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
545 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
546 } else {
547 InitTy = VarTy;
548 }
549 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000550 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000551 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000552 }
553 const llvm::Type* InitType = Init->getType();
554
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000555 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
556 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
557
Eli Friedman43a0ce82008-05-30 19:50:47 +0000558 if (!GV) {
559 GV = new llvm::GlobalVariable(InitType, false,
560 llvm::GlobalValue::ExternalLinkage,
561 0, D->getName(), &getModule(), 0,
562 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000563 } else if (GV->getType() !=
564 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000565 // We have a definition after a prototype with the wrong type.
566 // We must make a new GlobalVariable* and update everything that used OldGV
567 // (a declaration or tentative definition) with the new GlobalVariable*
568 // (which will be a definition).
569 //
570 // This happens if there is a prototype for a global (e.g. "extern int x[];")
571 // and then a definition of a different type (e.g. "int x[10];"). This also
572 // happens when an initializer has a different type from the type of the
573 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000574 //
575 // FIXME: This also ends up happening if there's a definition followed by
576 // a tentative definition! (Although Sema rejects that construct
577 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000578
579 // Save the old global
580 llvm::GlobalVariable *OldGV = GV;
581
582 // Make a new global with the correct type
583 GV = new llvm::GlobalVariable(InitType, false,
584 llvm::GlobalValue::ExternalLinkage,
585 0, D->getName(), &getModule(), 0,
586 ASTTy.getAddressSpace());
587 // Steal the name of the old global
588 GV->takeName(OldGV);
589
590 // Replace all uses of the old global with the new global
591 llvm::Constant *NewPtrForOldDecl =
592 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
593 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000594
595 // Erase the old global, since it is no longer used.
596 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000597 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000598
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000599 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000600
Nate Begeman8a704172008-04-19 04:17:09 +0000601 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
602 SourceManager &SM = Context.getSourceManager();
603 AddAnnotation(EmitAnnotateAttr(GV, AA,
604 SM.getLogicalLineNumber(D->getLocation())));
605 }
606
Chris Lattner4b009652007-07-25 00:24:17 +0000607 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000608
Eli Friedman7008e9a2008-05-30 20:39:54 +0000609 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
610 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000611 if (const IncompleteArrayType* IAT =
612 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000613 Align = Context.getTypeAlign(IAT->getElementType());
614 else
615 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000616 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
617 Align = std::max(Align, AA->getAlignment());
618 }
619 GV->setAlignment(Align / 8);
620
Chris Lattner402b3372008-03-03 03:28:21 +0000621 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000622 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000623 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000624
625 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
626 // Prefaced with special LLVM marker to indicate that the name
627 // should not be munged.
628 GV->setName("\01" + ALA->getLabel());
629 }
Chris Lattner4b009652007-07-25 00:24:17 +0000630
631 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000632 if (D->getStorageClass() == VarDecl::Static)
633 GV->setLinkage(llvm::Function::InternalLinkage);
634 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000635 GV->setLinkage(llvm::Function::DLLImportLinkage);
636 else if (D->getAttr<DLLExportAttr>())
637 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000638 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000639 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000640 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000641 // FIXME: This isn't right. This should handle common linkage and other
642 // stuff.
643 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000644 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000645 case VarDecl::Auto:
646 case VarDecl::Register:
647 assert(0 && "Can't have auto or register globals");
648 case VarDecl::None:
649 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000650 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000651 break;
652 case VarDecl::Extern:
653 case VarDecl::PrivateExtern:
654 // todo: common
655 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000656 }
Chris Lattner4b009652007-07-25 00:24:17 +0000657 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000658
659 // Emit global variable debug information.
660 CGDebugInfo *DI = getDebugInfo();
661 if(DI) {
662 if(D->getLocation().isValid())
663 DI->setLocation(D->getLocation());
664 DI->EmitGlobalVariable(GV, D);
665 }
Chris Lattner4b009652007-07-25 00:24:17 +0000666}
667
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000668llvm::GlobalValue *
669CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
670 // FIXME: param attributes for sext/zext etc.
671 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
672 assert(!D->getBody() && "Unexpected alias attr on function with body.");
673
674 const std::string& aliaseeName = AA->getAliasee();
675 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
676 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
677 llvm::Function::ExternalLinkage,
678 D->getName(),
679 aliasee,
680 &getModule());
681 SetGlobalValueAttributes(D, alias);
682 return alias;
683 } else {
684 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
685 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
686 llvm::Function *F = llvm::Function::Create(FTy,
687 llvm::Function::ExternalLinkage,
688 D->getName(), &getModule());
689
690 SetFunctionAttributes(D, F, FTy);
691 return F;
692 }
693}
694
695llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000696 QualType ASTTy = D->getType();
697 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
698 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000699
700 // Lookup the entry, lazily creating it if necessary.
701 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
702 if (!Entry)
703 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000704
Daniel Dunbar2188c532008-07-30 16:32:24 +0000705 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000706}
707
708void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000709 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
710 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000711 Entry = EmitForwardFunctionDefinition(D);
712 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000713 // If the types mismatch then we have to rewrite the definition.
714 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
715 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000716 // Otherwise, we have a definition after a prototype with the wrong type.
717 // F is the Function* for the one with the wrong type, we must make a new
718 // Function* and update everything that used F (a declaration) with the new
719 // Function* (which will be a definition).
720 //
721 // This happens if there is a prototype for a function (e.g. "int f()") and
722 // then a definition of a different type (e.g. "int f(int x)"). Start by
723 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000724 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
725 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000726
727 // Replace uses of F with the Function we will endow with a body.
728 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000729 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
730 Entry->replaceAllUsesWith(NewPtrForOldDecl);
731
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000732 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000733 // FIXME: Add GlobalValue->eraseFromParent().
734 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
735 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
736 F->eraseFromParent();
737 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
738 GA->eraseFromParent();
739 } else {
740 assert(0 && "Invalid global variable type.");
741 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000742
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000743 Entry = NewFn;
744 }
745 }
746
747 if (D->getAttr<AliasAttr>()) {
748 ;
749 } else {
750 llvm::Function *Fn = cast<llvm::Function>(Entry);
751 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000752
753 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
754 AddGlobalCtor(Fn, CA->getPriority());
755 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
756 AddGlobalDtor(Fn, DA->getPriority());
757 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000758 }
759}
760
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000761void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
762 // Make sure that this type is translated.
763 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000764}
765
766
Chris Lattnerab862cc2007-08-31 04:31:45 +0000767/// getBuiltinLibFunction
768llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000769 if (BuiltinID > BuiltinFunctions.size())
770 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000771
Chris Lattner9f2d6892007-12-13 00:38:03 +0000772 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
773 // a slot for it.
774 assert(BuiltinID && "Invalid Builtin ID");
775 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000776 if (FunctionSlot)
777 return FunctionSlot;
778
779 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
780
781 // Get the name, skip over the __builtin_ prefix.
782 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
783
784 // Get the type for the builtin.
785 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
786 const llvm::FunctionType *Ty =
787 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
788
789 // FIXME: This has a serious problem with code like this:
790 // void abs() {}
791 // ... __builtin_abs(x);
792 // The two versions of abs will collide. The fix is for the builtin to win,
793 // and for the existing one to be turned into a constantexpr cast of the
794 // builtin. In the case where the existing one is a static function, it
795 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000796 if (llvm::Function *Existing = getModule().getFunction(Name)) {
797 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
798 return FunctionSlot = Existing;
799 assert(Existing == 0 && "FIXME: Name collision");
800 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000801
802 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000803 return FunctionSlot =
804 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
805 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000806}
807
Chris Lattner4b23f942007-12-18 00:25:38 +0000808llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
809 unsigned NumTys) {
810 return llvm::Intrinsic::getDeclaration(&getModule(),
811 (llvm::Intrinsic::ID)IID, Tys, NumTys);
812}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000813
Chris Lattner4b009652007-07-25 00:24:17 +0000814llvm::Function *CodeGenModule::getMemCpyFn() {
815 if (MemCpyFn) return MemCpyFn;
816 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000817 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000818 default: assert(0 && "Unknown ptr width");
819 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
820 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
821 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000822 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000823}
Anders Carlsson36a04872007-08-21 00:21:21 +0000824
Eli Friedman8f08a252008-05-26 12:59:39 +0000825llvm::Function *CodeGenModule::getMemMoveFn() {
826 if (MemMoveFn) return MemMoveFn;
827 llvm::Intrinsic::ID IID;
828 switch (Context.Target.getPointerWidth(0)) {
829 default: assert(0 && "Unknown ptr width");
830 case 32: IID = llvm::Intrinsic::memmove_i32; break;
831 case 64: IID = llvm::Intrinsic::memmove_i64; break;
832 }
833 return MemMoveFn = getIntrinsic(IID);
834}
835
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000836llvm::Function *CodeGenModule::getMemSetFn() {
837 if (MemSetFn) return MemSetFn;
838 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000839 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000840 default: assert(0 && "Unknown ptr width");
841 case 32: IID = llvm::Intrinsic::memset_i32; break;
842 case 64: IID = llvm::Intrinsic::memset_i64; break;
843 }
844 return MemSetFn = getIntrinsic(IID);
845}
Chris Lattner4b23f942007-12-18 00:25:38 +0000846
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000847// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerab862cc2007-08-31 04:31:45 +0000848llvm::Constant *CodeGenModule::
849GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000850 llvm::StringMapEntry<llvm::Constant *> &Entry =
851 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
852
853 if (Entry.getValue())
854 return Entry.getValue();
855
856 std::vector<llvm::Constant*> Fields;
857
858 if (!CFConstantStringClassRef) {
859 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
860 Ty = llvm::ArrayType::get(Ty, 0);
861
862 CFConstantStringClassRef =
863 new llvm::GlobalVariable(Ty, false,
864 llvm::GlobalVariable::ExternalLinkage, 0,
865 "__CFConstantStringClassReference",
866 &getModule());
867 }
868
869 // Class pointer.
870 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
871 llvm::Constant *Zeros[] = { Zero, Zero };
872 llvm::Constant *C =
873 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
874 Fields.push_back(C);
875
876 // Flags.
877 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
878 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
879
880 // String pointer.
881 C = llvm::ConstantArray::get(str);
882 C = new llvm::GlobalVariable(C->getType(), true,
883 llvm::GlobalValue::InternalLinkage,
884 C, ".str", &getModule());
885
886 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
887 Fields.push_back(C);
888
889 // String length.
890 Ty = getTypes().ConvertType(getContext().LongTy);
891 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
892
893 // The struct.
894 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
895 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000896 llvm::GlobalVariable *GV =
897 new llvm::GlobalVariable(C->getType(), true,
898 llvm::GlobalVariable::InternalLinkage,
899 C, "", &getModule());
900 GV->setSection("__DATA,__cfstring");
901 Entry.setValue(GV);
902 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000903}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000904
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000905/// getStringForStringLiteral - Return the appropriate bytes for a
906/// string literal, properly padded to match the literal type.
907std::string CodeGenModule::getStringForStringLiteral(const StringLiteral *E) {
908 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
909 const char *StrData = E->getStrData();
910 unsigned Len = E->getByteLength();
911
912 const ConstantArrayType *CAT =
913 getContext().getAsConstantArrayType(E->getType());
914 assert(CAT && "String isn't pointer or array!");
915
916 // Resize the string to the right size
917 // FIXME: What about wchar_t strings?
918 std::string Str(StrData, StrData+Len);
919 uint64_t RealLen = CAT->getSize().getZExtValue();
920 Str.resize(RealLen, '\0');
921
922 return Str;
923}
924
Chris Lattnera6dcce32008-02-11 00:02:17 +0000925/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000926static llvm::Constant *GenerateStringLiteral(const std::string &str,
927 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000928 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000929 // Create Constant for this string literal
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000930 llvm::Constant *C = llvm::ConstantArray::get(str);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000931
932 // Create a global variable for this string
933 C = new llvm::GlobalVariable(C->getType(), constant,
934 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000935 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000936 return C;
937}
938
Chris Lattnera6dcce32008-02-11 00:02:17 +0000939/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
940/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000941llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
942 // Don't share any string literals if writable-strings is turned on.
943 if (Features.WritableStrings)
944 return GenerateStringLiteral(str, false, *this);
945
946 llvm::StringMapEntry<llvm::Constant *> &Entry =
947 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
948
949 if (Entry.getValue())
950 return Entry.getValue();
951
952 // Create a global variable for this.
953 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
954 Entry.setValue(C);
955 return C;
956}