blob: b3e721308d654bbda4a134e943645e76a7c63dde [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000019#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000022#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000023#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000025#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000026#include "llvm/Analysis/Verifier.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28using namespace CodeGen;
29
30
Chris Lattnerdb6be562007-11-28 05:34:05 +000031CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000032 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000033 Diagnostic &diags, bool GenerateDebugInfo,
34 bool UseMacObjCRuntime)
Chris Lattner22595b82007-12-02 01:40:18 +000035 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Eli Friedman8f08a252008-05-26 12:59:39 +000036 Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
37 CFConstantStringClassRef(0) {
Chris Lattnercbfb5512008-03-01 08:45:05 +000038 //TODO: Make this selectable at runtime
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000039 if (UseMacObjCRuntime) {
40 Runtime = CreateMacObjCRuntime(*this);
41 } else {
42 Runtime = CreateGNUObjCRuntime(*this);
43 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000044
45 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000046 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000047}
48
49CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000050 delete Runtime;
51 delete DebugInfo;
52}
53
54void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000055 EmitStatics();
Chris Lattnerb326b172008-03-30 23:03:07 +000056 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000057 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000058 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000059 EmitCtorList(GlobalCtors, "llvm.global_ctors");
60 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000061 EmitAnnotations();
Chris Lattnerb033c4a2008-04-30 16:05:42 +000062 // Run the verifier to check that the generated code is consistent.
63 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000064}
Chris Lattner4b009652007-07-25 00:24:17 +000065
Chris Lattnercf9c9d02007-12-02 07:19:18 +000066/// WarnUnsupported - Print out a warning that codegen doesn't support the
67/// specified stmt yet.
68void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
69 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
70 "cannot codegen this %0 yet");
71 SourceRange Range = S->getSourceRange();
72 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000073 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000074 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000075}
Chris Lattner0e4755d2007-12-02 06:27:33 +000076
Chris Lattner806a5f52008-01-12 07:05:38 +000077/// WarnUnsupported - Print out a warning that codegen doesn't support the
78/// specified decl yet.
79void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
80 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
81 "cannot codegen this %0 yet");
82 std::string Msg = Type;
83 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
84 &Msg, 1);
85}
86
Dan Gohman4751a3a2008-05-22 00:50:06 +000087/// setVisibility - Set the visibility for the given LLVM GlobalValue
88/// according to the given clang AST visibility value.
89void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
90 VisibilityAttr::VisibilityTypes Vis) {
91 switch (Vis) {
92 default: assert(0 && "Unknown visibility!");
93 case VisibilityAttr::DefaultVisibility:
94 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
95 break;
96 case VisibilityAttr::HiddenVisibility:
97 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
98 break;
99 case VisibilityAttr::ProtectedVisibility:
100 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
101 break;
102 }
103}
104
Chris Lattner753d2592008-03-14 17:18:18 +0000105/// AddGlobalCtor - Add a function to the list that will be called before
106/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000107void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000108 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000109 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000110}
111
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000112/// AddGlobalDtor - Add a function to the list that will be called
113/// when the module is unloaded.
114void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
115 // TODO: Type coercion of void()* types.
116 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
117}
118
119void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
120 // Ctor function type is void()*.
121 llvm::FunctionType* CtorFTy =
122 llvm::FunctionType::get(llvm::Type::VoidTy,
123 std::vector<const llvm::Type*>(),
124 false);
125 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
126
127 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000128 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000129 llvm::StructType::get(llvm::Type::Int32Ty,
130 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000131
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000132 // Construct the constructor and destructor arrays.
133 std::vector<llvm::Constant*> Ctors;
134 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
135 std::vector<llvm::Constant*> S;
136 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
137 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
138 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000139 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000140
141 if (!Ctors.empty()) {
142 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
143 new llvm::GlobalVariable(AT, false,
144 llvm::GlobalValue::AppendingLinkage,
145 llvm::ConstantArray::get(AT, Ctors),
146 GlobalName,
147 &TheModule);
148 }
Chris Lattner753d2592008-03-14 17:18:18 +0000149}
150
Nate Begeman52da5c72008-04-18 23:43:57 +0000151void CodeGenModule::EmitAnnotations() {
152 if (Annotations.empty())
153 return;
154
155 // Create a new global variable for the ConstantStruct in the Module.
156 llvm::Constant *Array =
157 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
158 Annotations.size()),
159 Annotations);
160 llvm::GlobalValue *gv =
161 new llvm::GlobalVariable(Array->getType(), false,
162 llvm::GlobalValue::AppendingLinkage, Array,
163 "llvm.global.annotations", &TheModule);
164 gv->setSection("llvm.metadata");
165}
166
Eli Friedman9be42212008-06-01 15:54:49 +0000167bool hasAggregateLLVMType(QualType T) {
168 return !T->isRealType() && !T->isPointerLikeType() &&
169 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
170}
171
Nuno Lopes78534382008-06-08 15:45:52 +0000172void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
173 llvm::GlobalValue *GV) {
174 // TODO: Set up linkage and many other things. Note, this is a simple
175 // approximation of what we really want.
176 if (FD->getStorageClass() == FunctionDecl::Static)
177 GV->setLinkage(llvm::Function::InternalLinkage);
178 else if (FD->getAttr<DLLImportAttr>())
179 GV->setLinkage(llvm::Function::DLLImportLinkage);
180 else if (FD->getAttr<DLLExportAttr>())
181 GV->setLinkage(llvm::Function::DLLExportLinkage);
182 else if (FD->getAttr<WeakAttr>() || FD->isInline())
183 GV->setLinkage(llvm::Function::WeakLinkage);
184
185 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
186 CodeGenModule::setVisibility(GV, attr->getVisibility());
187 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000188
189 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
190 // Prefaced with special LLVM marker to indicate that the name
191 // should not be munged.
192 GV->setName("\01" + ALA->getLabel());
193 }
Nuno Lopes78534382008-06-08 15:45:52 +0000194}
195
Eli Friedman9be42212008-06-01 15:54:49 +0000196void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
197 llvm::Function *F,
198 const llvm::FunctionType *FTy) {
199 unsigned FuncAttrs = 0;
200 if (FD->getAttr<NoThrowAttr>())
201 FuncAttrs |= llvm::ParamAttr::NoUnwind;
202 if (FD->getAttr<NoReturnAttr>())
203 FuncAttrs |= llvm::ParamAttr::NoReturn;
204
205 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
206 if (FuncAttrs)
207 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
208 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
209 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
210 if (AggregateReturn)
211 ParamAttrList.push_back(
212 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
213 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000214 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
215 if (FTP) {
216 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
217 QualType ParamType = FTP->getArgType(i);
218 unsigned ParamAttrs = 0;
219 if (ParamType->isRecordType())
220 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattner578279d2008-06-26 05:08:00 +0000221 if (ParamType->isSignedIntegerType() &&
222 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000223 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattner578279d2008-06-26 05:08:00 +0000224 if (ParamType->isUnsignedIntegerType() &&
225 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000226 ParamAttrs |= llvm::ParamAttr::ZExt;
227 if (ParamAttrs)
228 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
229 ParamAttrs));
230 }
Eli Friedman9be42212008-06-01 15:54:49 +0000231 }
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000232
Eli Friedman9be42212008-06-01 15:54:49 +0000233 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
234 ParamAttrList.size()));
235
236 // Set the appropriate calling convention for the Function.
237 if (FD->getAttr<FastCallAttr>())
238 F->setCallingConv(llvm::CallingConv::Fast);
239
Nuno Lopes78534382008-06-08 15:45:52 +0000240 SetGlobalValueAttributes(FD, F);
Eli Friedman9be42212008-06-01 15:54:49 +0000241}
242
Chris Lattnerb326b172008-03-30 23:03:07 +0000243void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
244 // If this is not a prototype, emit the body.
245 if (OMD->getBody())
246 CodeGenFunction(*this).GenerateObjCMethod(OMD);
247}
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000248void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
249 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner0be08822008-07-21 21:32:27 +0000250 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
251 E = PD->protocol_end(); PI != E; ++PI)
252 Protocols.push_back((*PI)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000253 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
254 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
255 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
Chris Lattner0be08822008-07-21 21:32:27 +0000256 E = PD->instmeth_end(); iter != E; iter++) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000257 std::string TypeStr;
Chris Lattner0be08822008-07-21 21:32:27 +0000258 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000259 InstanceMethodNames.push_back(
260 GetAddrOfConstantString((*iter)->getSelector().getName()));
261 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
262 }
263 // Collect information about class methods:
264 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
265 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
266 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
267 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
268 std::string TypeStr;
269 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
270 ClassMethodNames.push_back(
271 GetAddrOfConstantString((*iter)->getSelector().getName()));
272 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
273 }
274 Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
275 InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
276}
277
278void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
279
280 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000281 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000282 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
283 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
284 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000285 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000286 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000287 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000288 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
289 }
290
291 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000292 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000293 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
294 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
295 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000296 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000297 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000298 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000299 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
300 }
301
302 // Collect the names of referenced protocols
303 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000304 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
305 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
306 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
307 E = Protos.end(); I != E; ++I)
308 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000309
310 // Generate the category
311 Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
Chris Lattner578279d2008-06-26 05:08:00 +0000312 OCD->getName(), InstanceMethodSels, InstanceMethodTypes,
313 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000314}
315
316void CodeGenModule::EmitObjCClassImplementation(
317 const ObjCImplementationDecl *OID) {
318 // Get the superclass name.
319 const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
320 const char * SCName = NULL;
321 if (SCDecl) {
322 SCName = SCDecl->getName();
323 }
324
325 // Get the class name
326 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
327 const char * ClassName = ClassDecl->getName();
328
329 // Get the size of instances. For runtimes that support late-bound instances
330 // this should probably be something different (size just of instance
331 // varaibles in this class, not superclasses?).
332 int instanceSize = 0;
333 const llvm::Type *ObjTy;
334 if (!Runtime->LateBoundIVars()) {
335 ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
336 instanceSize = TheTargetData.getABITypeSize(ObjTy);
337 }
338
339 // Collect information about instance variables.
340 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
341 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
342 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
343 const llvm::StructLayout *Layout =
344 TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
345 ObjTy = llvm::PointerType::getUnqual(ObjTy);
346 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
347 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
348 // Store the name
349 IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
350 // Get the type encoding for this ivar
351 std::string TypeStr;
352 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
353 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
354 EncodingRecordTypes);
355 IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
356 // Get the offset
357 int offset =
358 (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
359 IvarOffsets.push_back(
360 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
361 }
362
363 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000364 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000365 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
366 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
367 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000368 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000369 std::string TypeStr;
370 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000371 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
372 }
373
374 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000375 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000376 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
377 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
378 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000379 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000380 std::string TypeStr;
381 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000382 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
383 }
384 // Collect the names of referenced protocols
385 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000386 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
387 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
388 E = Protos.end(); I != E; ++I)
389 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000390
391 // Generate the category
392 Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
Chris Lattner578279d2008-06-26 05:08:00 +0000393 IvarOffsets, InstanceMethodSels, InstanceMethodTypes,
394 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000395}
396
Nate Begemanad320b62008-04-20 06:29:50 +0000397void CodeGenModule::EmitStatics() {
398 // Emit code for each used static decl encountered. Since a previously unused
399 // static decl may become used during the generation of code for a static
400 // function, iterate until no changes are made.
401 bool Changed;
402 do {
403 Changed = false;
404 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000405 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000406
407 // Check if we have used a decl with the same name
408 // FIXME: The AST should have some sort of aggregate decls or
409 // global symbol map.
Daniel Dunbarced89142008-08-06 00:03:29 +0000410 if (!GlobalDeclMap.count(D->getName()))
411 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000412
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000413 // Emit the definition.
414 EmitGlobalDefinition(D);
415
Nate Begemanad320b62008-04-20 06:29:50 +0000416 // Erase the used decl from the list.
417 StaticDecls[i] = StaticDecls.back();
418 StaticDecls.pop_back();
419 --i;
420 --e;
421
422 // Remember that we made a change.
423 Changed = true;
424 }
425 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000426}
427
Nate Begeman8a704172008-04-19 04:17:09 +0000428/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
429/// annotation information for a given GlobalValue. The annotation struct is
430/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000431/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000432/// created from the AnnotateAttr's annotation. The third field is a constant
433/// string containing the name of the translation unit. The fourth field is
434/// the line number in the file of the annotated value declaration.
435///
436/// FIXME: this does not unique the annotation string constants, as llvm-gcc
437/// appears to.
438///
439llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
440 const AnnotateAttr *AA,
441 unsigned LineNo) {
442 llvm::Module *M = &getModule();
443
444 // get [N x i8] constants for the annotation string, and the filename string
445 // which are the 2nd and 3rd elements of the global annotation structure.
446 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
447 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
448 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
449 true);
450
451 // Get the two global values corresponding to the ConstantArrays we just
452 // created to hold the bytes of the strings.
453 llvm::GlobalValue *annoGV =
454 new llvm::GlobalVariable(anno->getType(), false,
455 llvm::GlobalValue::InternalLinkage, anno,
456 GV->getName() + ".str", M);
457 // translation unit name string, emitted into the llvm.metadata section.
458 llvm::GlobalValue *unitGV =
459 new llvm::GlobalVariable(unit->getType(), false,
460 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
461
462 // Create the ConstantStruct that is the global annotion.
463 llvm::Constant *Fields[4] = {
464 llvm::ConstantExpr::getBitCast(GV, SBP),
465 llvm::ConstantExpr::getBitCast(annoGV, SBP),
466 llvm::ConstantExpr::getBitCast(unitGV, SBP),
467 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
468 };
469 return llvm::ConstantStruct::get(Fields, 4, false);
470}
471
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000472void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
473 bool isDef, isStatic;
474
475 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
476 isDef = (FD->isThisDeclarationADefinition() ||
477 FD->getAttr<AliasAttr>());
478 isStatic = FD->getStorageClass() == FunctionDecl::Static;
479 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
480 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
481
482 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
483 isStatic = VD->getStorageClass() == VarDecl::Static;
484 } else {
485 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000486 return;
487 }
488
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000489 // Forward declarations are emitted lazily on first use.
490 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000491 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000492
493 // If the global is a static, defer code generation until later so
494 // we can easily omit unused statics.
495 if (isStatic) {
496 StaticDecls.push_back(Global);
497 return;
498 }
499
500 // Otherwise emit the definition.
501 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000502}
503
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000504void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
505 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
506 EmitGlobalFunctionDefinition(FD);
507 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
508 EmitGlobalVarDefinition(VD);
509 } else {
510 assert(0 && "Invalid argument to EmitGlobalDefinition()");
511 }
512}
513
Daniel Dunbar2188c532008-07-30 16:32:24 +0000514 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000515 assert(D->hasGlobalStorage() && "Not a global variable");
516
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000517 QualType ASTTy = D->getType();
518 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000519 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000520
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000521 // Lookup the entry, lazily creating it if necessary.
522 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
523 if (!Entry)
524 Entry = new llvm::GlobalVariable(Ty, false,
525 llvm::GlobalValue::ExternalLinkage,
526 0, D->getName(), &getModule(), 0,
527 ASTTy.getAddressSpace());
528
Daniel Dunbar2188c532008-07-30 16:32:24 +0000529 // Make sure the result is of the correct type.
530 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000531}
532
533void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000534 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000535 QualType ASTTy = D->getType();
536 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000537
Chris Lattner4b009652007-07-25 00:24:17 +0000538 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000539 // This is a tentative definition; tentative definitions are
540 // implicitly initialized with { 0 }
541 const llvm::Type* InitTy;
542 if (ASTTy->isIncompleteArrayType()) {
543 // An incomplete array is normally [ TYPE x 0 ], but we need
544 // to fix it to [ TYPE x 1 ].
545 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
546 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
547 } else {
548 InitTy = VarTy;
549 }
550 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000551 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000552 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000553 }
554 const llvm::Type* InitType = Init->getType();
555
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000556 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
557 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
558
Eli Friedman43a0ce82008-05-30 19:50:47 +0000559 if (!GV) {
560 GV = new llvm::GlobalVariable(InitType, false,
561 llvm::GlobalValue::ExternalLinkage,
562 0, D->getName(), &getModule(), 0,
563 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000564 } else if (GV->getType() !=
565 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000566 // We have a definition after a prototype with the wrong type.
567 // We must make a new GlobalVariable* and update everything that used OldGV
568 // (a declaration or tentative definition) with the new GlobalVariable*
569 // (which will be a definition).
570 //
571 // This happens if there is a prototype for a global (e.g. "extern int x[];")
572 // and then a definition of a different type (e.g. "int x[10];"). This also
573 // happens when an initializer has a different type from the type of the
574 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000575 //
576 // FIXME: This also ends up happening if there's a definition followed by
577 // a tentative definition! (Although Sema rejects that construct
578 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000579
580 // Save the old global
581 llvm::GlobalVariable *OldGV = GV;
582
583 // Make a new global with the correct type
584 GV = new llvm::GlobalVariable(InitType, false,
585 llvm::GlobalValue::ExternalLinkage,
586 0, D->getName(), &getModule(), 0,
587 ASTTy.getAddressSpace());
588 // Steal the name of the old global
589 GV->takeName(OldGV);
590
591 // Replace all uses of the old global with the new global
592 llvm::Constant *NewPtrForOldDecl =
593 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
594 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000595
596 // Erase the old global, since it is no longer used.
597 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000598 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000599
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000600 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000601
Nate Begeman8a704172008-04-19 04:17:09 +0000602 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
603 SourceManager &SM = Context.getSourceManager();
604 AddAnnotation(EmitAnnotateAttr(GV, AA,
605 SM.getLogicalLineNumber(D->getLocation())));
606 }
607
Chris Lattner4b009652007-07-25 00:24:17 +0000608 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000609
Eli Friedman7008e9a2008-05-30 20:39:54 +0000610 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
611 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000612 if (const IncompleteArrayType* IAT =
613 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000614 Align = Context.getTypeAlign(IAT->getElementType());
615 else
616 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000617 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
618 Align = std::max(Align, AA->getAlignment());
619 }
620 GV->setAlignment(Align / 8);
621
Chris Lattner402b3372008-03-03 03:28:21 +0000622 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000623 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000624 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000625
626 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
627 // Prefaced with special LLVM marker to indicate that the name
628 // should not be munged.
629 GV->setName("\01" + ALA->getLabel());
630 }
Chris Lattner4b009652007-07-25 00:24:17 +0000631
632 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000633 if (D->getStorageClass() == VarDecl::Static)
634 GV->setLinkage(llvm::Function::InternalLinkage);
635 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000636 GV->setLinkage(llvm::Function::DLLImportLinkage);
637 else if (D->getAttr<DLLExportAttr>())
638 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000639 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000640 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000641 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000642 // FIXME: This isn't right. This should handle common linkage and other
643 // stuff.
644 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000645 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000646 case VarDecl::Auto:
647 case VarDecl::Register:
648 assert(0 && "Can't have auto or register globals");
649 case VarDecl::None:
650 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000651 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000652 break;
653 case VarDecl::Extern:
654 case VarDecl::PrivateExtern:
655 // todo: common
656 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000657 }
Chris Lattner4b009652007-07-25 00:24:17 +0000658 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000659
660 // Emit global variable debug information.
661 CGDebugInfo *DI = getDebugInfo();
662 if(DI) {
663 if(D->getLocation().isValid())
664 DI->setLocation(D->getLocation());
665 DI->EmitGlobalVariable(GV, D);
666 }
Chris Lattner4b009652007-07-25 00:24:17 +0000667}
668
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000669llvm::GlobalValue *
670CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
671 // FIXME: param attributes for sext/zext etc.
672 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
673 assert(!D->getBody() && "Unexpected alias attr on function with body.");
674
675 const std::string& aliaseeName = AA->getAliasee();
676 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
677 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
678 llvm::Function::ExternalLinkage,
679 D->getName(),
680 aliasee,
681 &getModule());
682 SetGlobalValueAttributes(D, alias);
683 return alias;
684 } else {
685 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
686 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
687 llvm::Function *F = llvm::Function::Create(FTy,
688 llvm::Function::ExternalLinkage,
689 D->getName(), &getModule());
690
691 SetFunctionAttributes(D, F, FTy);
692 return F;
693 }
694}
695
696llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000697 QualType ASTTy = D->getType();
698 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
699 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000700
701 // Lookup the entry, lazily creating it if necessary.
702 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
703 if (!Entry)
704 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000705
Daniel Dunbar2188c532008-07-30 16:32:24 +0000706 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000707}
708
709void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000710 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
711 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000712 Entry = EmitForwardFunctionDefinition(D);
713 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000714 // If the types mismatch then we have to rewrite the definition.
715 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
716 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000717 // Otherwise, we have a definition after a prototype with the wrong type.
718 // F is the Function* for the one with the wrong type, we must make a new
719 // Function* and update everything that used F (a declaration) with the new
720 // Function* (which will be a definition).
721 //
722 // This happens if there is a prototype for a function (e.g. "int f()") and
723 // then a definition of a different type (e.g. "int f(int x)"). Start by
724 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000725 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
726 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000727
728 // Replace uses of F with the Function we will endow with a body.
729 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000730 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
731 Entry->replaceAllUsesWith(NewPtrForOldDecl);
732
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000733 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000734 // FIXME: Add GlobalValue->eraseFromParent().
735 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
736 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
737 F->eraseFromParent();
738 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
739 GA->eraseFromParent();
740 } else {
741 assert(0 && "Invalid global variable type.");
742 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000743
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000744 Entry = NewFn;
745 }
746 }
747
748 if (D->getAttr<AliasAttr>()) {
749 ;
750 } else {
751 llvm::Function *Fn = cast<llvm::Function>(Entry);
752 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000753
Daniel Dunbar91692d92008-08-11 17:36:14 +0000754 // Set attributes specific to definition.
755 // FIXME: This needs to be cleaned up by clearly emitting the
756 // declaration / definition at separate times.
757 if (!Features.Exceptions)
758 Fn->addParamAttr(0, llvm::ParamAttr::NoUnwind);
759
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000760 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
761 AddGlobalCtor(Fn, CA->getPriority());
762 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
763 AddGlobalDtor(Fn, DA->getPriority());
764 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000765 }
766}
767
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000768void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
769 // Make sure that this type is translated.
770 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000771}
772
773
Chris Lattnerab862cc2007-08-31 04:31:45 +0000774/// getBuiltinLibFunction
775llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000776 if (BuiltinID > BuiltinFunctions.size())
777 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000778
Chris Lattner9f2d6892007-12-13 00:38:03 +0000779 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
780 // a slot for it.
781 assert(BuiltinID && "Invalid Builtin ID");
782 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000783 if (FunctionSlot)
784 return FunctionSlot;
785
786 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
787
788 // Get the name, skip over the __builtin_ prefix.
789 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
790
791 // Get the type for the builtin.
792 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
793 const llvm::FunctionType *Ty =
794 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
795
796 // FIXME: This has a serious problem with code like this:
797 // void abs() {}
798 // ... __builtin_abs(x);
799 // The two versions of abs will collide. The fix is for the builtin to win,
800 // and for the existing one to be turned into a constantexpr cast of the
801 // builtin. In the case where the existing one is a static function, it
802 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000803 if (llvm::Function *Existing = getModule().getFunction(Name)) {
804 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
805 return FunctionSlot = Existing;
806 assert(Existing == 0 && "FIXME: Name collision");
807 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000808
809 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000810 return FunctionSlot =
811 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
812 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000813}
814
Chris Lattner4b23f942007-12-18 00:25:38 +0000815llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
816 unsigned NumTys) {
817 return llvm::Intrinsic::getDeclaration(&getModule(),
818 (llvm::Intrinsic::ID)IID, Tys, NumTys);
819}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000820
Chris Lattner4b009652007-07-25 00:24:17 +0000821llvm::Function *CodeGenModule::getMemCpyFn() {
822 if (MemCpyFn) return MemCpyFn;
823 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000824 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000825 default: assert(0 && "Unknown ptr width");
826 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
827 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
828 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000829 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000830}
Anders Carlsson36a04872007-08-21 00:21:21 +0000831
Eli Friedman8f08a252008-05-26 12:59:39 +0000832llvm::Function *CodeGenModule::getMemMoveFn() {
833 if (MemMoveFn) return MemMoveFn;
834 llvm::Intrinsic::ID IID;
835 switch (Context.Target.getPointerWidth(0)) {
836 default: assert(0 && "Unknown ptr width");
837 case 32: IID = llvm::Intrinsic::memmove_i32; break;
838 case 64: IID = llvm::Intrinsic::memmove_i64; break;
839 }
840 return MemMoveFn = getIntrinsic(IID);
841}
842
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000843llvm::Function *CodeGenModule::getMemSetFn() {
844 if (MemSetFn) return MemSetFn;
845 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000846 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000847 default: assert(0 && "Unknown ptr width");
848 case 32: IID = llvm::Intrinsic::memset_i32; break;
849 case 64: IID = llvm::Intrinsic::memset_i64; break;
850 }
851 return MemSetFn = getIntrinsic(IID);
852}
Chris Lattner4b23f942007-12-18 00:25:38 +0000853
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000854// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerab862cc2007-08-31 04:31:45 +0000855llvm::Constant *CodeGenModule::
856GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000857 llvm::StringMapEntry<llvm::Constant *> &Entry =
858 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
859
860 if (Entry.getValue())
861 return Entry.getValue();
862
863 std::vector<llvm::Constant*> Fields;
864
865 if (!CFConstantStringClassRef) {
866 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
867 Ty = llvm::ArrayType::get(Ty, 0);
868
869 CFConstantStringClassRef =
870 new llvm::GlobalVariable(Ty, false,
871 llvm::GlobalVariable::ExternalLinkage, 0,
872 "__CFConstantStringClassReference",
873 &getModule());
874 }
875
876 // Class pointer.
877 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
878 llvm::Constant *Zeros[] = { Zero, Zero };
879 llvm::Constant *C =
880 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
881 Fields.push_back(C);
882
883 // Flags.
884 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
885 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
886
887 // String pointer.
888 C = llvm::ConstantArray::get(str);
889 C = new llvm::GlobalVariable(C->getType(), true,
890 llvm::GlobalValue::InternalLinkage,
891 C, ".str", &getModule());
892
893 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
894 Fields.push_back(C);
895
896 // String length.
897 Ty = getTypes().ConvertType(getContext().LongTy);
898 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
899
900 // The struct.
901 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
902 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000903 llvm::GlobalVariable *GV =
904 new llvm::GlobalVariable(C->getType(), true,
905 llvm::GlobalVariable::InternalLinkage,
906 C, "", &getModule());
907 GV->setSection("__DATA,__cfstring");
908 Entry.setValue(GV);
909 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000910}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000911
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000912/// getStringForStringLiteral - Return the appropriate bytes for a
913/// string literal, properly padded to match the literal type.
914std::string CodeGenModule::getStringForStringLiteral(const StringLiteral *E) {
915 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
916 const char *StrData = E->getStrData();
917 unsigned Len = E->getByteLength();
918
919 const ConstantArrayType *CAT =
920 getContext().getAsConstantArrayType(E->getType());
921 assert(CAT && "String isn't pointer or array!");
922
923 // Resize the string to the right size
924 // FIXME: What about wchar_t strings?
925 std::string Str(StrData, StrData+Len);
926 uint64_t RealLen = CAT->getSize().getZExtValue();
927 Str.resize(RealLen, '\0');
928
929 return Str;
930}
931
Chris Lattnera6dcce32008-02-11 00:02:17 +0000932/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000933static llvm::Constant *GenerateStringLiteral(const std::string &str,
934 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000935 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000936 // Create Constant for this string literal
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000937 llvm::Constant *C = llvm::ConstantArray::get(str);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000938
939 // Create a global variable for this string
940 C = new llvm::GlobalVariable(C->getType(), constant,
941 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000942 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000943 return C;
944}
945
Chris Lattnera6dcce32008-02-11 00:02:17 +0000946/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
947/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000948llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
949 // Don't share any string literals if writable-strings is turned on.
950 if (Features.WritableStrings)
951 return GenerateStringLiteral(str, false, *this);
952
953 llvm::StringMapEntry<llvm::Constant *> &Entry =
954 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
955
956 if (Entry.getValue())
957 return Entry.getValue();
958
959 // Create a global variable for this.
960 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
961 Entry.setValue(C);
962 return C;
963}