blob: 176576acbbc29c1bc698ecc1c76c4357c54cd0eb [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000019#include "clang/Basic/Diagnostic.h"
Chris Lattner45e8cbd2007-11-28 05:34:05 +000020#include "clang/Basic/LangOptions.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000023#include "llvm/CallingConv.h"
Chris Lattner8f32f712007-07-14 00:23:28 +000024#include "llvm/Constants.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "llvm/DerivedTypes.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000028#include "llvm/Target/TargetData.h"
Chris Lattnera1945fa2008-04-30 16:05:42 +000029#include "llvm/Analysis/Verifier.h"
Christopher Lambce39faa2007-12-02 08:49:54 +000030#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32using namespace CodeGen;
33
34
Chris Lattner45e8cbd2007-11-28 05:34:05 +000035CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-12-02 01:40:18 +000036 llvm::Module &M, const llvm::TargetData &TD,
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000037 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattnerfb97b032007-12-02 01:40:18 +000038 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Eli Friedman0c995092008-05-26 12:59:39 +000039 Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
40 CFConstantStringClassRef(0) {
Chris Lattner2b94fe32008-03-01 08:45:05 +000041 //TODO: Make this selectable at runtime
Chris Lattnerdce14062008-06-26 04:19:03 +000042 Runtime = CreateObjCRuntime(*this);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000043
44 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek815c78f2008-08-05 18:50:11 +000045 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000046}
47
48CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000049 delete Runtime;
50 delete DebugInfo;
51}
52
53void CodeGenModule::Release() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000054 EmitStatics();
Chris Lattner391d77a2008-03-30 23:03:07 +000055 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerce5605e2008-03-30 23:25:33 +000056 if (ObjCInitFunction)
Chris Lattner391d77a2008-03-30 23:03:07 +000057 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000058 EmitCtorList(GlobalCtors, "llvm.global_ctors");
59 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000060 EmitAnnotations();
Chris Lattnera1945fa2008-04-30 16:05:42 +000061 // Run the verifier to check that the generated code is consistent.
62 assert(!verifyModule(TheModule));
Chris Lattner2b94fe32008-03-01 08:45:05 +000063}
Reid Spencer5f016e22007-07-11 17:01:13 +000064
Chris Lattner2c8569d2007-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 Kremenek9c728dc2007-12-12 22:39:36 +000072 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000073 &Msg, 1, &Range, 1);
Chris Lattner2c8569d2007-12-02 07:19:18 +000074}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000075
Chris Lattnerc6fdc342008-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 Gohman4f8d1232008-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 Lattner6d397602008-03-14 17:18:18 +0000104/// AddGlobalCtor - Add a function to the list that will be called before
105/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000106void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner6d397602008-03-14 17:18:18 +0000107 // TODO: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000108 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000109}
110
Daniel Dunbar6bfed7e2008-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 Lattner572cf092008-03-19 05:24:56 +0000127 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000128 llvm::StructType::get(llvm::Type::Int32Ty,
129 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000130
Daniel Dunbar6bfed7e2008-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 Lattner6d397602008-03-14 17:18:18 +0000138 }
Daniel Dunbar6bfed7e2008-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 Lattner6d397602008-03-14 17:18:18 +0000148}
149
Nate Begeman532485c2008-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 Friedmanff4a2d92008-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 Lopesd4cbda62008-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
187}
188
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000189void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
190 llvm::Function *F,
191 const llvm::FunctionType *FTy) {
192 unsigned FuncAttrs = 0;
193 if (FD->getAttr<NoThrowAttr>())
194 FuncAttrs |= llvm::ParamAttr::NoUnwind;
195 if (FD->getAttr<NoReturnAttr>())
196 FuncAttrs |= llvm::ParamAttr::NoReturn;
197
198 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
199 if (FuncAttrs)
200 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
201 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
202 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
203 if (AggregateReturn)
204 ParamAttrList.push_back(
205 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
206 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000207 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
208 if (FTP) {
209 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
210 QualType ParamType = FTP->getArgType(i);
211 unsigned ParamAttrs = 0;
212 if (ParamType->isRecordType())
213 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattnera4210072008-06-26 05:08:00 +0000214 if (ParamType->isSignedIntegerType() &&
215 ParamType->isPromotableIntegerType())
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000216 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattnera4210072008-06-26 05:08:00 +0000217 if (ParamType->isUnsignedIntegerType() &&
218 ParamType->isPromotableIntegerType())
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000219 ParamAttrs |= llvm::ParamAttr::ZExt;
220 if (ParamAttrs)
221 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
222 ParamAttrs));
223 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000224 }
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000225
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000226 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
227 ParamAttrList.size()));
228
229 // Set the appropriate calling convention for the Function.
230 if (FD->getAttr<FastCallAttr>())
231 F->setCallingConv(llvm::CallingConv::Fast);
232
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000233 SetGlobalValueAttributes(FD, F);
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000234}
235
Chris Lattner391d77a2008-03-30 23:03:07 +0000236void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
237 // If this is not a prototype, emit the body.
238 if (OMD->getBody())
239 CodeGenFunction(*this).GenerateObjCMethod(OMD);
240}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000241void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
242 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner780f3292008-07-21 21:32:27 +0000243 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
244 E = PD->protocol_end(); PI != E; ++PI)
245 Protocols.push_back((*PI)->getName());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000246 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
247 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
248 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
Chris Lattner780f3292008-07-21 21:32:27 +0000249 E = PD->instmeth_end(); iter != E; iter++) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000250 std::string TypeStr;
Chris Lattner780f3292008-07-21 21:32:27 +0000251 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000252 InstanceMethodNames.push_back(
253 GetAddrOfConstantString((*iter)->getSelector().getName()));
254 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
255 }
256 // Collect information about class methods:
257 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
258 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
259 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
260 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
261 std::string TypeStr;
262 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
263 ClassMethodNames.push_back(
264 GetAddrOfConstantString((*iter)->getSelector().getName()));
265 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
266 }
267 Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
268 InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
269}
270
271void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
272
273 // Collect information about instance methods
Chris Lattnera4210072008-06-26 05:08:00 +0000274 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000275 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
276 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
277 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattnera4210072008-06-26 05:08:00 +0000278 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000279 std::string TypeStr;
Chris Lattnerfba67632008-06-26 04:52:29 +0000280 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000281 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
282 }
283
284 // Collect information about class methods
Chris Lattnera4210072008-06-26 05:08:00 +0000285 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000286 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
287 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
288 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattnera4210072008-06-26 05:08:00 +0000289 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000290 std::string TypeStr;
Chris Lattnerfba67632008-06-26 04:52:29 +0000291 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000292 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
293 }
294
295 // Collect the names of referenced protocols
296 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner3db6cae2008-07-21 18:19:38 +0000297 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
298 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
299 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
300 E = Protos.end(); I != E; ++I)
301 Protocols.push_back((*I)->getName());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000302
303 // Generate the category
304 Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
Chris Lattnera4210072008-06-26 05:08:00 +0000305 OCD->getName(), InstanceMethodSels, InstanceMethodTypes,
306 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000307}
308
309void CodeGenModule::EmitObjCClassImplementation(
310 const ObjCImplementationDecl *OID) {
311 // Get the superclass name.
312 const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
313 const char * SCName = NULL;
314 if (SCDecl) {
315 SCName = SCDecl->getName();
316 }
317
318 // Get the class name
319 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
320 const char * ClassName = ClassDecl->getName();
321
322 // Get the size of instances. For runtimes that support late-bound instances
323 // this should probably be something different (size just of instance
324 // varaibles in this class, not superclasses?).
325 int instanceSize = 0;
326 const llvm::Type *ObjTy;
327 if (!Runtime->LateBoundIVars()) {
328 ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
329 instanceSize = TheTargetData.getABITypeSize(ObjTy);
330 }
331
332 // Collect information about instance variables.
333 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
334 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
335 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
336 const llvm::StructLayout *Layout =
337 TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
338 ObjTy = llvm::PointerType::getUnqual(ObjTy);
339 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
340 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
341 // Store the name
342 IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
343 // Get the type encoding for this ivar
344 std::string TypeStr;
345 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
346 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
347 EncodingRecordTypes);
348 IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
349 // Get the offset
350 int offset =
351 (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
352 IvarOffsets.push_back(
353 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
354 }
355
356 // Collect information about instance methods
Chris Lattnera4210072008-06-26 05:08:00 +0000357 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000358 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
359 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
360 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattnera4210072008-06-26 05:08:00 +0000361 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000362 std::string TypeStr;
363 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000364 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
365 }
366
367 // Collect information about class methods
Chris Lattnera4210072008-06-26 05:08:00 +0000368 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000369 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
370 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
371 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattnera4210072008-06-26 05:08:00 +0000372 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000373 std::string TypeStr;
374 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000375 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
376 }
377 // Collect the names of referenced protocols
378 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner3db6cae2008-07-21 18:19:38 +0000379 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
380 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
381 E = Protos.end(); I != E; ++I)
382 Protocols.push_back((*I)->getName());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000383
384 // Generate the category
385 Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
Chris Lattnera4210072008-06-26 05:08:00 +0000386 IvarOffsets, InstanceMethodSels, InstanceMethodTypes,
387 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000388}
389
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000390void CodeGenModule::EmitStatics() {
391 // Emit code for each used static decl encountered. Since a previously unused
392 // static decl may become used during the generation of code for a static
393 // function, iterate until no changes are made.
394 bool Changed;
395 do {
396 Changed = false;
397 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000398 const ValueDecl *D = StaticDecls[i];
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000399
400 // Check if we have used a decl with the same name
401 // FIXME: The AST should have some sort of aggregate decls or
402 // global symbol map.
403 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
404 if (!getModule().getFunction(FD->getName()))
405 continue;
406 } else {
407 if (!getModule().getNamedGlobal(cast<VarDecl>(D)->getName()))
408 continue;
409 }
410
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000411 // Emit the definition.
412 EmitGlobalDefinition(D);
413
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000414 // Erase the used decl from the list.
415 StaticDecls[i] = StaticDecls.back();
416 StaticDecls.pop_back();
417 --i;
418 --e;
419
420 // Remember that we made a change.
421 Changed = true;
422 }
423 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000424}
425
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000426/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
427/// annotation information for a given GlobalValue. The annotation struct is
428/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000429/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000430/// created from the AnnotateAttr's annotation. The third field is a constant
431/// string containing the name of the translation unit. The fourth field is
432/// the line number in the file of the annotated value declaration.
433///
434/// FIXME: this does not unique the annotation string constants, as llvm-gcc
435/// appears to.
436///
437llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
438 const AnnotateAttr *AA,
439 unsigned LineNo) {
440 llvm::Module *M = &getModule();
441
442 // get [N x i8] constants for the annotation string, and the filename string
443 // which are the 2nd and 3rd elements of the global annotation structure.
444 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
445 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
446 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
447 true);
448
449 // Get the two global values corresponding to the ConstantArrays we just
450 // created to hold the bytes of the strings.
451 llvm::GlobalValue *annoGV =
452 new llvm::GlobalVariable(anno->getType(), false,
453 llvm::GlobalValue::InternalLinkage, anno,
454 GV->getName() + ".str", M);
455 // translation unit name string, emitted into the llvm.metadata section.
456 llvm::GlobalValue *unitGV =
457 new llvm::GlobalVariable(unit->getType(), false,
458 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
459
460 // Create the ConstantStruct that is the global annotion.
461 llvm::Constant *Fields[4] = {
462 llvm::ConstantExpr::getBitCast(GV, SBP),
463 llvm::ConstantExpr::getBitCast(annoGV, SBP),
464 llvm::ConstantExpr::getBitCast(unitGV, SBP),
465 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
466 };
467 return llvm::ConstantStruct::get(Fields, 4, false);
468}
469
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000470void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
471 bool isDef, isStatic;
472
473 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
474 isDef = (FD->isThisDeclarationADefinition() ||
475 FD->getAttr<AliasAttr>());
476 isStatic = FD->getStorageClass() == FunctionDecl::Static;
477 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
478 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
479
480 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
481 isStatic = VD->getStorageClass() == VarDecl::Static;
482 } else {
483 assert(0 && "Invalid argument to EmitGlobal");
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000484 return;
485 }
486
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000487 // Forward declarations are emitted lazily on first use.
488 if (!isDef)
Chris Lattner88a69ad2007-07-13 05:13:43 +0000489 return;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000490
491 // If the global is a static, defer code generation until later so
492 // we can easily omit unused statics.
493 if (isStatic) {
494 StaticDecls.push_back(Global);
495 return;
496 }
497
498 // Otherwise emit the definition.
499 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000500}
501
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000502void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
503 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
504 EmitGlobalFunctionDefinition(FD);
505 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
506 EmitGlobalVarDefinition(VD);
507 } else {
508 assert(0 && "Invalid argument to EmitGlobalDefinition()");
509 }
510}
511
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000512 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000513 assert(D->hasGlobalStorage() && "Not a global variable");
514
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000515 QualType ASTTy = D->getType();
516 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000517 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000518
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000519 // Lookup the entry, lazily creating it if necessary.
520 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
521 if (!Entry)
522 Entry = new llvm::GlobalVariable(Ty, false,
523 llvm::GlobalValue::ExternalLinkage,
524 0, D->getName(), &getModule(), 0,
525 ASTTy.getAddressSpace());
526
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000527 // Make sure the result is of the correct type.
528 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000529}
530
531void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000532 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000533 QualType ASTTy = D->getType();
534 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000535
Chris Lattner8f32f712007-07-14 00:23:28 +0000536 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000537 // This is a tentative definition; tentative definitions are
538 // implicitly initialized with { 0 }
539 const llvm::Type* InitTy;
540 if (ASTTy->isIncompleteArrayType()) {
541 // An incomplete array is normally [ TYPE x 0 ], but we need
542 // to fix it to [ TYPE x 1 ].
543 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
544 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
545 } else {
546 InitTy = VarTy;
547 }
548 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000549 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000550 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000551 }
552 const llvm::Type* InitType = Init->getType();
553
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000554 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
555 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
556
Eli Friedman77ba7082008-05-30 19:50:47 +0000557 if (!GV) {
558 GV = new llvm::GlobalVariable(InitType, false,
559 llvm::GlobalValue::ExternalLinkage,
560 0, D->getName(), &getModule(), 0,
561 ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000562 } else if (GV->getType() !=
563 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000564 // We have a definition after a prototype with the wrong type.
565 // We must make a new GlobalVariable* and update everything that used OldGV
566 // (a declaration or tentative definition) with the new GlobalVariable*
567 // (which will be a definition).
568 //
569 // This happens if there is a prototype for a global (e.g. "extern int x[];")
570 // and then a definition of a different type (e.g. "int x[10];"). This also
571 // happens when an initializer has a different type from the type of the
572 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000573 //
574 // FIXME: This also ends up happening if there's a definition followed by
575 // a tentative definition! (Although Sema rejects that construct
576 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000577
578 // Save the old global
579 llvm::GlobalVariable *OldGV = GV;
580
581 // Make a new global with the correct type
582 GV = new llvm::GlobalVariable(InitType, false,
583 llvm::GlobalValue::ExternalLinkage,
584 0, D->getName(), &getModule(), 0,
585 ASTTy.getAddressSpace());
586 // Steal the name of the old global
587 GV->takeName(OldGV);
588
589 // Replace all uses of the old global with the new global
590 llvm::Constant *NewPtrForOldDecl =
591 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
592 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000593
594 // Erase the old global, since it is no longer used.
595 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000596 }
Devang Patel8e53e722007-10-26 16:31:40 +0000597
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000598 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000599
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000600 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
601 SourceManager &SM = Context.getSourceManager();
602 AddAnnotation(EmitAnnotateAttr(GV, AA,
603 SM.getLogicalLineNumber(D->getLocation())));
604 }
605
Chris Lattner88a69ad2007-07-13 05:13:43 +0000606 GV->setInitializer(Init);
Chris Lattnerddee4232008-03-03 03:28:21 +0000607
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000608 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
609 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000610 if (const IncompleteArrayType* IAT =
611 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000612 Align = Context.getTypeAlign(IAT->getElementType());
613 else
614 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000615 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
616 Align = std::max(Align, AA->getAlignment());
617 }
618 GV->setAlignment(Align / 8);
619
Chris Lattnerddee4232008-03-03 03:28:21 +0000620 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4f8d1232008-05-22 00:50:06 +0000621 setVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000622 // FIXME: else handle -fvisibility
Chris Lattner88a69ad2007-07-13 05:13:43 +0000623
624 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000625 if (D->getStorageClass() == VarDecl::Static)
626 GV->setLinkage(llvm::Function::InternalLinkage);
627 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000628 GV->setLinkage(llvm::Function::DLLImportLinkage);
629 else if (D->getAttr<DLLExportAttr>())
630 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000631 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000632 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000633 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000634 // FIXME: This isn't right. This should handle common linkage and other
635 // stuff.
636 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000637 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000638 case VarDecl::Auto:
639 case VarDecl::Register:
640 assert(0 && "Can't have auto or register globals");
641 case VarDecl::None:
642 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000643 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000644 break;
645 case VarDecl::Extern:
646 case VarDecl::PrivateExtern:
647 // todo: common
648 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000649 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000650 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000651
652 // Emit global variable debug information.
653 CGDebugInfo *DI = getDebugInfo();
654 if(DI) {
655 if(D->getLocation().isValid())
656 DI->setLocation(D->getLocation());
657 DI->EmitGlobalVariable(GV, D);
658 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000659}
Reid Spencer5f016e22007-07-11 17:01:13 +0000660
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000661llvm::GlobalValue *
662CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
663 // FIXME: param attributes for sext/zext etc.
664 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
665 assert(!D->getBody() && "Unexpected alias attr on function with body.");
666
667 const std::string& aliaseeName = AA->getAliasee();
668 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
669 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
670 llvm::Function::ExternalLinkage,
671 D->getName(),
672 aliasee,
673 &getModule());
674 SetGlobalValueAttributes(D, alias);
675 return alias;
676 } else {
677 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
678 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
679 llvm::Function *F = llvm::Function::Create(FTy,
680 llvm::Function::ExternalLinkage,
681 D->getName(), &getModule());
682
683 SetFunctionAttributes(D, F, FTy);
684 return F;
685 }
686}
687
688llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000689 QualType ASTTy = D->getType();
690 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
691 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000692
693 // Lookup the entry, lazily creating it if necessary.
694 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
695 if (!Entry)
696 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000697
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000698 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000699}
700
701void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000702 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
703 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000704 Entry = EmitForwardFunctionDefinition(D);
705 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000706 // If the types mismatch then we have to rewrite the definition.
707 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
708 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000709 // Otherwise, we have a definition after a prototype with the wrong type.
710 // F is the Function* for the one with the wrong type, we must make a new
711 // Function* and update everything that used F (a declaration) with the new
712 // Function* (which will be a definition).
713 //
714 // This happens if there is a prototype for a function (e.g. "int f()") and
715 // then a definition of a different type (e.g. "int f(int x)"). Start by
716 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000717 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
718 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000719
720 // Replace uses of F with the Function we will endow with a body.
721 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000722 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
723 Entry->replaceAllUsesWith(NewPtrForOldDecl);
724
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000725 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000726 // FIXME: Add GlobalValue->eraseFromParent().
727 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
728 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
729 F->eraseFromParent();
730 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
731 GA->eraseFromParent();
732 } else {
733 assert(0 && "Invalid global variable type.");
734 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000735
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000736 Entry = NewFn;
737 }
738 }
739
740 if (D->getAttr<AliasAttr>()) {
741 ;
742 } else {
743 llvm::Function *Fn = cast<llvm::Function>(Entry);
744 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000745
746 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
747 AddGlobalCtor(Fn, CA->getPriority());
748 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
749 AddGlobalDtor(Fn, DA->getPriority());
750 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000751 }
752}
753
Chris Lattnerc5b88062008-02-06 05:08:19 +0000754void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
755 // Make sure that this type is translated.
756 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000757}
758
759
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000760/// getBuiltinLibFunction
761llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000762 if (BuiltinID > BuiltinFunctions.size())
763 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000764
Chris Lattner1426fec2007-12-13 00:38:03 +0000765 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
766 // a slot for it.
767 assert(BuiltinID && "Invalid Builtin ID");
768 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000769 if (FunctionSlot)
770 return FunctionSlot;
771
772 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
773
774 // Get the name, skip over the __builtin_ prefix.
775 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
776
777 // Get the type for the builtin.
778 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
779 const llvm::FunctionType *Ty =
780 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
781
782 // FIXME: This has a serious problem with code like this:
783 // void abs() {}
784 // ... __builtin_abs(x);
785 // The two versions of abs will collide. The fix is for the builtin to win,
786 // and for the existing one to be turned into a constantexpr cast of the
787 // builtin. In the case where the existing one is a static function, it
788 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000789 if (llvm::Function *Existing = getModule().getFunction(Name)) {
790 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
791 return FunctionSlot = Existing;
792 assert(Existing == 0 && "FIXME: Name collision");
793 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000794
795 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000796 return FunctionSlot =
797 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
798 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000799}
800
Chris Lattner7acda7c2007-12-18 00:25:38 +0000801llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
802 unsigned NumTys) {
803 return llvm::Intrinsic::getDeclaration(&getModule(),
804 (llvm::Intrinsic::ID)IID, Tys, NumTys);
805}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000806
Reid Spencer5f016e22007-07-11 17:01:13 +0000807llvm::Function *CodeGenModule::getMemCpyFn() {
808 if (MemCpyFn) return MemCpyFn;
809 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000810 switch (Context.Target.getPointerWidth(0)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 default: assert(0 && "Unknown ptr width");
812 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
813 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
814 }
Chris Lattner7acda7c2007-12-18 00:25:38 +0000815 return MemCpyFn = getIntrinsic(IID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000816}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000817
Eli Friedman0c995092008-05-26 12:59:39 +0000818llvm::Function *CodeGenModule::getMemMoveFn() {
819 if (MemMoveFn) return MemMoveFn;
820 llvm::Intrinsic::ID IID;
821 switch (Context.Target.getPointerWidth(0)) {
822 default: assert(0 && "Unknown ptr width");
823 case 32: IID = llvm::Intrinsic::memmove_i32; break;
824 case 64: IID = llvm::Intrinsic::memmove_i64; break;
825 }
826 return MemMoveFn = getIntrinsic(IID);
827}
828
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000829llvm::Function *CodeGenModule::getMemSetFn() {
830 if (MemSetFn) return MemSetFn;
831 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000832 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000833 default: assert(0 && "Unknown ptr width");
834 case 32: IID = llvm::Intrinsic::memset_i32; break;
835 case 64: IID = llvm::Intrinsic::memset_i64; break;
836 }
837 return MemSetFn = getIntrinsic(IID);
838}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000839
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000840// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000841llvm::Constant *CodeGenModule::
842GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000843 llvm::StringMapEntry<llvm::Constant *> &Entry =
844 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
845
846 if (Entry.getValue())
847 return Entry.getValue();
848
849 std::vector<llvm::Constant*> Fields;
850
851 if (!CFConstantStringClassRef) {
852 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
853 Ty = llvm::ArrayType::get(Ty, 0);
854
855 CFConstantStringClassRef =
856 new llvm::GlobalVariable(Ty, false,
857 llvm::GlobalVariable::ExternalLinkage, 0,
858 "__CFConstantStringClassReference",
859 &getModule());
860 }
861
862 // Class pointer.
863 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
864 llvm::Constant *Zeros[] = { Zero, Zero };
865 llvm::Constant *C =
866 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
867 Fields.push_back(C);
868
869 // Flags.
870 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
871 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
872
873 // String pointer.
874 C = llvm::ConstantArray::get(str);
875 C = new llvm::GlobalVariable(C->getType(), true,
876 llvm::GlobalValue::InternalLinkage,
877 C, ".str", &getModule());
878
879 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
880 Fields.push_back(C);
881
882 // String length.
883 Ty = getTypes().ConvertType(getContext().LongTy);
884 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
885
886 // The struct.
887 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
888 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000889 llvm::GlobalVariable *GV =
890 new llvm::GlobalVariable(C->getType(), true,
891 llvm::GlobalVariable::InternalLinkage,
892 C, "", &getModule());
893 GV->setSection("__DATA,__cfstring");
894 Entry.setValue(GV);
895 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000896}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000897
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000898/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000899static llvm::Constant *GenerateStringLiteral(const std::string &str,
900 bool constant,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000901 CodeGenModule &CGM) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000902 // Create Constant for this string literal
903 llvm::Constant *C=llvm::ConstantArray::get(str);
904
905 // Create a global variable for this string
906 C = new llvm::GlobalVariable(C->getType(), constant,
907 llvm::GlobalValue::InternalLinkage,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000908 C, ".str", &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000909 return C;
910}
911
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000912/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
913/// array containing the literal. The result is pointer to array type.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000914llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
915 // Don't share any string literals if writable-strings is turned on.
916 if (Features.WritableStrings)
917 return GenerateStringLiteral(str, false, *this);
918
919 llvm::StringMapEntry<llvm::Constant *> &Entry =
920 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
921
922 if (Entry.getValue())
923 return Entry.getValue();
924
925 // Create a global variable for this.
926 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
927 Entry.setValue(C);
928 return C;
929}