blob: f575300b6dd5b19c8a2ce1f4c02c3e331f0dce84 [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"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000017#include "CGObjCRuntime.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000020#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000023#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000024#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000026#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000027#include "llvm/Analysis/Verifier.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29using namespace CodeGen;
30
31
Chris Lattnerdb6be562007-11-28 05:34:05 +000032CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000033 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000034 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000035 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000036 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman8f08a252008-05-26 12:59:39 +000037 CFConstantStringClassRef(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000038
39 if (Features.ObjC1) {
Daniel Dunbar1be1df32008-08-11 21:35:06 +000040 if (Features.NeXTRuntime) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000041 Runtime = CreateMacObjCRuntime(*this);
42 } else {
43 Runtime = CreateGNUObjCRuntime(*this);
44 }
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000045 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000046
47 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000048 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000049}
50
51CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000052 delete Runtime;
53 delete DebugInfo;
54}
55
56void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000057 EmitStatics();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000058 if (Runtime)
59 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
60 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000061 EmitCtorList(GlobalCtors, "llvm.global_ctors");
62 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000063 EmitAnnotations();
Chris Lattnerb033c4a2008-04-30 16:05:42 +000064 // Run the verifier to check that the generated code is consistent.
65 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000066}
Chris Lattner4b009652007-07-25 00:24:17 +000067
Chris Lattnercf9c9d02007-12-02 07:19:18 +000068/// WarnUnsupported - Print out a warning that codegen doesn't support the
69/// specified stmt yet.
70void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
71 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
72 "cannot codegen this %0 yet");
73 SourceRange Range = S->getSourceRange();
74 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000075 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000076 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000077}
Chris Lattner0e4755d2007-12-02 06:27:33 +000078
Chris Lattner806a5f52008-01-12 07:05:38 +000079/// WarnUnsupported - Print out a warning that codegen doesn't support the
80/// specified decl yet.
81void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
82 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
83 "cannot codegen this %0 yet");
84 std::string Msg = Type;
85 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
86 &Msg, 1);
87}
88
Dan Gohman4751a3a2008-05-22 00:50:06 +000089/// setVisibility - Set the visibility for the given LLVM GlobalValue
90/// according to the given clang AST visibility value.
91void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
92 VisibilityAttr::VisibilityTypes Vis) {
93 switch (Vis) {
94 default: assert(0 && "Unknown visibility!");
95 case VisibilityAttr::DefaultVisibility:
96 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
97 break;
98 case VisibilityAttr::HiddenVisibility:
99 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
100 break;
101 case VisibilityAttr::ProtectedVisibility:
102 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
103 break;
104 }
105}
106
Chris Lattner753d2592008-03-14 17:18:18 +0000107/// AddGlobalCtor - Add a function to the list that will be called before
108/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000109void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000110 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000111 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000112}
113
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000114/// AddGlobalDtor - Add a function to the list that will be called
115/// when the module is unloaded.
116void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
117 // TODO: Type coercion of void()* types.
118 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
119}
120
121void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
122 // Ctor function type is void()*.
123 llvm::FunctionType* CtorFTy =
124 llvm::FunctionType::get(llvm::Type::VoidTy,
125 std::vector<const llvm::Type*>(),
126 false);
127 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
128
129 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000130 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000131 llvm::StructType::get(llvm::Type::Int32Ty,
132 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000133
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000134 // Construct the constructor and destructor arrays.
135 std::vector<llvm::Constant*> Ctors;
136 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
137 std::vector<llvm::Constant*> S;
138 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
139 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
140 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000141 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000142
143 if (!Ctors.empty()) {
144 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
145 new llvm::GlobalVariable(AT, false,
146 llvm::GlobalValue::AppendingLinkage,
147 llvm::ConstantArray::get(AT, Ctors),
148 GlobalName,
149 &TheModule);
150 }
Chris Lattner753d2592008-03-14 17:18:18 +0000151}
152
Nate Begeman52da5c72008-04-18 23:43:57 +0000153void CodeGenModule::EmitAnnotations() {
154 if (Annotations.empty())
155 return;
156
157 // Create a new global variable for the ConstantStruct in the Module.
158 llvm::Constant *Array =
159 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
160 Annotations.size()),
161 Annotations);
162 llvm::GlobalValue *gv =
163 new llvm::GlobalVariable(Array->getType(), false,
164 llvm::GlobalValue::AppendingLinkage, Array,
165 "llvm.global.annotations", &TheModule);
166 gv->setSection("llvm.metadata");
167}
168
Eli Friedman9be42212008-06-01 15:54:49 +0000169bool hasAggregateLLVMType(QualType T) {
170 return !T->isRealType() && !T->isPointerLikeType() &&
171 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
172}
173
Nuno Lopes78534382008-06-08 15:45:52 +0000174void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
175 llvm::GlobalValue *GV) {
176 // TODO: Set up linkage and many other things. Note, this is a simple
177 // approximation of what we really want.
178 if (FD->getStorageClass() == FunctionDecl::Static)
179 GV->setLinkage(llvm::Function::InternalLinkage);
180 else if (FD->getAttr<DLLImportAttr>())
181 GV->setLinkage(llvm::Function::DLLImportLinkage);
182 else if (FD->getAttr<DLLExportAttr>())
183 GV->setLinkage(llvm::Function::DLLExportLinkage);
184 else if (FD->getAttr<WeakAttr>() || FD->isInline())
185 GV->setLinkage(llvm::Function::WeakLinkage);
186
187 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
188 CodeGenModule::setVisibility(GV, attr->getVisibility());
189 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000190
191 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
192 // Prefaced with special LLVM marker to indicate that the name
193 // should not be munged.
194 GV->setName("\01" + ALA->getLabel());
195 }
Nuno Lopes78534382008-06-08 15:45:52 +0000196}
197
Eli Friedman9be42212008-06-01 15:54:49 +0000198void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
199 llvm::Function *F,
200 const llvm::FunctionType *FTy) {
201 unsigned FuncAttrs = 0;
202 if (FD->getAttr<NoThrowAttr>())
203 FuncAttrs |= llvm::ParamAttr::NoUnwind;
204 if (FD->getAttr<NoReturnAttr>())
205 FuncAttrs |= llvm::ParamAttr::NoReturn;
206
207 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
208 if (FuncAttrs)
209 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
210 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
211 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
212 if (AggregateReturn)
213 ParamAttrList.push_back(
214 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
215 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000216 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
217 if (FTP) {
218 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
219 QualType ParamType = FTP->getArgType(i);
220 unsigned ParamAttrs = 0;
221 if (ParamType->isRecordType())
222 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattner578279d2008-06-26 05:08:00 +0000223 if (ParamType->isSignedIntegerType() &&
224 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000225 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattner578279d2008-06-26 05:08:00 +0000226 if (ParamType->isUnsignedIntegerType() &&
227 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000228 ParamAttrs |= llvm::ParamAttr::ZExt;
229 if (ParamAttrs)
230 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
231 ParamAttrs));
232 }
Eli Friedman9be42212008-06-01 15:54:49 +0000233 }
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000234
Eli Friedman9be42212008-06-01 15:54:49 +0000235 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
236 ParamAttrList.size()));
237
238 // Set the appropriate calling convention for the Function.
239 if (FD->getAttr<FastCallAttr>())
240 F->setCallingConv(llvm::CallingConv::Fast);
241
Nuno Lopes78534382008-06-08 15:45:52 +0000242 SetGlobalValueAttributes(FD, F);
Eli Friedman9be42212008-06-01 15:54:49 +0000243}
244
Chris Lattnerb326b172008-03-30 23:03:07 +0000245void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
246 // If this is not a prototype, emit the body.
247 if (OMD->getBody())
248 CodeGenFunction(*this).GenerateObjCMethod(OMD);
249}
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000250void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
Daniel Dunbar84bb85f2008-08-13 00:59:25 +0000251 Runtime->GenerateProtocol(PD);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000252}
253
254void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
255
256 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000257 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000258 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
259 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
260 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000261 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000262 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000263 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000264 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
265 }
266
267 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000268 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000269 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
270 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
271 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000272 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000273 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000274 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000275 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
276 }
277
278 // Collect the names of referenced protocols
279 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000280 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
281 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
282 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
283 E = Protos.end(); I != E; ++I)
284 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000285
286 // Generate the category
287 Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
Chris Lattner578279d2008-06-26 05:08:00 +0000288 OCD->getName(), InstanceMethodSels, InstanceMethodTypes,
289 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000290}
291
292void CodeGenModule::EmitObjCClassImplementation(
293 const ObjCImplementationDecl *OID) {
294 // Get the superclass name.
295 const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
296 const char * SCName = NULL;
297 if (SCDecl) {
298 SCName = SCDecl->getName();
299 }
300
301 // Get the class name
302 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
303 const char * ClassName = ClassDecl->getName();
304
305 // Get the size of instances. For runtimes that support late-bound instances
306 // this should probably be something different (size just of instance
307 // varaibles in this class, not superclasses?).
308 int instanceSize = 0;
Mike Stump5f982852008-08-11 23:16:18 +0000309 const llvm::Type *ObjTy = 0;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000310 if (!Runtime->LateBoundIVars()) {
311 ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
312 instanceSize = TheTargetData.getABITypeSize(ObjTy);
Mike Stump5f982852008-08-11 23:16:18 +0000313 } else {
314 // This is required by newer ObjC runtimes.
315 assert(0 && "Late-bound instance variables not yet supported");
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000316 }
317
318 // Collect information about instance variables.
319 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
320 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
321 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
322 const llvm::StructLayout *Layout =
323 TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
324 ObjTy = llvm::PointerType::getUnqual(ObjTy);
325 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
326 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
327 // Store the name
328 IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
329 // Get the type encoding for this ivar
330 std::string TypeStr;
331 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
332 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
333 EncodingRecordTypes);
334 IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
335 // Get the offset
336 int offset =
337 (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
338 IvarOffsets.push_back(
339 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
340 }
341
342 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000343 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000344 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
345 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
346 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000347 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000348 std::string TypeStr;
349 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000350 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
351 }
352
353 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000354 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000355 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
356 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
357 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000358 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000359 std::string TypeStr;
360 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000361 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
362 }
363 // Collect the names of referenced protocols
364 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000365 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
366 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
367 E = Protos.end(); I != E; ++I)
368 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000369
370 // Generate the category
371 Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
Chris Lattner578279d2008-06-26 05:08:00 +0000372 IvarOffsets, InstanceMethodSels, InstanceMethodTypes,
373 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000374}
375
Nate Begemanad320b62008-04-20 06:29:50 +0000376void CodeGenModule::EmitStatics() {
377 // Emit code for each used static decl encountered. Since a previously unused
378 // static decl may become used during the generation of code for a static
379 // function, iterate until no changes are made.
380 bool Changed;
381 do {
382 Changed = false;
383 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000384 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000385
386 // Check if we have used a decl with the same name
387 // FIXME: The AST should have some sort of aggregate decls or
388 // global symbol map.
Daniel Dunbarced89142008-08-06 00:03:29 +0000389 if (!GlobalDeclMap.count(D->getName()))
390 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000391
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000392 // Emit the definition.
393 EmitGlobalDefinition(D);
394
Nate Begemanad320b62008-04-20 06:29:50 +0000395 // Erase the used decl from the list.
396 StaticDecls[i] = StaticDecls.back();
397 StaticDecls.pop_back();
398 --i;
399 --e;
400
401 // Remember that we made a change.
402 Changed = true;
403 }
404 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000405}
406
Nate Begeman8a704172008-04-19 04:17:09 +0000407/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
408/// annotation information for a given GlobalValue. The annotation struct is
409/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000410/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000411/// created from the AnnotateAttr's annotation. The third field is a constant
412/// string containing the name of the translation unit. The fourth field is
413/// the line number in the file of the annotated value declaration.
414///
415/// FIXME: this does not unique the annotation string constants, as llvm-gcc
416/// appears to.
417///
418llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
419 const AnnotateAttr *AA,
420 unsigned LineNo) {
421 llvm::Module *M = &getModule();
422
423 // get [N x i8] constants for the annotation string, and the filename string
424 // which are the 2nd and 3rd elements of the global annotation structure.
425 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
426 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
427 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
428 true);
429
430 // Get the two global values corresponding to the ConstantArrays we just
431 // created to hold the bytes of the strings.
432 llvm::GlobalValue *annoGV =
433 new llvm::GlobalVariable(anno->getType(), false,
434 llvm::GlobalValue::InternalLinkage, anno,
435 GV->getName() + ".str", M);
436 // translation unit name string, emitted into the llvm.metadata section.
437 llvm::GlobalValue *unitGV =
438 new llvm::GlobalVariable(unit->getType(), false,
439 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
440
441 // Create the ConstantStruct that is the global annotion.
442 llvm::Constant *Fields[4] = {
443 llvm::ConstantExpr::getBitCast(GV, SBP),
444 llvm::ConstantExpr::getBitCast(annoGV, SBP),
445 llvm::ConstantExpr::getBitCast(unitGV, SBP),
446 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
447 };
448 return llvm::ConstantStruct::get(Fields, 4, false);
449}
450
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000451void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
452 bool isDef, isStatic;
453
454 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
455 isDef = (FD->isThisDeclarationADefinition() ||
456 FD->getAttr<AliasAttr>());
457 isStatic = FD->getStorageClass() == FunctionDecl::Static;
458 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
459 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
460
461 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
462 isStatic = VD->getStorageClass() == VarDecl::Static;
463 } else {
464 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000465 return;
466 }
467
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000468 // Forward declarations are emitted lazily on first use.
469 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000470 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000471
472 // If the global is a static, defer code generation until later so
473 // we can easily omit unused statics.
474 if (isStatic) {
475 StaticDecls.push_back(Global);
476 return;
477 }
478
479 // Otherwise emit the definition.
480 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000481}
482
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000483void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
484 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
485 EmitGlobalFunctionDefinition(FD);
486 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
487 EmitGlobalVarDefinition(VD);
488 } else {
489 assert(0 && "Invalid argument to EmitGlobalDefinition()");
490 }
491}
492
Daniel Dunbar2188c532008-07-30 16:32:24 +0000493 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000494 assert(D->hasGlobalStorage() && "Not a global variable");
495
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000496 QualType ASTTy = D->getType();
497 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000498 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000499
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000500 // Lookup the entry, lazily creating it if necessary.
501 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
502 if (!Entry)
503 Entry = new llvm::GlobalVariable(Ty, false,
504 llvm::GlobalValue::ExternalLinkage,
505 0, D->getName(), &getModule(), 0,
506 ASTTy.getAddressSpace());
507
Daniel Dunbar2188c532008-07-30 16:32:24 +0000508 // Make sure the result is of the correct type.
509 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000510}
511
512void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000513 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000514 QualType ASTTy = D->getType();
515 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000516
Chris Lattner4b009652007-07-25 00:24:17 +0000517 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000518 // This is a tentative definition; tentative definitions are
519 // implicitly initialized with { 0 }
520 const llvm::Type* InitTy;
521 if (ASTTy->isIncompleteArrayType()) {
522 // An incomplete array is normally [ TYPE x 0 ], but we need
523 // to fix it to [ TYPE x 1 ].
524 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
525 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
526 } else {
527 InitTy = VarTy;
528 }
529 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000530 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000531 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000532 }
533 const llvm::Type* InitType = Init->getType();
534
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000535 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
536 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
537
Eli Friedman43a0ce82008-05-30 19:50:47 +0000538 if (!GV) {
539 GV = new llvm::GlobalVariable(InitType, false,
540 llvm::GlobalValue::ExternalLinkage,
541 0, D->getName(), &getModule(), 0,
542 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000543 } else if (GV->getType() !=
544 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000545 // We have a definition after a prototype with the wrong type.
546 // We must make a new GlobalVariable* and update everything that used OldGV
547 // (a declaration or tentative definition) with the new GlobalVariable*
548 // (which will be a definition).
549 //
550 // This happens if there is a prototype for a global (e.g. "extern int x[];")
551 // and then a definition of a different type (e.g. "int x[10];"). This also
552 // happens when an initializer has a different type from the type of the
553 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000554 //
555 // FIXME: This also ends up happening if there's a definition followed by
556 // a tentative definition! (Although Sema rejects that construct
557 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000558
559 // Save the old global
560 llvm::GlobalVariable *OldGV = GV;
561
562 // Make a new global with the correct type
563 GV = new llvm::GlobalVariable(InitType, false,
564 llvm::GlobalValue::ExternalLinkage,
565 0, D->getName(), &getModule(), 0,
566 ASTTy.getAddressSpace());
567 // Steal the name of the old global
568 GV->takeName(OldGV);
569
570 // Replace all uses of the old global with the new global
571 llvm::Constant *NewPtrForOldDecl =
572 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
573 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000574
575 // Erase the old global, since it is no longer used.
576 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000577 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000578
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000579 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000580
Nate Begeman8a704172008-04-19 04:17:09 +0000581 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
582 SourceManager &SM = Context.getSourceManager();
583 AddAnnotation(EmitAnnotateAttr(GV, AA,
584 SM.getLogicalLineNumber(D->getLocation())));
585 }
586
Chris Lattner4b009652007-07-25 00:24:17 +0000587 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000588
Eli Friedman7008e9a2008-05-30 20:39:54 +0000589 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
590 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000591 if (const IncompleteArrayType* IAT =
592 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000593 Align = Context.getTypeAlign(IAT->getElementType());
594 else
595 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000596 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
597 Align = std::max(Align, AA->getAlignment());
598 }
599 GV->setAlignment(Align / 8);
600
Chris Lattner402b3372008-03-03 03:28:21 +0000601 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000602 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000603 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000604
605 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
606 // Prefaced with special LLVM marker to indicate that the name
607 // should not be munged.
608 GV->setName("\01" + ALA->getLabel());
609 }
Chris Lattner4b009652007-07-25 00:24:17 +0000610
611 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000612 if (D->getStorageClass() == VarDecl::Static)
613 GV->setLinkage(llvm::Function::InternalLinkage);
614 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000615 GV->setLinkage(llvm::Function::DLLImportLinkage);
616 else if (D->getAttr<DLLExportAttr>())
617 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000618 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000619 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000620 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000621 // FIXME: This isn't right. This should handle common linkage and other
622 // stuff.
623 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000624 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000625 case VarDecl::Auto:
626 case VarDecl::Register:
627 assert(0 && "Can't have auto or register globals");
628 case VarDecl::None:
629 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000630 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000631 break;
632 case VarDecl::Extern:
633 case VarDecl::PrivateExtern:
634 // todo: common
635 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000636 }
Chris Lattner4b009652007-07-25 00:24:17 +0000637 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000638
639 // Emit global variable debug information.
640 CGDebugInfo *DI = getDebugInfo();
641 if(DI) {
642 if(D->getLocation().isValid())
643 DI->setLocation(D->getLocation());
644 DI->EmitGlobalVariable(GV, D);
645 }
Chris Lattner4b009652007-07-25 00:24:17 +0000646}
647
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000648llvm::GlobalValue *
649CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
650 // FIXME: param attributes for sext/zext etc.
651 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
652 assert(!D->getBody() && "Unexpected alias attr on function with body.");
653
654 const std::string& aliaseeName = AA->getAliasee();
655 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
656 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
657 llvm::Function::ExternalLinkage,
658 D->getName(),
659 aliasee,
660 &getModule());
661 SetGlobalValueAttributes(D, alias);
662 return alias;
663 } else {
664 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
665 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
666 llvm::Function *F = llvm::Function::Create(FTy,
667 llvm::Function::ExternalLinkage,
668 D->getName(), &getModule());
669
670 SetFunctionAttributes(D, F, FTy);
671 return F;
672 }
673}
674
675llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000676 QualType ASTTy = D->getType();
677 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
678 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000679
680 // Lookup the entry, lazily creating it if necessary.
681 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
682 if (!Entry)
683 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000684
Daniel Dunbar2188c532008-07-30 16:32:24 +0000685 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000686}
687
688void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000689 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
690 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000691 Entry = EmitForwardFunctionDefinition(D);
692 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000693 // If the types mismatch then we have to rewrite the definition.
694 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
695 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000696 // Otherwise, we have a definition after a prototype with the wrong type.
697 // F is the Function* for the one with the wrong type, we must make a new
698 // Function* and update everything that used F (a declaration) with the new
699 // Function* (which will be a definition).
700 //
701 // This happens if there is a prototype for a function (e.g. "int f()") and
702 // then a definition of a different type (e.g. "int f(int x)"). Start by
703 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000704 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
705 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000706
707 // Replace uses of F with the Function we will endow with a body.
708 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000709 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
710 Entry->replaceAllUsesWith(NewPtrForOldDecl);
711
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000712 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000713 // FIXME: Add GlobalValue->eraseFromParent().
714 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
715 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
716 F->eraseFromParent();
717 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
718 GA->eraseFromParent();
719 } else {
720 assert(0 && "Invalid global variable type.");
721 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000722
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000723 Entry = NewFn;
724 }
725 }
726
727 if (D->getAttr<AliasAttr>()) {
728 ;
729 } else {
730 llvm::Function *Fn = cast<llvm::Function>(Entry);
731 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000732
Daniel Dunbar91692d92008-08-11 17:36:14 +0000733 // Set attributes specific to definition.
734 // FIXME: This needs to be cleaned up by clearly emitting the
735 // declaration / definition at separate times.
736 if (!Features.Exceptions)
737 Fn->addParamAttr(0, llvm::ParamAttr::NoUnwind);
738
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000739 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
740 AddGlobalCtor(Fn, CA->getPriority());
741 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
742 AddGlobalDtor(Fn, DA->getPriority());
743 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000744 }
745}
746
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000747void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
748 // Make sure that this type is translated.
749 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000750}
751
752
Chris Lattnerab862cc2007-08-31 04:31:45 +0000753/// getBuiltinLibFunction
754llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000755 if (BuiltinID > BuiltinFunctions.size())
756 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000757
Chris Lattner9f2d6892007-12-13 00:38:03 +0000758 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
759 // a slot for it.
760 assert(BuiltinID && "Invalid Builtin ID");
761 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000762 if (FunctionSlot)
763 return FunctionSlot;
764
765 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
766
767 // Get the name, skip over the __builtin_ prefix.
768 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
769
770 // Get the type for the builtin.
771 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
772 const llvm::FunctionType *Ty =
773 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
774
775 // FIXME: This has a serious problem with code like this:
776 // void abs() {}
777 // ... __builtin_abs(x);
778 // The two versions of abs will collide. The fix is for the builtin to win,
779 // and for the existing one to be turned into a constantexpr cast of the
780 // builtin. In the case where the existing one is a static function, it
781 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000782 if (llvm::Function *Existing = getModule().getFunction(Name)) {
783 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
784 return FunctionSlot = Existing;
785 assert(Existing == 0 && "FIXME: Name collision");
786 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000787
788 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000789 return FunctionSlot =
790 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
791 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000792}
793
Chris Lattner4b23f942007-12-18 00:25:38 +0000794llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
795 unsigned NumTys) {
796 return llvm::Intrinsic::getDeclaration(&getModule(),
797 (llvm::Intrinsic::ID)IID, Tys, NumTys);
798}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000799
Chris Lattner4b009652007-07-25 00:24:17 +0000800llvm::Function *CodeGenModule::getMemCpyFn() {
801 if (MemCpyFn) return MemCpyFn;
802 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000803 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000804 default: assert(0 && "Unknown ptr width");
805 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
806 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
807 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000808 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000809}
Anders Carlsson36a04872007-08-21 00:21:21 +0000810
Eli Friedman8f08a252008-05-26 12:59:39 +0000811llvm::Function *CodeGenModule::getMemMoveFn() {
812 if (MemMoveFn) return MemMoveFn;
813 llvm::Intrinsic::ID IID;
814 switch (Context.Target.getPointerWidth(0)) {
815 default: assert(0 && "Unknown ptr width");
816 case 32: IID = llvm::Intrinsic::memmove_i32; break;
817 case 64: IID = llvm::Intrinsic::memmove_i64; break;
818 }
819 return MemMoveFn = getIntrinsic(IID);
820}
821
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000822llvm::Function *CodeGenModule::getMemSetFn() {
823 if (MemSetFn) return MemSetFn;
824 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000825 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000826 default: assert(0 && "Unknown ptr width");
827 case 32: IID = llvm::Intrinsic::memset_i32; break;
828 case 64: IID = llvm::Intrinsic::memset_i64; break;
829 }
830 return MemSetFn = getIntrinsic(IID);
831}
Chris Lattner4b23f942007-12-18 00:25:38 +0000832
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000833// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerab862cc2007-08-31 04:31:45 +0000834llvm::Constant *CodeGenModule::
835GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000836 llvm::StringMapEntry<llvm::Constant *> &Entry =
837 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
838
839 if (Entry.getValue())
840 return Entry.getValue();
841
842 std::vector<llvm::Constant*> Fields;
843
844 if (!CFConstantStringClassRef) {
845 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
846 Ty = llvm::ArrayType::get(Ty, 0);
847
848 CFConstantStringClassRef =
849 new llvm::GlobalVariable(Ty, false,
850 llvm::GlobalVariable::ExternalLinkage, 0,
851 "__CFConstantStringClassReference",
852 &getModule());
853 }
854
855 // Class pointer.
856 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
857 llvm::Constant *Zeros[] = { Zero, Zero };
858 llvm::Constant *C =
859 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
860 Fields.push_back(C);
861
862 // Flags.
863 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
864 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
865
866 // String pointer.
867 C = llvm::ConstantArray::get(str);
868 C = new llvm::GlobalVariable(C->getType(), true,
869 llvm::GlobalValue::InternalLinkage,
870 C, ".str", &getModule());
871
872 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
873 Fields.push_back(C);
874
875 // String length.
876 Ty = getTypes().ConvertType(getContext().LongTy);
877 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
878
879 // The struct.
880 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
881 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000882 llvm::GlobalVariable *GV =
883 new llvm::GlobalVariable(C->getType(), true,
884 llvm::GlobalVariable::InternalLinkage,
885 C, "", &getModule());
886 GV->setSection("__DATA,__cfstring");
887 Entry.setValue(GV);
888 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000889}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000890
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000891/// getStringForStringLiteral - Return the appropriate bytes for a
892/// string literal, properly padded to match the literal type.
893std::string CodeGenModule::getStringForStringLiteral(const StringLiteral *E) {
894 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
895 const char *StrData = E->getStrData();
896 unsigned Len = E->getByteLength();
897
898 const ConstantArrayType *CAT =
899 getContext().getAsConstantArrayType(E->getType());
900 assert(CAT && "String isn't pointer or array!");
901
902 // Resize the string to the right size
903 // FIXME: What about wchar_t strings?
904 std::string Str(StrData, StrData+Len);
905 uint64_t RealLen = CAT->getSize().getZExtValue();
906 Str.resize(RealLen, '\0');
907
908 return Str;
909}
910
Chris Lattnera6dcce32008-02-11 00:02:17 +0000911/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000912static llvm::Constant *GenerateStringLiteral(const std::string &str,
913 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000914 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000915 // Create Constant for this string literal
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000916 llvm::Constant *C = llvm::ConstantArray::get(str);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000917
918 // Create a global variable for this string
919 C = new llvm::GlobalVariable(C->getType(), constant,
920 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000921 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000922 return C;
923}
924
Chris Lattnera6dcce32008-02-11 00:02:17 +0000925/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
926/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000927llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
928 // Don't share any string literals if writable-strings is turned on.
929 if (Features.WritableStrings)
930 return GenerateStringLiteral(str, false, *this);
931
932 llvm::StringMapEntry<llvm::Constant *> &Entry =
933 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
934
935 if (Entry.getValue())
936 return Entry.getValue();
937
938 // Create a global variable for this.
939 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
940 Entry.setValue(C);
941 return C;
942}