blob: 347f4d24f903fc8d6aad66e76906863740dd6bd4 [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"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000019#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000020#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000022#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000023#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000025#include "llvm/Target/TargetData.h"
Chris Lattnera1945fa2008-04-30 16:05:42 +000026#include "llvm/Analysis/Verifier.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28using namespace CodeGen;
29
30
Chris Lattner45e8cbd2007-11-28 05:34:05 +000031CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-12-02 01:40:18 +000032 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000033 Diagnostic &diags, bool GenerateDebugInfo,
34 bool UseMacObjCRuntime)
Chris Lattnerfb97b032007-12-02 01:40:18 +000035 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000036 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman0c995092008-05-26 12:59:39 +000037 CFConstantStringClassRef(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000038
39 if (Features.ObjC1) {
40 // TODO: Make this selectable at runtime
41 if (UseMacObjCRuntime) {
42 Runtime = CreateMacObjCRuntime(*this);
43 } else {
44 Runtime = CreateGNUObjCRuntime(*this);
45 }
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000046 }
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000047
48 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek815c78f2008-08-05 18:50:11 +000049 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000050}
51
52CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000053 delete Runtime;
54 delete DebugInfo;
55}
56
57void CodeGenModule::Release() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000058 EmitStatics();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000059 if (Runtime)
60 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
61 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000062 EmitCtorList(GlobalCtors, "llvm.global_ctors");
63 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000064 EmitAnnotations();
Chris Lattnera1945fa2008-04-30 16:05:42 +000065 // Run the verifier to check that the generated code is consistent.
66 assert(!verifyModule(TheModule));
Chris Lattner2b94fe32008-03-01 08:45:05 +000067}
Reid Spencer5f016e22007-07-11 17:01:13 +000068
Chris Lattner2c8569d2007-12-02 07:19:18 +000069/// WarnUnsupported - Print out a warning that codegen doesn't support the
70/// specified stmt yet.
71void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
72 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
73 "cannot codegen this %0 yet");
74 SourceRange Range = S->getSourceRange();
75 std::string Msg = Type;
Ted Kremenek9c728dc2007-12-12 22:39:36 +000076 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000077 &Msg, 1, &Range, 1);
Chris Lattner2c8569d2007-12-02 07:19:18 +000078}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000079
Chris Lattnerc6fdc342008-01-12 07:05:38 +000080/// WarnUnsupported - Print out a warning that codegen doesn't support the
81/// specified decl yet.
82void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
83 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
84 "cannot codegen this %0 yet");
85 std::string Msg = Type;
86 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
87 &Msg, 1);
88}
89
Dan Gohman4f8d1232008-05-22 00:50:06 +000090/// setVisibility - Set the visibility for the given LLVM GlobalValue
91/// according to the given clang AST visibility value.
92void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
93 VisibilityAttr::VisibilityTypes Vis) {
94 switch (Vis) {
95 default: assert(0 && "Unknown visibility!");
96 case VisibilityAttr::DefaultVisibility:
97 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
98 break;
99 case VisibilityAttr::HiddenVisibility:
100 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
101 break;
102 case VisibilityAttr::ProtectedVisibility:
103 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
104 break;
105 }
106}
107
Chris Lattner6d397602008-03-14 17:18:18 +0000108/// AddGlobalCtor - Add a function to the list that will be called before
109/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000110void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner6d397602008-03-14 17:18:18 +0000111 // TODO: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000112 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000113}
114
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000115/// AddGlobalDtor - Add a function to the list that will be called
116/// when the module is unloaded.
117void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
118 // TODO: Type coercion of void()* types.
119 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
120}
121
122void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
123 // Ctor function type is void()*.
124 llvm::FunctionType* CtorFTy =
125 llvm::FunctionType::get(llvm::Type::VoidTy,
126 std::vector<const llvm::Type*>(),
127 false);
128 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
129
130 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000131 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000132 llvm::StructType::get(llvm::Type::Int32Ty,
133 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000134
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000135 // Construct the constructor and destructor arrays.
136 std::vector<llvm::Constant*> Ctors;
137 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
138 std::vector<llvm::Constant*> S;
139 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
140 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
141 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000142 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000143
144 if (!Ctors.empty()) {
145 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
146 new llvm::GlobalVariable(AT, false,
147 llvm::GlobalValue::AppendingLinkage,
148 llvm::ConstantArray::get(AT, Ctors),
149 GlobalName,
150 &TheModule);
151 }
Chris Lattner6d397602008-03-14 17:18:18 +0000152}
153
Nate Begeman532485c2008-04-18 23:43:57 +0000154void CodeGenModule::EmitAnnotations() {
155 if (Annotations.empty())
156 return;
157
158 // Create a new global variable for the ConstantStruct in the Module.
159 llvm::Constant *Array =
160 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
161 Annotations.size()),
162 Annotations);
163 llvm::GlobalValue *gv =
164 new llvm::GlobalVariable(Array->getType(), false,
165 llvm::GlobalValue::AppendingLinkage, Array,
166 "llvm.global.annotations", &TheModule);
167 gv->setSection("llvm.metadata");
168}
169
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000170bool hasAggregateLLVMType(QualType T) {
171 return !T->isRealType() && !T->isPointerLikeType() &&
172 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
173}
174
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000175void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
176 llvm::GlobalValue *GV) {
177 // TODO: Set up linkage and many other things. Note, this is a simple
178 // approximation of what we really want.
179 if (FD->getStorageClass() == FunctionDecl::Static)
180 GV->setLinkage(llvm::Function::InternalLinkage);
181 else if (FD->getAttr<DLLImportAttr>())
182 GV->setLinkage(llvm::Function::DLLImportLinkage);
183 else if (FD->getAttr<DLLExportAttr>())
184 GV->setLinkage(llvm::Function::DLLExportLinkage);
185 else if (FD->getAttr<WeakAttr>() || FD->isInline())
186 GV->setLinkage(llvm::Function::WeakLinkage);
187
188 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
189 CodeGenModule::setVisibility(GV, attr->getVisibility());
190 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000191
192 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
193 // Prefaced with special LLVM marker to indicate that the name
194 // should not be munged.
195 GV->setName("\01" + ALA->getLabel());
196 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000197}
198
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000199void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
200 llvm::Function *F,
201 const llvm::FunctionType *FTy) {
202 unsigned FuncAttrs = 0;
203 if (FD->getAttr<NoThrowAttr>())
204 FuncAttrs |= llvm::ParamAttr::NoUnwind;
205 if (FD->getAttr<NoReturnAttr>())
206 FuncAttrs |= llvm::ParamAttr::NoReturn;
207
208 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
209 if (FuncAttrs)
210 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
211 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
212 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
213 if (AggregateReturn)
214 ParamAttrList.push_back(
215 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
216 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000217 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
218 if (FTP) {
219 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
220 QualType ParamType = FTP->getArgType(i);
221 unsigned ParamAttrs = 0;
222 if (ParamType->isRecordType())
223 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattnera4210072008-06-26 05:08:00 +0000224 if (ParamType->isSignedIntegerType() &&
225 ParamType->isPromotableIntegerType())
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000226 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattnera4210072008-06-26 05:08:00 +0000227 if (ParamType->isUnsignedIntegerType() &&
228 ParamType->isPromotableIntegerType())
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000229 ParamAttrs |= llvm::ParamAttr::ZExt;
230 if (ParamAttrs)
231 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
232 ParamAttrs));
233 }
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000234 }
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000235
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000236 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
237 ParamAttrList.size()));
238
239 // Set the appropriate calling convention for the Function.
240 if (FD->getAttr<FastCallAttr>())
241 F->setCallingConv(llvm::CallingConv::Fast);
242
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000243 SetGlobalValueAttributes(FD, F);
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000244}
245
Chris Lattner391d77a2008-03-30 23:03:07 +0000246void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
247 // If this is not a prototype, emit the body.
248 if (OMD->getBody())
249 CodeGenFunction(*this).GenerateObjCMethod(OMD);
250}
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000251void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
252 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner780f3292008-07-21 21:32:27 +0000253 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
254 E = PD->protocol_end(); PI != E; ++PI)
255 Protocols.push_back((*PI)->getName());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000256 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
257 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
258 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
Chris Lattner780f3292008-07-21 21:32:27 +0000259 E = PD->instmeth_end(); iter != E; iter++) {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000260 std::string TypeStr;
Chris Lattner780f3292008-07-21 21:32:27 +0000261 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000262 InstanceMethodNames.push_back(
263 GetAddrOfConstantString((*iter)->getSelector().getName()));
264 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
265 }
266 // Collect information about class methods:
267 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
268 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
269 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
270 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
271 std::string TypeStr;
272 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
273 ClassMethodNames.push_back(
274 GetAddrOfConstantString((*iter)->getSelector().getName()));
275 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
276 }
277 Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
278 InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
279}
280
281void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
282
283 // Collect information about instance methods
Chris Lattnera4210072008-06-26 05:08:00 +0000284 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000285 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
286 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
287 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattnera4210072008-06-26 05:08:00 +0000288 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000289 std::string TypeStr;
Chris Lattnerfba67632008-06-26 04:52:29 +0000290 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000291 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
292 }
293
294 // Collect information about class methods
Chris Lattnera4210072008-06-26 05:08:00 +0000295 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000296 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
297 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
298 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattnera4210072008-06-26 05:08:00 +0000299 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000300 std::string TypeStr;
Chris Lattnerfba67632008-06-26 04:52:29 +0000301 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000302 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
303 }
304
305 // Collect the names of referenced protocols
306 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner3db6cae2008-07-21 18:19:38 +0000307 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
308 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
309 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
310 E = Protos.end(); I != E; ++I)
311 Protocols.push_back((*I)->getName());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000312
313 // Generate the category
314 Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
Chris Lattnera4210072008-06-26 05:08:00 +0000315 OCD->getName(), InstanceMethodSels, InstanceMethodTypes,
316 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000317}
318
319void CodeGenModule::EmitObjCClassImplementation(
320 const ObjCImplementationDecl *OID) {
321 // Get the superclass name.
322 const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
323 const char * SCName = NULL;
324 if (SCDecl) {
325 SCName = SCDecl->getName();
326 }
327
328 // Get the class name
329 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
330 const char * ClassName = ClassDecl->getName();
331
332 // Get the size of instances. For runtimes that support late-bound instances
333 // this should probably be something different (size just of instance
334 // varaibles in this class, not superclasses?).
335 int instanceSize = 0;
336 const llvm::Type *ObjTy;
337 if (!Runtime->LateBoundIVars()) {
338 ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
339 instanceSize = TheTargetData.getABITypeSize(ObjTy);
340 }
341
342 // Collect information about instance variables.
343 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
344 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
345 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
346 const llvm::StructLayout *Layout =
347 TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
348 ObjTy = llvm::PointerType::getUnqual(ObjTy);
349 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
350 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
351 // Store the name
352 IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
353 // Get the type encoding for this ivar
354 std::string TypeStr;
355 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
356 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
357 EncodingRecordTypes);
358 IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
359 // Get the offset
360 int offset =
361 (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
362 IvarOffsets.push_back(
363 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
364 }
365
366 // Collect information about instance methods
Chris Lattnera4210072008-06-26 05:08:00 +0000367 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000368 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
369 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
370 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattnera4210072008-06-26 05:08:00 +0000371 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000372 std::string TypeStr;
373 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000374 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
375 }
376
377 // Collect information about class methods
Chris Lattnera4210072008-06-26 05:08:00 +0000378 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000379 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
380 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
381 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattnera4210072008-06-26 05:08:00 +0000382 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000383 std::string TypeStr;
384 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000385 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
386 }
387 // Collect the names of referenced protocols
388 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner3db6cae2008-07-21 18:19:38 +0000389 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
390 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
391 E = Protos.end(); I != E; ++I)
392 Protocols.push_back((*I)->getName());
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000393
394 // Generate the category
395 Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
Chris Lattnera4210072008-06-26 05:08:00 +0000396 IvarOffsets, InstanceMethodSels, InstanceMethodTypes,
397 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000398}
399
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000400void CodeGenModule::EmitStatics() {
401 // Emit code for each used static decl encountered. Since a previously unused
402 // static decl may become used during the generation of code for a static
403 // function, iterate until no changes are made.
404 bool Changed;
405 do {
406 Changed = false;
407 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000408 const ValueDecl *D = StaticDecls[i];
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000409
410 // Check if we have used a decl with the same name
411 // FIXME: The AST should have some sort of aggregate decls or
412 // global symbol map.
Daniel Dunbara735ad82008-08-06 00:03:29 +0000413 if (!GlobalDeclMap.count(D->getName()))
414 continue;
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000415
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000416 // Emit the definition.
417 EmitGlobalDefinition(D);
418
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000419 // Erase the used decl from the list.
420 StaticDecls[i] = StaticDecls.back();
421 StaticDecls.pop_back();
422 --i;
423 --e;
424
425 // Remember that we made a change.
426 Changed = true;
427 }
428 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000429}
430
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000431/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
432/// annotation information for a given GlobalValue. The annotation struct is
433/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000434/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000435/// created from the AnnotateAttr's annotation. The third field is a constant
436/// string containing the name of the translation unit. The fourth field is
437/// the line number in the file of the annotated value declaration.
438///
439/// FIXME: this does not unique the annotation string constants, as llvm-gcc
440/// appears to.
441///
442llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
443 const AnnotateAttr *AA,
444 unsigned LineNo) {
445 llvm::Module *M = &getModule();
446
447 // get [N x i8] constants for the annotation string, and the filename string
448 // which are the 2nd and 3rd elements of the global annotation structure.
449 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
450 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
451 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
452 true);
453
454 // Get the two global values corresponding to the ConstantArrays we just
455 // created to hold the bytes of the strings.
456 llvm::GlobalValue *annoGV =
457 new llvm::GlobalVariable(anno->getType(), false,
458 llvm::GlobalValue::InternalLinkage, anno,
459 GV->getName() + ".str", M);
460 // translation unit name string, emitted into the llvm.metadata section.
461 llvm::GlobalValue *unitGV =
462 new llvm::GlobalVariable(unit->getType(), false,
463 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
464
465 // Create the ConstantStruct that is the global annotion.
466 llvm::Constant *Fields[4] = {
467 llvm::ConstantExpr::getBitCast(GV, SBP),
468 llvm::ConstantExpr::getBitCast(annoGV, SBP),
469 llvm::ConstantExpr::getBitCast(unitGV, SBP),
470 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
471 };
472 return llvm::ConstantStruct::get(Fields, 4, false);
473}
474
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000475void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
476 bool isDef, isStatic;
477
478 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
479 isDef = (FD->isThisDeclarationADefinition() ||
480 FD->getAttr<AliasAttr>());
481 isStatic = FD->getStorageClass() == FunctionDecl::Static;
482 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
483 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
484
485 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
486 isStatic = VD->getStorageClass() == VarDecl::Static;
487 } else {
488 assert(0 && "Invalid argument to EmitGlobal");
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000489 return;
490 }
491
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000492 // Forward declarations are emitted lazily on first use.
493 if (!isDef)
Chris Lattner88a69ad2007-07-13 05:13:43 +0000494 return;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000495
496 // If the global is a static, defer code generation until later so
497 // we can easily omit unused statics.
498 if (isStatic) {
499 StaticDecls.push_back(Global);
500 return;
501 }
502
503 // Otherwise emit the definition.
504 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000505}
506
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000507void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
508 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
509 EmitGlobalFunctionDefinition(FD);
510 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
511 EmitGlobalVarDefinition(VD);
512 } else {
513 assert(0 && "Invalid argument to EmitGlobalDefinition()");
514 }
515}
516
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000517 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000518 assert(D->hasGlobalStorage() && "Not a global variable");
519
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000520 QualType ASTTy = D->getType();
521 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000522 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000523
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000524 // Lookup the entry, lazily creating it if necessary.
525 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
526 if (!Entry)
527 Entry = new llvm::GlobalVariable(Ty, false,
528 llvm::GlobalValue::ExternalLinkage,
529 0, D->getName(), &getModule(), 0,
530 ASTTy.getAddressSpace());
531
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000532 // Make sure the result is of the correct type.
533 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000534}
535
536void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000537 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000538 QualType ASTTy = D->getType();
539 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000540
Chris Lattner8f32f712007-07-14 00:23:28 +0000541 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000542 // This is a tentative definition; tentative definitions are
543 // implicitly initialized with { 0 }
544 const llvm::Type* InitTy;
545 if (ASTTy->isIncompleteArrayType()) {
546 // An incomplete array is normally [ TYPE x 0 ], but we need
547 // to fix it to [ TYPE x 1 ].
548 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
549 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
550 } else {
551 InitTy = VarTy;
552 }
553 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000554 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000555 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000556 }
557 const llvm::Type* InitType = Init->getType();
558
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000559 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
560 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
561
Eli Friedman77ba7082008-05-30 19:50:47 +0000562 if (!GV) {
563 GV = new llvm::GlobalVariable(InitType, false,
564 llvm::GlobalValue::ExternalLinkage,
565 0, D->getName(), &getModule(), 0,
566 ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000567 } else if (GV->getType() !=
568 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000569 // We have a definition after a prototype with the wrong type.
570 // We must make a new GlobalVariable* and update everything that used OldGV
571 // (a declaration or tentative definition) with the new GlobalVariable*
572 // (which will be a definition).
573 //
574 // This happens if there is a prototype for a global (e.g. "extern int x[];")
575 // and then a definition of a different type (e.g. "int x[10];"). This also
576 // happens when an initializer has a different type from the type of the
577 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000578 //
579 // FIXME: This also ends up happening if there's a definition followed by
580 // a tentative definition! (Although Sema rejects that construct
581 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000582
583 // Save the old global
584 llvm::GlobalVariable *OldGV = GV;
585
586 // Make a new global with the correct type
587 GV = new llvm::GlobalVariable(InitType, false,
588 llvm::GlobalValue::ExternalLinkage,
589 0, D->getName(), &getModule(), 0,
590 ASTTy.getAddressSpace());
591 // Steal the name of the old global
592 GV->takeName(OldGV);
593
594 // Replace all uses of the old global with the new global
595 llvm::Constant *NewPtrForOldDecl =
596 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
597 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000598
599 // Erase the old global, since it is no longer used.
600 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000601 }
Devang Patel8e53e722007-10-26 16:31:40 +0000602
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000603 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000604
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000605 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
606 SourceManager &SM = Context.getSourceManager();
607 AddAnnotation(EmitAnnotateAttr(GV, AA,
608 SM.getLogicalLineNumber(D->getLocation())));
609 }
610
Chris Lattner88a69ad2007-07-13 05:13:43 +0000611 GV->setInitializer(Init);
Chris Lattnerddee4232008-03-03 03:28:21 +0000612
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000613 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
614 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000615 if (const IncompleteArrayType* IAT =
616 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000617 Align = Context.getTypeAlign(IAT->getElementType());
618 else
619 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000620 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
621 Align = std::max(Align, AA->getAlignment());
622 }
623 GV->setAlignment(Align / 8);
624
Chris Lattnerddee4232008-03-03 03:28:21 +0000625 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4f8d1232008-05-22 00:50:06 +0000626 setVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000627 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000628
629 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
630 // Prefaced with special LLVM marker to indicate that the name
631 // should not be munged.
632 GV->setName("\01" + ALA->getLabel());
633 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000634
635 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000636 if (D->getStorageClass() == VarDecl::Static)
637 GV->setLinkage(llvm::Function::InternalLinkage);
638 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000639 GV->setLinkage(llvm::Function::DLLImportLinkage);
640 else if (D->getAttr<DLLExportAttr>())
641 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000642 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000643 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000644 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000645 // FIXME: This isn't right. This should handle common linkage and other
646 // stuff.
647 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000648 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000649 case VarDecl::Auto:
650 case VarDecl::Register:
651 assert(0 && "Can't have auto or register globals");
652 case VarDecl::None:
653 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000654 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000655 break;
656 case VarDecl::Extern:
657 case VarDecl::PrivateExtern:
658 // todo: common
659 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000660 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000661 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000662
663 // Emit global variable debug information.
664 CGDebugInfo *DI = getDebugInfo();
665 if(DI) {
666 if(D->getLocation().isValid())
667 DI->setLocation(D->getLocation());
668 DI->EmitGlobalVariable(GV, D);
669 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000670}
Reid Spencer5f016e22007-07-11 17:01:13 +0000671
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000672llvm::GlobalValue *
673CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
674 // FIXME: param attributes for sext/zext etc.
675 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
676 assert(!D->getBody() && "Unexpected alias attr on function with body.");
677
678 const std::string& aliaseeName = AA->getAliasee();
679 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
680 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
681 llvm::Function::ExternalLinkage,
682 D->getName(),
683 aliasee,
684 &getModule());
685 SetGlobalValueAttributes(D, alias);
686 return alias;
687 } else {
688 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
689 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
690 llvm::Function *F = llvm::Function::Create(FTy,
691 llvm::Function::ExternalLinkage,
692 D->getName(), &getModule());
693
694 SetFunctionAttributes(D, F, FTy);
695 return F;
696 }
697}
698
699llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000700 QualType ASTTy = D->getType();
701 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
702 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000703
704 // Lookup the entry, lazily creating it if necessary.
705 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
706 if (!Entry)
707 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000708
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000709 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000710}
711
712void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000713 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
714 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000715 Entry = EmitForwardFunctionDefinition(D);
716 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000717 // If the types mismatch then we have to rewrite the definition.
718 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
719 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000720 // Otherwise, we have a definition after a prototype with the wrong type.
721 // F is the Function* for the one with the wrong type, we must make a new
722 // Function* and update everything that used F (a declaration) with the new
723 // Function* (which will be a definition).
724 //
725 // This happens if there is a prototype for a function (e.g. "int f()") and
726 // then a definition of a different type (e.g. "int f(int x)"). Start by
727 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000728 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
729 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000730
731 // Replace uses of F with the Function we will endow with a body.
732 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000733 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
734 Entry->replaceAllUsesWith(NewPtrForOldDecl);
735
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000736 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000737 // FIXME: Add GlobalValue->eraseFromParent().
738 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
739 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
740 F->eraseFromParent();
741 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
742 GA->eraseFromParent();
743 } else {
744 assert(0 && "Invalid global variable type.");
745 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000746
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000747 Entry = NewFn;
748 }
749 }
750
751 if (D->getAttr<AliasAttr>()) {
752 ;
753 } else {
754 llvm::Function *Fn = cast<llvm::Function>(Entry);
755 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000756
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000757 // Set attributes specific to definition.
758 // FIXME: This needs to be cleaned up by clearly emitting the
759 // declaration / definition at separate times.
760 if (!Features.Exceptions)
761 Fn->addParamAttr(0, llvm::ParamAttr::NoUnwind);
762
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000763 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
764 AddGlobalCtor(Fn, CA->getPriority());
765 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
766 AddGlobalDtor(Fn, DA->getPriority());
767 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000768 }
769}
770
Chris Lattnerc5b88062008-02-06 05:08:19 +0000771void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
772 // Make sure that this type is translated.
773 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000774}
775
776
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000777/// getBuiltinLibFunction
778llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000779 if (BuiltinID > BuiltinFunctions.size())
780 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000781
Chris Lattner1426fec2007-12-13 00:38:03 +0000782 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
783 // a slot for it.
784 assert(BuiltinID && "Invalid Builtin ID");
785 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000786 if (FunctionSlot)
787 return FunctionSlot;
788
789 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
790
791 // Get the name, skip over the __builtin_ prefix.
792 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
793
794 // Get the type for the builtin.
795 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
796 const llvm::FunctionType *Ty =
797 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
798
799 // FIXME: This has a serious problem with code like this:
800 // void abs() {}
801 // ... __builtin_abs(x);
802 // The two versions of abs will collide. The fix is for the builtin to win,
803 // and for the existing one to be turned into a constantexpr cast of the
804 // builtin. In the case where the existing one is a static function, it
805 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000806 if (llvm::Function *Existing = getModule().getFunction(Name)) {
807 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
808 return FunctionSlot = Existing;
809 assert(Existing == 0 && "FIXME: Name collision");
810 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000811
812 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000813 return FunctionSlot =
814 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
815 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000816}
817
Chris Lattner7acda7c2007-12-18 00:25:38 +0000818llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
819 unsigned NumTys) {
820 return llvm::Intrinsic::getDeclaration(&getModule(),
821 (llvm::Intrinsic::ID)IID, Tys, NumTys);
822}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000823
Reid Spencer5f016e22007-07-11 17:01:13 +0000824llvm::Function *CodeGenModule::getMemCpyFn() {
825 if (MemCpyFn) return MemCpyFn;
826 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000827 switch (Context.Target.getPointerWidth(0)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000828 default: assert(0 && "Unknown ptr width");
829 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
830 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
831 }
Chris Lattner7acda7c2007-12-18 00:25:38 +0000832 return MemCpyFn = getIntrinsic(IID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000833}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000834
Eli Friedman0c995092008-05-26 12:59:39 +0000835llvm::Function *CodeGenModule::getMemMoveFn() {
836 if (MemMoveFn) return MemMoveFn;
837 llvm::Intrinsic::ID IID;
838 switch (Context.Target.getPointerWidth(0)) {
839 default: assert(0 && "Unknown ptr width");
840 case 32: IID = llvm::Intrinsic::memmove_i32; break;
841 case 64: IID = llvm::Intrinsic::memmove_i64; break;
842 }
843 return MemMoveFn = getIntrinsic(IID);
844}
845
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000846llvm::Function *CodeGenModule::getMemSetFn() {
847 if (MemSetFn) return MemSetFn;
848 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000849 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000850 default: assert(0 && "Unknown ptr width");
851 case 32: IID = llvm::Intrinsic::memset_i32; break;
852 case 64: IID = llvm::Intrinsic::memset_i64; break;
853 }
854 return MemSetFn = getIntrinsic(IID);
855}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000856
Anton Korobeynikov20ff3102008-06-01 14:13:53 +0000857// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000858llvm::Constant *CodeGenModule::
859GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000860 llvm::StringMapEntry<llvm::Constant *> &Entry =
861 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
862
863 if (Entry.getValue())
864 return Entry.getValue();
865
866 std::vector<llvm::Constant*> Fields;
867
868 if (!CFConstantStringClassRef) {
869 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
870 Ty = llvm::ArrayType::get(Ty, 0);
871
872 CFConstantStringClassRef =
873 new llvm::GlobalVariable(Ty, false,
874 llvm::GlobalVariable::ExternalLinkage, 0,
875 "__CFConstantStringClassReference",
876 &getModule());
877 }
878
879 // Class pointer.
880 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
881 llvm::Constant *Zeros[] = { Zero, Zero };
882 llvm::Constant *C =
883 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
884 Fields.push_back(C);
885
886 // Flags.
887 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
888 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
889
890 // String pointer.
891 C = llvm::ConstantArray::get(str);
892 C = new llvm::GlobalVariable(C->getType(), true,
893 llvm::GlobalValue::InternalLinkage,
894 C, ".str", &getModule());
895
896 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
897 Fields.push_back(C);
898
899 // String length.
900 Ty = getTypes().ConvertType(getContext().LongTy);
901 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
902
903 // The struct.
904 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
905 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000906 llvm::GlobalVariable *GV =
907 new llvm::GlobalVariable(C->getType(), true,
908 llvm::GlobalVariable::InternalLinkage,
909 C, "", &getModule());
910 GV->setSection("__DATA,__cfstring");
911 Entry.setValue(GV);
912 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000913}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000914
Daniel Dunbar1e049762008-08-10 20:25:57 +0000915/// getStringForStringLiteral - Return the appropriate bytes for a
916/// string literal, properly padded to match the literal type.
917std::string CodeGenModule::getStringForStringLiteral(const StringLiteral *E) {
918 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
919 const char *StrData = E->getStrData();
920 unsigned Len = E->getByteLength();
921
922 const ConstantArrayType *CAT =
923 getContext().getAsConstantArrayType(E->getType());
924 assert(CAT && "String isn't pointer or array!");
925
926 // Resize the string to the right size
927 // FIXME: What about wchar_t strings?
928 std::string Str(StrData, StrData+Len);
929 uint64_t RealLen = CAT->getSize().getZExtValue();
930 Str.resize(RealLen, '\0');
931
932 return Str;
933}
934
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000935/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000936static llvm::Constant *GenerateStringLiteral(const std::string &str,
937 bool constant,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000938 CodeGenModule &CGM) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000939 // Create Constant for this string literal
Daniel Dunbar1e049762008-08-10 20:25:57 +0000940 llvm::Constant *C = llvm::ConstantArray::get(str);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000941
942 // Create a global variable for this string
943 C = new llvm::GlobalVariable(C->getType(), constant,
944 llvm::GlobalValue::InternalLinkage,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000945 C, ".str", &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000946 return C;
947}
948
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000949/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
950/// array containing the literal. The result is pointer to array type.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000951llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
952 // Don't share any string literals if writable-strings is turned on.
953 if (Features.WritableStrings)
954 return GenerateStringLiteral(str, false, *this);
955
956 llvm::StringMapEntry<llvm::Constant *> &Entry =
957 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
958
959 if (Entry.getValue())
960 return Entry.getValue();
961
962 // Create a global variable for this.
963 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
964 Entry.setValue(C);
965 return C;
966}