blob: 1e91ac2f25263ce043c3f1f8ff937ff4a2cb4d04 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000019#include "clang/Basic/Diagnostic.h"
Chris Lattnerdb6be562007-11-28 05:34:05 +000020#include "clang/Basic/LangOptions.h"
Nate Begeman8a704172008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000023#include "llvm/CallingConv.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000029#include "llvm/Analysis/Verifier.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000030#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000031using namespace clang;
32using namespace CodeGen;
33
34
Chris Lattnerdb6be562007-11-28 05:34:05 +000035CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000036 llvm::Module &M, const llvm::TargetData &TD,
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000037 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000038 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Eli Friedman8f08a252008-05-26 12:59:39 +000039 Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
40 CFConstantStringClassRef(0) {
Chris Lattnercbfb5512008-03-01 08:45:05 +000041 //TODO: Make this selectable at runtime
Chris Lattner547907c2008-06-26 04:19:03 +000042 Runtime = CreateObjCRuntime(*this);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000043
44 // If debug info generation is enabled, create the CGDebugInfo object.
45 if (GenerateDebugInfo)
46 DebugInfo = new CGDebugInfo(this);
47 else
48 DebugInfo = NULL;
Chris Lattnercbfb5512008-03-01 08:45:05 +000049}
50
51CodeGenModule::~CodeGenModule() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000052 EmitStatics();
Chris Lattnerb326b172008-03-30 23:03:07 +000053 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000054 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000055 AddGlobalCtor(ObjCInitFunction);
Chris Lattner753d2592008-03-14 17:18:18 +000056 EmitGlobalCtors();
Nate Begeman52da5c72008-04-18 23:43:57 +000057 EmitAnnotations();
Chris Lattnercbfb5512008-03-01 08:45:05 +000058 delete Runtime;
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000059 delete DebugInfo;
Chris Lattnerb033c4a2008-04-30 16:05:42 +000060 // Run the verifier to check that the generated code is consistent.
61 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000062}
Chris Lattner4b009652007-07-25 00:24:17 +000063
Chris Lattnercf9c9d02007-12-02 07:19:18 +000064/// WarnUnsupported - Print out a warning that codegen doesn't support the
65/// specified stmt yet.
66void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
67 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
68 "cannot codegen this %0 yet");
69 SourceRange Range = S->getSourceRange();
70 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000071 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000072 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000073}
Chris Lattner0e4755d2007-12-02 06:27:33 +000074
Chris Lattner806a5f52008-01-12 07:05:38 +000075/// WarnUnsupported - Print out a warning that codegen doesn't support the
76/// specified decl yet.
77void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
78 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
79 "cannot codegen this %0 yet");
80 std::string Msg = Type;
81 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
82 &Msg, 1);
83}
84
Dan Gohman4751a3a2008-05-22 00:50:06 +000085/// setVisibility - Set the visibility for the given LLVM GlobalValue
86/// according to the given clang AST visibility value.
87void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
88 VisibilityAttr::VisibilityTypes Vis) {
89 switch (Vis) {
90 default: assert(0 && "Unknown visibility!");
91 case VisibilityAttr::DefaultVisibility:
92 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
93 break;
94 case VisibilityAttr::HiddenVisibility:
95 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
96 break;
97 case VisibilityAttr::ProtectedVisibility:
98 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
99 break;
100 }
101}
102
Chris Lattner753d2592008-03-14 17:18:18 +0000103/// AddGlobalCtor - Add a function to the list that will be called before
104/// main() runs.
105void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
106 // TODO: Type coercion of void()* types.
107 GlobalCtors.push_back(Ctor);
108}
109
Chris Lattnerb326b172008-03-30 23:03:07 +0000110/// EmitGlobalCtors - Generates the array of contsturctor functions to be
111/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +0000112void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +0000113 if (GlobalCtors.empty()) return;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000114
Chris Lattner753d2592008-03-14 17:18:18 +0000115 // Get the type of @llvm.global_ctors
116 std::vector<const llvm::Type*> CtorFields;
117 CtorFields.push_back(llvm::IntegerType::get(32));
118 // Constructor function type
119 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000120 llvm::FunctionType* CtorFuncTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
122
Chris Lattner753d2592008-03-14 17:18:18 +0000123 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +0000124 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
125 llvm::StructType* CtorStructTy =
126 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000127 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +0000128 llvm::ArrayType* GlobalCtorsTy =
129 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +0000130
Chris Lattner753d2592008-03-14 17:18:18 +0000131 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000132 llvm::GlobalVariable *GlobalCtorsVal =
133 new llvm::GlobalVariable(GlobalCtorsTy, false,
134 llvm::GlobalValue::AppendingLinkage,
135 (llvm::Constant*)0, "llvm.global_ctors",
136 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000137
138 // Populate the array
139 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000140 llvm::Constant *MagicNumber =
141 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
142 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000143 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000144 E = GlobalCtors.end(); I != E; ++I) {
145 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000146 StructValues.push_back(MagicNumber);
147 StructValues.push_back(*I);
148
Chris Lattnera18c12e2008-03-19 05:24:56 +0000149 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000150 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000151
152 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
153 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000154}
155
Nate Begeman52da5c72008-04-18 23:43:57 +0000156void CodeGenModule::EmitAnnotations() {
157 if (Annotations.empty())
158 return;
159
160 // Create a new global variable for the ConstantStruct in the Module.
161 llvm::Constant *Array =
162 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
163 Annotations.size()),
164 Annotations);
165 llvm::GlobalValue *gv =
166 new llvm::GlobalVariable(Array->getType(), false,
167 llvm::GlobalValue::AppendingLinkage, Array,
168 "llvm.global.annotations", &TheModule);
169 gv->setSection("llvm.metadata");
170}
171
Eli Friedman9be42212008-06-01 15:54:49 +0000172bool hasAggregateLLVMType(QualType T) {
173 return !T->isRealType() && !T->isPointerLikeType() &&
174 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
175}
176
Nuno Lopes78534382008-06-08 15:45:52 +0000177void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
178 llvm::GlobalValue *GV) {
179 // TODO: Set up linkage and many other things. Note, this is a simple
180 // approximation of what we really want.
181 if (FD->getStorageClass() == FunctionDecl::Static)
182 GV->setLinkage(llvm::Function::InternalLinkage);
183 else if (FD->getAttr<DLLImportAttr>())
184 GV->setLinkage(llvm::Function::DLLImportLinkage);
185 else if (FD->getAttr<DLLExportAttr>())
186 GV->setLinkage(llvm::Function::DLLExportLinkage);
187 else if (FD->getAttr<WeakAttr>() || FD->isInline())
188 GV->setLinkage(llvm::Function::WeakLinkage);
189
190 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
191 CodeGenModule::setVisibility(GV, attr->getVisibility());
192 // FIXME: else handle -fvisibility
193}
194
Eli Friedman9be42212008-06-01 15:54:49 +0000195void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
196 llvm::Function *F,
197 const llvm::FunctionType *FTy) {
198 unsigned FuncAttrs = 0;
199 if (FD->getAttr<NoThrowAttr>())
200 FuncAttrs |= llvm::ParamAttr::NoUnwind;
201 if (FD->getAttr<NoReturnAttr>())
202 FuncAttrs |= llvm::ParamAttr::NoReturn;
203
204 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
205 if (FuncAttrs)
206 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
207 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
208 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
209 if (AggregateReturn)
210 ParamAttrList.push_back(
211 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
212 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000213 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
214 if (FTP) {
215 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
216 QualType ParamType = FTP->getArgType(i);
217 unsigned ParamAttrs = 0;
218 if (ParamType->isRecordType())
219 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattner578279d2008-06-26 05:08:00 +0000220 if (ParamType->isSignedIntegerType() &&
221 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000222 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattner578279d2008-06-26 05:08:00 +0000223 if (ParamType->isUnsignedIntegerType() &&
224 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000225 ParamAttrs |= llvm::ParamAttr::ZExt;
226 if (ParamAttrs)
227 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
228 ParamAttrs));
229 }
Eli Friedman9be42212008-06-01 15:54:49 +0000230 }
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000231
Eli Friedman9be42212008-06-01 15:54:49 +0000232 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
233 ParamAttrList.size()));
234
235 // Set the appropriate calling convention for the Function.
236 if (FD->getAttr<FastCallAttr>())
237 F->setCallingConv(llvm::CallingConv::Fast);
238
Nuno Lopes78534382008-06-08 15:45:52 +0000239 SetGlobalValueAttributes(FD, F);
Eli Friedman9be42212008-06-01 15:54:49 +0000240}
241
Chris Lattnerb326b172008-03-30 23:03:07 +0000242void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
243 // If this is not a prototype, emit the body.
244 if (OMD->getBody())
245 CodeGenFunction(*this).GenerateObjCMethod(OMD);
246}
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000247void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
248 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner0be08822008-07-21 21:32:27 +0000249 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
250 E = PD->protocol_end(); PI != E; ++PI)
251 Protocols.push_back((*PI)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000252 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
253 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
254 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
Chris Lattner0be08822008-07-21 21:32:27 +0000255 E = PD->instmeth_end(); iter != E; iter++) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000256 std::string TypeStr;
Chris Lattner0be08822008-07-21 21:32:27 +0000257 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000258 InstanceMethodNames.push_back(
259 GetAddrOfConstantString((*iter)->getSelector().getName()));
260 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
261 }
262 // Collect information about class methods:
263 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
264 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
265 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
266 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
267 std::string TypeStr;
268 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
269 ClassMethodNames.push_back(
270 GetAddrOfConstantString((*iter)->getSelector().getName()));
271 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
272 }
273 Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
274 InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
275}
276
277void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
278
279 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000280 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000281 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
282 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
283 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000284 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000285 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000286 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000287 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
288 }
289
290 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000291 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000292 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
293 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
294 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000295 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000296 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000297 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000298 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
299 }
300
301 // Collect the names of referenced protocols
302 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000303 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
304 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
305 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
306 E = Protos.end(); I != E; ++I)
307 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000308
309 // Generate the category
310 Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
Chris Lattner578279d2008-06-26 05:08:00 +0000311 OCD->getName(), InstanceMethodSels, InstanceMethodTypes,
312 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000313}
314
315void CodeGenModule::EmitObjCClassImplementation(
316 const ObjCImplementationDecl *OID) {
317 // Get the superclass name.
318 const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
319 const char * SCName = NULL;
320 if (SCDecl) {
321 SCName = SCDecl->getName();
322 }
323
324 // Get the class name
325 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
326 const char * ClassName = ClassDecl->getName();
327
328 // Get the size of instances. For runtimes that support late-bound instances
329 // this should probably be something different (size just of instance
330 // varaibles in this class, not superclasses?).
331 int instanceSize = 0;
332 const llvm::Type *ObjTy;
333 if (!Runtime->LateBoundIVars()) {
334 ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
335 instanceSize = TheTargetData.getABITypeSize(ObjTy);
336 }
337
338 // Collect information about instance variables.
339 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
340 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
341 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
342 const llvm::StructLayout *Layout =
343 TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
344 ObjTy = llvm::PointerType::getUnqual(ObjTy);
345 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
346 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
347 // Store the name
348 IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
349 // Get the type encoding for this ivar
350 std::string TypeStr;
351 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
352 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
353 EncodingRecordTypes);
354 IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
355 // Get the offset
356 int offset =
357 (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
358 IvarOffsets.push_back(
359 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
360 }
361
362 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000363 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000364 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
365 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
366 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000367 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000368 std::string TypeStr;
369 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000370 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
371 }
372
373 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000374 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000375 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
376 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
377 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000378 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000379 std::string TypeStr;
380 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000381 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
382 }
383 // Collect the names of referenced protocols
384 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000385 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
386 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
387 E = Protos.end(); I != E; ++I)
388 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000389
390 // Generate the category
391 Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
Chris Lattner578279d2008-06-26 05:08:00 +0000392 IvarOffsets, InstanceMethodSels, InstanceMethodTypes,
393 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000394}
395
Nate Begemanad320b62008-04-20 06:29:50 +0000396void CodeGenModule::EmitStatics() {
397 // Emit code for each used static decl encountered. Since a previously unused
398 // static decl may become used during the generation of code for a static
399 // function, iterate until no changes are made.
400 bool Changed;
401 do {
402 Changed = false;
403 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000404 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000405
406 // Check if we have used a decl with the same name
407 // FIXME: The AST should have some sort of aggregate decls or
408 // global symbol map.
409 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
410 if (!getModule().getFunction(FD->getName()))
411 continue;
412 } else {
413 if (!getModule().getNamedGlobal(cast<VarDecl>(D)->getName()))
414 continue;
415 }
416
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000417 // Emit the definition.
418 EmitGlobalDefinition(D);
419
Nate Begemanad320b62008-04-20 06:29:50 +0000420 // Erase the used decl from the list.
421 StaticDecls[i] = StaticDecls.back();
422 StaticDecls.pop_back();
423 --i;
424 --e;
425
426 // Remember that we made a change.
427 Changed = true;
428 }
429 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000430}
431
Nate Begeman8a704172008-04-19 04:17:09 +0000432/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
433/// annotation information for a given GlobalValue. The annotation struct is
434/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
435/// GlobalValue being annotated. The second filed is thee constant string
436/// created from the AnnotateAttr's annotation. The third field is a constant
437/// string containing the name of the translation unit. The fourth field is
438/// the line number in the file of the annotated value declaration.
439///
440/// FIXME: this does not unique the annotation string constants, as llvm-gcc
441/// appears to.
442///
443llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
444 const AnnotateAttr *AA,
445 unsigned LineNo) {
446 llvm::Module *M = &getModule();
447
448 // get [N x i8] constants for the annotation string, and the filename string
449 // which are the 2nd and 3rd elements of the global annotation structure.
450 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
451 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
452 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
453 true);
454
455 // Get the two global values corresponding to the ConstantArrays we just
456 // created to hold the bytes of the strings.
457 llvm::GlobalValue *annoGV =
458 new llvm::GlobalVariable(anno->getType(), false,
459 llvm::GlobalValue::InternalLinkage, anno,
460 GV->getName() + ".str", M);
461 // translation unit name string, emitted into the llvm.metadata section.
462 llvm::GlobalValue *unitGV =
463 new llvm::GlobalVariable(unit->getType(), false,
464 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
465
466 // Create the ConstantStruct that is the global annotion.
467 llvm::Constant *Fields[4] = {
468 llvm::ConstantExpr::getBitCast(GV, SBP),
469 llvm::ConstantExpr::getBitCast(annoGV, SBP),
470 llvm::ConstantExpr::getBitCast(unitGV, SBP),
471 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
472 };
473 return llvm::ConstantStruct::get(Fields, 4, false);
474}
475
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000476/// ReplaceMapValuesWith - This is a really slow and bad function that
477/// searches for any entries in GlobalDeclMap that point to OldVal, changing
478/// them to point to NewVal. This is badbadbad, FIXME!
479void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
480 llvm::Constant *NewVal) {
481 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
482 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
483 if (I->second == OldVal) I->second = NewVal;
484}
485
486void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
487 bool isDef, isStatic;
488
489 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
490 isDef = (FD->isThisDeclarationADefinition() ||
491 FD->getAttr<AliasAttr>());
492 isStatic = FD->getStorageClass() == FunctionDecl::Static;
493 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
494 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
495
496 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
497 isStatic = VD->getStorageClass() == VarDecl::Static;
498 } else {
499 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000500 return;
501 }
502
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000503 // Forward declarations are emitted lazily on first use.
504 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000505 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000506
507 // If the global is a static, defer code generation until later so
508 // we can easily omit unused statics.
509 if (isStatic) {
510 StaticDecls.push_back(Global);
511 return;
512 }
513
514 // Otherwise emit the definition.
515 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000516}
517
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000518void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
519 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
520 EmitGlobalFunctionDefinition(FD);
521 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
522 EmitGlobalVarDefinition(VD);
523 } else {
524 assert(0 && "Invalid argument to EmitGlobalDefinition()");
525 }
526}
527
528llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000529 assert(D->hasGlobalStorage() && "Not a global variable");
530
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000531 // See if it is already in the map.
532 llvm::Constant *&Entry = GlobalDeclMap[D];
533 if (Entry) return Entry;
534
535 QualType ASTTy = D->getType();
536 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
537
538 // Check to see if the global already exists.
539 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
540
541 // If it doesn't already exist, just create and return an entry.
542 if (GV == 0) {
543 return Entry = new llvm::GlobalVariable(Ty, false,
544 llvm::GlobalValue::ExternalLinkage,
545 0, D->getName(), &getModule(), 0,
546 ASTTy.getAddressSpace());
547 }
548
549 // Otherwise, it already exists; return the existing version
550 llvm::PointerType *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
551 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
552}
553
554void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000555 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000556 QualType ASTTy = D->getType();
557 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
558 const llvm::Type *VarPtrTy =
559 llvm::PointerType::get(VarTy, ASTTy.getAddressSpace());
560
Chris Lattner4b009652007-07-25 00:24:17 +0000561 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000562 // This is a tentative definition; tentative definitions are
563 // implicitly initialized with { 0 }
564 const llvm::Type* InitTy;
565 if (ASTTy->isIncompleteArrayType()) {
566 // An incomplete array is normally [ TYPE x 0 ], but we need
567 // to fix it to [ TYPE x 1 ].
568 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
569 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
570 } else {
571 InitTy = VarTy;
572 }
573 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000574 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000575 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000576 }
577 const llvm::Type* InitType = Init->getType();
578
579 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
580
581 if (!GV) {
582 GV = new llvm::GlobalVariable(InitType, false,
583 llvm::GlobalValue::ExternalLinkage,
584 0, D->getName(), &getModule(), 0,
585 ASTTy.getAddressSpace());
586 } else if (GV->getType()->getElementType() != InitType ||
587 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
588 // We have a definition after a prototype with the wrong type.
589 // We must make a new GlobalVariable* and update everything that used OldGV
590 // (a declaration or tentative definition) with the new GlobalVariable*
591 // (which will be a definition).
592 //
593 // This happens if there is a prototype for a global (e.g. "extern int x[];")
594 // and then a definition of a different type (e.g. "int x[10];"). This also
595 // happens when an initializer has a different type from the type of the
596 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000597 //
598 // FIXME: This also ends up happening if there's a definition followed by
599 // a tentative definition! (Although Sema rejects that construct
600 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000601
602 // Save the old global
603 llvm::GlobalVariable *OldGV = GV;
604
605 // Make a new global with the correct type
606 GV = new llvm::GlobalVariable(InitType, false,
607 llvm::GlobalValue::ExternalLinkage,
608 0, D->getName(), &getModule(), 0,
609 ASTTy.getAddressSpace());
610 // Steal the name of the old global
611 GV->takeName(OldGV);
612
613 // Replace all uses of the old global with the new global
614 llvm::Constant *NewPtrForOldDecl =
615 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
616 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
617 // Make sure we don't keep around any stale references to globals
618 // FIXME: This is really slow; we need a better way to walk all
619 // the decls with the same name
620 ReplaceMapValuesWith(OldGV, NewPtrForOldDecl);
621
622 // Erase the old global, since it is no longer used.
623 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000624 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000625
Eli Friedman43a0ce82008-05-30 19:50:47 +0000626 GlobalDeclMap[D] = llvm::ConstantExpr::getBitCast(GV, VarPtrTy);
Devang Patel8b5f5302007-10-26 16:31:40 +0000627
Nate Begeman8a704172008-04-19 04:17:09 +0000628 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
629 SourceManager &SM = Context.getSourceManager();
630 AddAnnotation(EmitAnnotateAttr(GV, AA,
631 SM.getLogicalLineNumber(D->getLocation())));
632 }
633
Chris Lattner4b009652007-07-25 00:24:17 +0000634 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000635
Eli Friedman7008e9a2008-05-30 20:39:54 +0000636 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
637 unsigned Align;
638 if (const IncompleteArrayType* IAT = D->getType()->getAsIncompleteArrayType())
639 Align = Context.getTypeAlign(IAT->getElementType());
640 else
641 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000642 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
643 Align = std::max(Align, AA->getAlignment());
644 }
645 GV->setAlignment(Align / 8);
646
Chris Lattner402b3372008-03-03 03:28:21 +0000647 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000648 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000649 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000650
651 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000652 if (D->getStorageClass() == VarDecl::Static)
653 GV->setLinkage(llvm::Function::InternalLinkage);
654 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000655 GV->setLinkage(llvm::Function::DLLImportLinkage);
656 else if (D->getAttr<DLLExportAttr>())
657 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000658 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000659 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000660 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000661 // FIXME: This isn't right. This should handle common linkage and other
662 // stuff.
663 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000664 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000665 case VarDecl::Auto:
666 case VarDecl::Register:
667 assert(0 && "Can't have auto or register globals");
668 case VarDecl::None:
669 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000670 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000671 break;
672 case VarDecl::Extern:
673 case VarDecl::PrivateExtern:
674 // todo: common
675 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000676 }
Chris Lattner4b009652007-07-25 00:24:17 +0000677 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000678
679 // Emit global variable debug information.
680 CGDebugInfo *DI = getDebugInfo();
681 if(DI) {
682 if(D->getLocation().isValid())
683 DI->setLocation(D->getLocation());
684 DI->EmitGlobalVariable(GV, D);
685 }
Chris Lattner4b009652007-07-25 00:24:17 +0000686}
687
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000688llvm::GlobalValue *
689CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
690 // FIXME: param attributes for sext/zext etc.
691 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
692 assert(!D->getBody() && "Unexpected alias attr on function with body.");
693
694 const std::string& aliaseeName = AA->getAliasee();
695 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
696 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
697 llvm::Function::ExternalLinkage,
698 D->getName(),
699 aliasee,
700 &getModule());
701 SetGlobalValueAttributes(D, alias);
702 return alias;
703 } else {
704 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
705 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
706 llvm::Function *F = llvm::Function::Create(FTy,
707 llvm::Function::ExternalLinkage,
708 D->getName(), &getModule());
709
710 SetFunctionAttributes(D, F, FTy);
711 return F;
712 }
713}
714
715llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
716 // See if it is already in the map. If so, just return it.
717 llvm::Constant *&Entry = GlobalDeclMap[D];
718 if (Entry) return Entry;
719
720 // Check to see if the function already exists; this occurs when
721 // this decl shadows a previous one. If it exists we bitcast it to
722 // the proper type for this decl and return.
723 llvm::Function *F = getModule().getFunction(D->getName());
724 if (F) {
725 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
726 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
727 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
728 }
729
730 // It doesn't exist; create and return an entry.
731 return Entry = EmitForwardFunctionDefinition(D);
732}
733
734void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
735 llvm::Constant *&Entry = GlobalDeclMap[D];
736
737 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
738 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
739
740 // Check to see if the function already exists.
741 llvm::Function *F = getModule().getFunction(D->getName());
742
743 // If it doesn't already exist, just create and return an entry.
744 if (F == 0) {
745 Entry = EmitForwardFunctionDefinition(D);
746 } else {
747 // If the pointer type matches, just return it.
748 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
749 if (PFTy == F->getType()) {
750 Entry = F;
751 } else {
752 // Otherwise, we have a definition after a prototype with the wrong type.
753 // F is the Function* for the one with the wrong type, we must make a new
754 // Function* and update everything that used F (a declaration) with the new
755 // Function* (which will be a definition).
756 //
757 // This happens if there is a prototype for a function (e.g. "int f()") and
758 // then a definition of a different type (e.g. "int f(int x)"). Start by
759 // making a new function of the correct type, RAUW, then steal the name.
760 llvm::Function *NewFn = llvm::Function::Create(FTy,
761 llvm::Function::ExternalLinkage,
762 "", &getModule());
763 NewFn->takeName(F);
764
765 // Replace uses of F with the Function we will endow with a body.
766 llvm::Constant *NewPtrForOldDecl =
767 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
768 F->replaceAllUsesWith(NewPtrForOldDecl);
769
770 // FIXME: Update the globaldeclmap for the previous decl of this name. We
771 // really want a way to walk all of these, but we don't have it yet. This
772 // is incredibly slow!
773 ReplaceMapValuesWith(F, NewPtrForOldDecl);
774
775 // Ok, delete the old function now, which is dead.
776 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
777 F->eraseFromParent();
778
779 SetFunctionAttributes(D, NewFn, FTy);
780 // Return the new function which has the right type.
781 Entry = NewFn;
782 }
783 }
784
785 if (D->getAttr<AliasAttr>()) {
786 ;
787 } else {
788 llvm::Function *Fn = cast<llvm::Function>(Entry);
789 CodeGenFunction(*this).GenerateCode(D, Fn);
790 }
791}
792
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000793void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
794 // Make sure that this type is translated.
795 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000796}
797
798
Chris Lattnerab862cc2007-08-31 04:31:45 +0000799/// getBuiltinLibFunction
800llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000801 if (BuiltinID > BuiltinFunctions.size())
802 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000803
Chris Lattner9f2d6892007-12-13 00:38:03 +0000804 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
805 // a slot for it.
806 assert(BuiltinID && "Invalid Builtin ID");
807 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000808 if (FunctionSlot)
809 return FunctionSlot;
810
811 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
812
813 // Get the name, skip over the __builtin_ prefix.
814 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
815
816 // Get the type for the builtin.
817 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
818 const llvm::FunctionType *Ty =
819 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
820
821 // FIXME: This has a serious problem with code like this:
822 // void abs() {}
823 // ... __builtin_abs(x);
824 // The two versions of abs will collide. The fix is for the builtin to win,
825 // and for the existing one to be turned into a constantexpr cast of the
826 // builtin. In the case where the existing one is a static function, it
827 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000828 if (llvm::Function *Existing = getModule().getFunction(Name)) {
829 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
830 return FunctionSlot = Existing;
831 assert(Existing == 0 && "FIXME: Name collision");
832 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000833
834 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000835 return FunctionSlot =
836 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
837 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000838}
839
Chris Lattner4b23f942007-12-18 00:25:38 +0000840llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
841 unsigned NumTys) {
842 return llvm::Intrinsic::getDeclaration(&getModule(),
843 (llvm::Intrinsic::ID)IID, Tys, NumTys);
844}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000845
Chris Lattner4b009652007-07-25 00:24:17 +0000846llvm::Function *CodeGenModule::getMemCpyFn() {
847 if (MemCpyFn) return MemCpyFn;
848 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000849 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000850 default: assert(0 && "Unknown ptr width");
851 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
852 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
853 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000854 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000855}
Anders Carlsson36a04872007-08-21 00:21:21 +0000856
Eli Friedman8f08a252008-05-26 12:59:39 +0000857llvm::Function *CodeGenModule::getMemMoveFn() {
858 if (MemMoveFn) return MemMoveFn;
859 llvm::Intrinsic::ID IID;
860 switch (Context.Target.getPointerWidth(0)) {
861 default: assert(0 && "Unknown ptr width");
862 case 32: IID = llvm::Intrinsic::memmove_i32; break;
863 case 64: IID = llvm::Intrinsic::memmove_i64; break;
864 }
865 return MemMoveFn = getIntrinsic(IID);
866}
867
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000868llvm::Function *CodeGenModule::getMemSetFn() {
869 if (MemSetFn) return MemSetFn;
870 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000871 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000872 default: assert(0 && "Unknown ptr width");
873 case 32: IID = llvm::Intrinsic::memset_i32; break;
874 case 64: IID = llvm::Intrinsic::memset_i64; break;
875 }
876 return MemSetFn = getIntrinsic(IID);
877}
Chris Lattner4b23f942007-12-18 00:25:38 +0000878
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000879// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerab862cc2007-08-31 04:31:45 +0000880llvm::Constant *CodeGenModule::
881GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000882 llvm::StringMapEntry<llvm::Constant *> &Entry =
883 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
884
885 if (Entry.getValue())
886 return Entry.getValue();
887
888 std::vector<llvm::Constant*> Fields;
889
890 if (!CFConstantStringClassRef) {
891 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
892 Ty = llvm::ArrayType::get(Ty, 0);
893
894 CFConstantStringClassRef =
895 new llvm::GlobalVariable(Ty, false,
896 llvm::GlobalVariable::ExternalLinkage, 0,
897 "__CFConstantStringClassReference",
898 &getModule());
899 }
900
901 // Class pointer.
902 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
903 llvm::Constant *Zeros[] = { Zero, Zero };
904 llvm::Constant *C =
905 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
906 Fields.push_back(C);
907
908 // Flags.
909 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
910 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
911
912 // String pointer.
913 C = llvm::ConstantArray::get(str);
914 C = new llvm::GlobalVariable(C->getType(), true,
915 llvm::GlobalValue::InternalLinkage,
916 C, ".str", &getModule());
917
918 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
919 Fields.push_back(C);
920
921 // String length.
922 Ty = getTypes().ConvertType(getContext().LongTy);
923 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
924
925 // The struct.
926 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
927 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000928 llvm::GlobalVariable *GV =
929 new llvm::GlobalVariable(C->getType(), true,
930 llvm::GlobalVariable::InternalLinkage,
931 C, "", &getModule());
932 GV->setSection("__DATA,__cfstring");
933 Entry.setValue(GV);
934 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000935}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000936
Chris Lattnera6dcce32008-02-11 00:02:17 +0000937/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000938static llvm::Constant *GenerateStringLiteral(const std::string &str,
939 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000940 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000941 // Create Constant for this string literal
942 llvm::Constant *C=llvm::ConstantArray::get(str);
943
944 // Create a global variable for this string
945 C = new llvm::GlobalVariable(C->getType(), constant,
946 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000947 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000948 return C;
949}
950
Chris Lattnera6dcce32008-02-11 00:02:17 +0000951/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
952/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000953llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
954 // Don't share any string literals if writable-strings is turned on.
955 if (Features.WritableStrings)
956 return GenerateStringLiteral(str, false, *this);
957
958 llvm::StringMapEntry<llvm::Constant *> &Entry =
959 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
960
961 if (Entry.getValue())
962 return Entry.getValue();
963
964 // Create a global variable for this.
965 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
966 Entry.setValue(C);
967 return C;
968}