blob: cd8c90f921e8caa116e1aee82d7892836e10d010 [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,
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000037 Diagnostic &diags, bool GenerateDebugInfo,
38 bool UseMacObjCRuntime)
Chris Lattner22595b82007-12-02 01:40:18 +000039 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Eli Friedman8f08a252008-05-26 12:59:39 +000040 Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
41 CFConstantStringClassRef(0) {
Chris Lattnercbfb5512008-03-01 08:45:05 +000042 //TODO: Make this selectable at runtime
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000043 if (UseMacObjCRuntime) {
44 Runtime = CreateMacObjCRuntime(*this);
45 } else {
46 Runtime = CreateGNUObjCRuntime(*this);
47 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000048
49 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000050 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000051}
52
53CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000054 delete Runtime;
55 delete DebugInfo;
56}
57
58void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000059 EmitStatics();
Chris Lattnerb326b172008-03-30 23:03:07 +000060 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000061 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000062 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000063 EmitCtorList(GlobalCtors, "llvm.global_ctors");
64 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000065 EmitAnnotations();
Chris Lattnerb033c4a2008-04-30 16:05:42 +000066 // Run the verifier to check that the generated code is consistent.
67 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000068}
Chris Lattner4b009652007-07-25 00:24:17 +000069
Chris Lattnercf9c9d02007-12-02 07:19:18 +000070/// WarnUnsupported - Print out a warning that codegen doesn't support the
71/// specified stmt yet.
72void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
73 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
74 "cannot codegen this %0 yet");
75 SourceRange Range = S->getSourceRange();
76 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000077 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000078 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000079}
Chris Lattner0e4755d2007-12-02 06:27:33 +000080
Chris Lattner806a5f52008-01-12 07:05:38 +000081/// WarnUnsupported - Print out a warning that codegen doesn't support the
82/// specified decl yet.
83void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
84 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
85 "cannot codegen this %0 yet");
86 std::string Msg = Type;
87 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
88 &Msg, 1);
89}
90
Dan Gohman4751a3a2008-05-22 00:50:06 +000091/// setVisibility - Set the visibility for the given LLVM GlobalValue
92/// according to the given clang AST visibility value.
93void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
94 VisibilityAttr::VisibilityTypes Vis) {
95 switch (Vis) {
96 default: assert(0 && "Unknown visibility!");
97 case VisibilityAttr::DefaultVisibility:
98 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
99 break;
100 case VisibilityAttr::HiddenVisibility:
101 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
102 break;
103 case VisibilityAttr::ProtectedVisibility:
104 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
105 break;
106 }
107}
108
Chris Lattner753d2592008-03-14 17:18:18 +0000109/// AddGlobalCtor - Add a function to the list that will be called before
110/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000111void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000112 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000113 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000114}
115
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000116/// AddGlobalDtor - Add a function to the list that will be called
117/// when the module is unloaded.
118void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
119 // TODO: Type coercion of void()* types.
120 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
121}
122
123void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
124 // Ctor function type is void()*.
125 llvm::FunctionType* CtorFTy =
126 llvm::FunctionType::get(llvm::Type::VoidTy,
127 std::vector<const llvm::Type*>(),
128 false);
129 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
130
131 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000132 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000133 llvm::StructType::get(llvm::Type::Int32Ty,
134 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000135
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000136 // Construct the constructor and destructor arrays.
137 std::vector<llvm::Constant*> Ctors;
138 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
139 std::vector<llvm::Constant*> S;
140 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
141 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
142 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000143 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000144
145 if (!Ctors.empty()) {
146 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
147 new llvm::GlobalVariable(AT, false,
148 llvm::GlobalValue::AppendingLinkage,
149 llvm::ConstantArray::get(AT, Ctors),
150 GlobalName,
151 &TheModule);
152 }
Chris Lattner753d2592008-03-14 17:18:18 +0000153}
154
Nate Begeman52da5c72008-04-18 23:43:57 +0000155void CodeGenModule::EmitAnnotations() {
156 if (Annotations.empty())
157 return;
158
159 // Create a new global variable for the ConstantStruct in the Module.
160 llvm::Constant *Array =
161 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
162 Annotations.size()),
163 Annotations);
164 llvm::GlobalValue *gv =
165 new llvm::GlobalVariable(Array->getType(), false,
166 llvm::GlobalValue::AppendingLinkage, Array,
167 "llvm.global.annotations", &TheModule);
168 gv->setSection("llvm.metadata");
169}
170
Eli Friedman9be42212008-06-01 15:54:49 +0000171bool hasAggregateLLVMType(QualType T) {
172 return !T->isRealType() && !T->isPointerLikeType() &&
173 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
174}
175
Nuno Lopes78534382008-06-08 15:45:52 +0000176void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
177 llvm::GlobalValue *GV) {
178 // TODO: Set up linkage and many other things. Note, this is a simple
179 // approximation of what we really want.
180 if (FD->getStorageClass() == FunctionDecl::Static)
181 GV->setLinkage(llvm::Function::InternalLinkage);
182 else if (FD->getAttr<DLLImportAttr>())
183 GV->setLinkage(llvm::Function::DLLImportLinkage);
184 else if (FD->getAttr<DLLExportAttr>())
185 GV->setLinkage(llvm::Function::DLLExportLinkage);
186 else if (FD->getAttr<WeakAttr>() || FD->isInline())
187 GV->setLinkage(llvm::Function::WeakLinkage);
188
189 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
190 CodeGenModule::setVisibility(GV, attr->getVisibility());
191 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000192
193 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
194 // Prefaced with special LLVM marker to indicate that the name
195 // should not be munged.
196 GV->setName("\01" + ALA->getLabel());
197 }
Nuno Lopes78534382008-06-08 15:45:52 +0000198}
199
Eli Friedman9be42212008-06-01 15:54:49 +0000200void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
201 llvm::Function *F,
202 const llvm::FunctionType *FTy) {
203 unsigned FuncAttrs = 0;
204 if (FD->getAttr<NoThrowAttr>())
205 FuncAttrs |= llvm::ParamAttr::NoUnwind;
206 if (FD->getAttr<NoReturnAttr>())
207 FuncAttrs |= llvm::ParamAttr::NoReturn;
208
209 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
210 if (FuncAttrs)
211 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
212 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
213 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
214 if (AggregateReturn)
215 ParamAttrList.push_back(
216 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
217 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000218 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
219 if (FTP) {
220 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
221 QualType ParamType = FTP->getArgType(i);
222 unsigned ParamAttrs = 0;
223 if (ParamType->isRecordType())
224 ParamAttrs |= llvm::ParamAttr::ByVal;
Chris Lattner578279d2008-06-26 05:08:00 +0000225 if (ParamType->isSignedIntegerType() &&
226 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000227 ParamAttrs |= llvm::ParamAttr::SExt;
Chris Lattner578279d2008-06-26 05:08:00 +0000228 if (ParamType->isUnsignedIntegerType() &&
229 ParamType->isPromotableIntegerType())
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000230 ParamAttrs |= llvm::ParamAttr::ZExt;
231 if (ParamAttrs)
232 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
233 ParamAttrs));
234 }
Eli Friedman9be42212008-06-01 15:54:49 +0000235 }
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000236
Eli Friedman9be42212008-06-01 15:54:49 +0000237 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
238 ParamAttrList.size()));
239
240 // Set the appropriate calling convention for the Function.
241 if (FD->getAttr<FastCallAttr>())
242 F->setCallingConv(llvm::CallingConv::Fast);
243
Nuno Lopes78534382008-06-08 15:45:52 +0000244 SetGlobalValueAttributes(FD, F);
Eli Friedman9be42212008-06-01 15:54:49 +0000245}
246
Chris Lattnerb326b172008-03-30 23:03:07 +0000247void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
248 // If this is not a prototype, emit the body.
249 if (OMD->getBody())
250 CodeGenFunction(*this).GenerateObjCMethod(OMD);
251}
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000252void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
253 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner0be08822008-07-21 21:32:27 +0000254 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
255 E = PD->protocol_end(); PI != E; ++PI)
256 Protocols.push_back((*PI)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000257 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
258 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
259 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
Chris Lattner0be08822008-07-21 21:32:27 +0000260 E = PD->instmeth_end(); iter != E; iter++) {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000261 std::string TypeStr;
Chris Lattner0be08822008-07-21 21:32:27 +0000262 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000263 InstanceMethodNames.push_back(
264 GetAddrOfConstantString((*iter)->getSelector().getName()));
265 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
266 }
267 // Collect information about class methods:
268 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
269 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
270 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
271 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
272 std::string TypeStr;
273 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
274 ClassMethodNames.push_back(
275 GetAddrOfConstantString((*iter)->getSelector().getName()));
276 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
277 }
278 Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
279 InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
280}
281
282void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
283
284 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000285 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000286 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
287 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
288 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000289 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000290 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000291 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000292 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
293 }
294
295 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000296 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000297 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
298 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
299 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000300 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000301 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000302 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000303 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
304 }
305
306 // Collect the names of referenced protocols
307 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000308 const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
309 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
310 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
311 E = Protos.end(); I != E; ++I)
312 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000313
314 // Generate the category
315 Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
Chris Lattner578279d2008-06-26 05:08:00 +0000316 OCD->getName(), InstanceMethodSels, InstanceMethodTypes,
317 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000318}
319
320void CodeGenModule::EmitObjCClassImplementation(
321 const ObjCImplementationDecl *OID) {
322 // Get the superclass name.
323 const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
324 const char * SCName = NULL;
325 if (SCDecl) {
326 SCName = SCDecl->getName();
327 }
328
329 // Get the class name
330 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
331 const char * ClassName = ClassDecl->getName();
332
333 // Get the size of instances. For runtimes that support late-bound instances
334 // this should probably be something different (size just of instance
335 // varaibles in this class, not superclasses?).
336 int instanceSize = 0;
337 const llvm::Type *ObjTy;
338 if (!Runtime->LateBoundIVars()) {
339 ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
340 instanceSize = TheTargetData.getABITypeSize(ObjTy);
341 }
342
343 // Collect information about instance variables.
344 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
345 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
346 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
347 const llvm::StructLayout *Layout =
348 TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
349 ObjTy = llvm::PointerType::getUnqual(ObjTy);
350 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
351 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
352 // Store the name
353 IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
354 // Get the type encoding for this ivar
355 std::string TypeStr;
356 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
357 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
358 EncodingRecordTypes);
359 IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
360 // Get the offset
361 int offset =
362 (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
363 IvarOffsets.push_back(
364 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
365 }
366
367 // Collect information about instance methods
Chris Lattner578279d2008-06-26 05:08:00 +0000368 llvm::SmallVector<Selector, 16> InstanceMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000369 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
370 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
371 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000372 InstanceMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000373 std::string TypeStr;
374 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000375 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
376 }
377
378 // Collect information about class methods
Chris Lattner578279d2008-06-26 05:08:00 +0000379 llvm::SmallVector<Selector, 16> ClassMethodSels;
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000380 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
381 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
382 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
Chris Lattner578279d2008-06-26 05:08:00 +0000383 ClassMethodSels.push_back((*iter)->getSelector());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000384 std::string TypeStr;
385 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000386 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
387 }
388 // Collect the names of referenced protocols
389 llvm::SmallVector<std::string, 16> Protocols;
Chris Lattner8bcb5252008-07-21 18:19:38 +0000390 const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
391 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
392 E = Protos.end(); I != E; ++I)
393 Protocols.push_back((*I)->getName());
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000394
395 // Generate the category
396 Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
Chris Lattner578279d2008-06-26 05:08:00 +0000397 IvarOffsets, InstanceMethodSels, InstanceMethodTypes,
398 ClassMethodSels, ClassMethodTypes, Protocols);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000399}
400
Nate Begemanad320b62008-04-20 06:29:50 +0000401void CodeGenModule::EmitStatics() {
402 // Emit code for each used static decl encountered. Since a previously unused
403 // static decl may become used during the generation of code for a static
404 // function, iterate until no changes are made.
405 bool Changed;
406 do {
407 Changed = false;
408 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000409 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000410
411 // Check if we have used a decl with the same name
412 // FIXME: The AST should have some sort of aggregate decls or
413 // global symbol map.
Daniel Dunbarced89142008-08-06 00:03:29 +0000414 if (!GlobalDeclMap.count(D->getName()))
415 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000416
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
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000435/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000436/// 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 +0000476void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
477 bool isDef, isStatic;
478
479 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
480 isDef = (FD->isThisDeclarationADefinition() ||
481 FD->getAttr<AliasAttr>());
482 isStatic = FD->getStorageClass() == FunctionDecl::Static;
483 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
484 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
485
486 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
487 isStatic = VD->getStorageClass() == VarDecl::Static;
488 } else {
489 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000490 return;
491 }
492
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000493 // Forward declarations are emitted lazily on first use.
494 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000495 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000496
497 // If the global is a static, defer code generation until later so
498 // we can easily omit unused statics.
499 if (isStatic) {
500 StaticDecls.push_back(Global);
501 return;
502 }
503
504 // Otherwise emit the definition.
505 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000506}
507
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000508void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
509 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
510 EmitGlobalFunctionDefinition(FD);
511 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
512 EmitGlobalVarDefinition(VD);
513 } else {
514 assert(0 && "Invalid argument to EmitGlobalDefinition()");
515 }
516}
517
Daniel Dunbar2188c532008-07-30 16:32:24 +0000518 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000519 assert(D->hasGlobalStorage() && "Not a global variable");
520
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000521 QualType ASTTy = D->getType();
522 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000523 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000524
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000525 // Lookup the entry, lazily creating it if necessary.
526 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
527 if (!Entry)
528 Entry = new llvm::GlobalVariable(Ty, false,
529 llvm::GlobalValue::ExternalLinkage,
530 0, D->getName(), &getModule(), 0,
531 ASTTy.getAddressSpace());
532
Daniel Dunbar2188c532008-07-30 16:32:24 +0000533 // Make sure the result is of the correct type.
534 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000535}
536
537void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000538 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000539 QualType ASTTy = D->getType();
540 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000541
Chris Lattner4b009652007-07-25 00:24:17 +0000542 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000543 // This is a tentative definition; tentative definitions are
544 // implicitly initialized with { 0 }
545 const llvm::Type* InitTy;
546 if (ASTTy->isIncompleteArrayType()) {
547 // An incomplete array is normally [ TYPE x 0 ], but we need
548 // to fix it to [ TYPE x 1 ].
549 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
550 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
551 } else {
552 InitTy = VarTy;
553 }
554 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000555 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000556 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000557 }
558 const llvm::Type* InitType = Init->getType();
559
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000560 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
561 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
562
Eli Friedman43a0ce82008-05-30 19:50:47 +0000563 if (!GV) {
564 GV = new llvm::GlobalVariable(InitType, false,
565 llvm::GlobalValue::ExternalLinkage,
566 0, D->getName(), &getModule(), 0,
567 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000568 } else if (GV->getType() !=
569 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000570 // We have a definition after a prototype with the wrong type.
571 // We must make a new GlobalVariable* and update everything that used OldGV
572 // (a declaration or tentative definition) with the new GlobalVariable*
573 // (which will be a definition).
574 //
575 // This happens if there is a prototype for a global (e.g. "extern int x[];")
576 // and then a definition of a different type (e.g. "int x[10];"). This also
577 // happens when an initializer has a different type from the type of the
578 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000579 //
580 // FIXME: This also ends up happening if there's a definition followed by
581 // a tentative definition! (Although Sema rejects that construct
582 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000583
584 // Save the old global
585 llvm::GlobalVariable *OldGV = GV;
586
587 // Make a new global with the correct type
588 GV = new llvm::GlobalVariable(InitType, false,
589 llvm::GlobalValue::ExternalLinkage,
590 0, D->getName(), &getModule(), 0,
591 ASTTy.getAddressSpace());
592 // Steal the name of the old global
593 GV->takeName(OldGV);
594
595 // Replace all uses of the old global with the new global
596 llvm::Constant *NewPtrForOldDecl =
597 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
598 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000599
600 // Erase the old global, since it is no longer used.
601 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000602 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000603
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000604 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000605
Nate Begeman8a704172008-04-19 04:17:09 +0000606 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
607 SourceManager &SM = Context.getSourceManager();
608 AddAnnotation(EmitAnnotateAttr(GV, AA,
609 SM.getLogicalLineNumber(D->getLocation())));
610 }
611
Chris Lattner4b009652007-07-25 00:24:17 +0000612 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000613
Eli Friedman7008e9a2008-05-30 20:39:54 +0000614 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
615 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000616 if (const IncompleteArrayType* IAT =
617 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000618 Align = Context.getTypeAlign(IAT->getElementType());
619 else
620 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000621 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
622 Align = std::max(Align, AA->getAlignment());
623 }
624 GV->setAlignment(Align / 8);
625
Chris Lattner402b3372008-03-03 03:28:21 +0000626 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000627 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000628 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000629
630 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
631 // Prefaced with special LLVM marker to indicate that the name
632 // should not be munged.
633 GV->setName("\01" + ALA->getLabel());
634 }
Chris Lattner4b009652007-07-25 00:24:17 +0000635
636 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000637 if (D->getStorageClass() == VarDecl::Static)
638 GV->setLinkage(llvm::Function::InternalLinkage);
639 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000640 GV->setLinkage(llvm::Function::DLLImportLinkage);
641 else if (D->getAttr<DLLExportAttr>())
642 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000643 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000644 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000645 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000646 // FIXME: This isn't right. This should handle common linkage and other
647 // stuff.
648 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000649 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000650 case VarDecl::Auto:
651 case VarDecl::Register:
652 assert(0 && "Can't have auto or register globals");
653 case VarDecl::None:
654 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000655 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000656 break;
657 case VarDecl::Extern:
658 case VarDecl::PrivateExtern:
659 // todo: common
660 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000661 }
Chris Lattner4b009652007-07-25 00:24:17 +0000662 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000663
664 // Emit global variable debug information.
665 CGDebugInfo *DI = getDebugInfo();
666 if(DI) {
667 if(D->getLocation().isValid())
668 DI->setLocation(D->getLocation());
669 DI->EmitGlobalVariable(GV, D);
670 }
Chris Lattner4b009652007-07-25 00:24:17 +0000671}
672
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000673llvm::GlobalValue *
674CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
675 // FIXME: param attributes for sext/zext etc.
676 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
677 assert(!D->getBody() && "Unexpected alias attr on function with body.");
678
679 const std::string& aliaseeName = AA->getAliasee();
680 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
681 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
682 llvm::Function::ExternalLinkage,
683 D->getName(),
684 aliasee,
685 &getModule());
686 SetGlobalValueAttributes(D, alias);
687 return alias;
688 } else {
689 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
690 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
691 llvm::Function *F = llvm::Function::Create(FTy,
692 llvm::Function::ExternalLinkage,
693 D->getName(), &getModule());
694
695 SetFunctionAttributes(D, F, FTy);
696 return F;
697 }
698}
699
700llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000701 QualType ASTTy = D->getType();
702 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
703 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000704
705 // Lookup the entry, lazily creating it if necessary.
706 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
707 if (!Entry)
708 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000709
Daniel Dunbar2188c532008-07-30 16:32:24 +0000710 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000711}
712
713void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000714 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
715 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000716 Entry = EmitForwardFunctionDefinition(D);
717 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000718 // If the types mismatch then we have to rewrite the definition.
719 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
720 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000721 // Otherwise, we have a definition after a prototype with the wrong type.
722 // F is the Function* for the one with the wrong type, we must make a new
723 // Function* and update everything that used F (a declaration) with the new
724 // Function* (which will be a definition).
725 //
726 // This happens if there is a prototype for a function (e.g. "int f()") and
727 // then a definition of a different type (e.g. "int f(int x)"). Start by
728 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000729 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
730 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000731
732 // Replace uses of F with the Function we will endow with a body.
733 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000734 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
735 Entry->replaceAllUsesWith(NewPtrForOldDecl);
736
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000737 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000738 // FIXME: Add GlobalValue->eraseFromParent().
739 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
740 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
741 F->eraseFromParent();
742 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
743 GA->eraseFromParent();
744 } else {
745 assert(0 && "Invalid global variable type.");
746 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000747
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000748 Entry = NewFn;
749 }
750 }
751
752 if (D->getAttr<AliasAttr>()) {
753 ;
754 } else {
755 llvm::Function *Fn = cast<llvm::Function>(Entry);
756 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000757
758 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
759 AddGlobalCtor(Fn, CA->getPriority());
760 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
761 AddGlobalDtor(Fn, DA->getPriority());
762 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000763 }
764}
765
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000766void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
767 // Make sure that this type is translated.
768 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000769}
770
771
Chris Lattnerab862cc2007-08-31 04:31:45 +0000772/// getBuiltinLibFunction
773llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000774 if (BuiltinID > BuiltinFunctions.size())
775 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000776
Chris Lattner9f2d6892007-12-13 00:38:03 +0000777 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
778 // a slot for it.
779 assert(BuiltinID && "Invalid Builtin ID");
780 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000781 if (FunctionSlot)
782 return FunctionSlot;
783
784 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
785
786 // Get the name, skip over the __builtin_ prefix.
787 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
788
789 // Get the type for the builtin.
790 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
791 const llvm::FunctionType *Ty =
792 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
793
794 // FIXME: This has a serious problem with code like this:
795 // void abs() {}
796 // ... __builtin_abs(x);
797 // The two versions of abs will collide. The fix is for the builtin to win,
798 // and for the existing one to be turned into a constantexpr cast of the
799 // builtin. In the case where the existing one is a static function, it
800 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000801 if (llvm::Function *Existing = getModule().getFunction(Name)) {
802 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
803 return FunctionSlot = Existing;
804 assert(Existing == 0 && "FIXME: Name collision");
805 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000806
807 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000808 return FunctionSlot =
809 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
810 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000811}
812
Chris Lattner4b23f942007-12-18 00:25:38 +0000813llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
814 unsigned NumTys) {
815 return llvm::Intrinsic::getDeclaration(&getModule(),
816 (llvm::Intrinsic::ID)IID, Tys, NumTys);
817}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000818
Chris Lattner4b009652007-07-25 00:24:17 +0000819llvm::Function *CodeGenModule::getMemCpyFn() {
820 if (MemCpyFn) return MemCpyFn;
821 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000822 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000823 default: assert(0 && "Unknown ptr width");
824 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
825 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
826 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000827 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000828}
Anders Carlsson36a04872007-08-21 00:21:21 +0000829
Eli Friedman8f08a252008-05-26 12:59:39 +0000830llvm::Function *CodeGenModule::getMemMoveFn() {
831 if (MemMoveFn) return MemMoveFn;
832 llvm::Intrinsic::ID IID;
833 switch (Context.Target.getPointerWidth(0)) {
834 default: assert(0 && "Unknown ptr width");
835 case 32: IID = llvm::Intrinsic::memmove_i32; break;
836 case 64: IID = llvm::Intrinsic::memmove_i64; break;
837 }
838 return MemMoveFn = getIntrinsic(IID);
839}
840
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000841llvm::Function *CodeGenModule::getMemSetFn() {
842 if (MemSetFn) return MemSetFn;
843 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000844 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000845 default: assert(0 && "Unknown ptr width");
846 case 32: IID = llvm::Intrinsic::memset_i32; break;
847 case 64: IID = llvm::Intrinsic::memset_i64; break;
848 }
849 return MemSetFn = getIntrinsic(IID);
850}
Chris Lattner4b23f942007-12-18 00:25:38 +0000851
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000852// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerab862cc2007-08-31 04:31:45 +0000853llvm::Constant *CodeGenModule::
854GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000855 llvm::StringMapEntry<llvm::Constant *> &Entry =
856 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
857
858 if (Entry.getValue())
859 return Entry.getValue();
860
861 std::vector<llvm::Constant*> Fields;
862
863 if (!CFConstantStringClassRef) {
864 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
865 Ty = llvm::ArrayType::get(Ty, 0);
866
867 CFConstantStringClassRef =
868 new llvm::GlobalVariable(Ty, false,
869 llvm::GlobalVariable::ExternalLinkage, 0,
870 "__CFConstantStringClassReference",
871 &getModule());
872 }
873
874 // Class pointer.
875 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
876 llvm::Constant *Zeros[] = { Zero, Zero };
877 llvm::Constant *C =
878 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
879 Fields.push_back(C);
880
881 // Flags.
882 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
883 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
884
885 // String pointer.
886 C = llvm::ConstantArray::get(str);
887 C = new llvm::GlobalVariable(C->getType(), true,
888 llvm::GlobalValue::InternalLinkage,
889 C, ".str", &getModule());
890
891 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
892 Fields.push_back(C);
893
894 // String length.
895 Ty = getTypes().ConvertType(getContext().LongTy);
896 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
897
898 // The struct.
899 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
900 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000901 llvm::GlobalVariable *GV =
902 new llvm::GlobalVariable(C->getType(), true,
903 llvm::GlobalVariable::InternalLinkage,
904 C, "", &getModule());
905 GV->setSection("__DATA,__cfstring");
906 Entry.setValue(GV);
907 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000908}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000909
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000910/// getStringForStringLiteral - Return the appropriate bytes for a
911/// string literal, properly padded to match the literal type.
912std::string CodeGenModule::getStringForStringLiteral(const StringLiteral *E) {
913 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
914 const char *StrData = E->getStrData();
915 unsigned Len = E->getByteLength();
916
917 const ConstantArrayType *CAT =
918 getContext().getAsConstantArrayType(E->getType());
919 assert(CAT && "String isn't pointer or array!");
920
921 // Resize the string to the right size
922 // FIXME: What about wchar_t strings?
923 std::string Str(StrData, StrData+Len);
924 uint64_t RealLen = CAT->getSize().getZExtValue();
925 Str.resize(RealLen, '\0');
926
927 return Str;
928}
929
Chris Lattnera6dcce32008-02-11 00:02:17 +0000930/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000931static llvm::Constant *GenerateStringLiteral(const std::string &str,
932 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000933 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000934 // Create Constant for this string literal
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000935 llvm::Constant *C = llvm::ConstantArray::get(str);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000936
937 // Create a global variable for this string
938 C = new llvm::GlobalVariable(C->getType(), constant,
939 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000940 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000941 return C;
942}
943
Chris Lattnera6dcce32008-02-11 00:02:17 +0000944/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
945/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000946llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
947 // Don't share any string literals if writable-strings is turned on.
948 if (Features.WritableStrings)
949 return GenerateStringLiteral(str, false, *this);
950
951 llvm::StringMapEntry<llvm::Constant *> &Entry =
952 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
953
954 if (Entry.getValue())
955 return Entry.getValue();
956
957 // Create a global variable for this.
958 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
959 Entry.setValue(C);
960 return C;
961}