blob: bc9d68a4f518bd8f587e858beeb69ea157c0dfce [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
18#include "clang/Basic/TargetInfo.h"
Chris Lattner8f32f712007-07-14 00:23:28 +000019#include "llvm/Constants.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "llvm/DerivedTypes.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000021#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "llvm/Intrinsics.h"
23using namespace clang;
24using namespace CodeGen;
25
26
Devang Patel7a4718e2007-10-31 20:01:01 +000027CodeGenModule::CodeGenModule(ASTContext &C, llvm::Module &M,
28 const llvm::TargetData &TD)
29 : Context(C), TheModule(M), TheTargetData(TD),
30 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Reid Spencer5f016e22007-07-11 17:01:13 +000031
Steve Naroff8e74c932007-09-13 21:41:19 +000032llvm::Constant *CodeGenModule::GetAddrOfGlobalDecl(const ValueDecl *D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000033 // See if it is already in the map.
34 llvm::Constant *&Entry = GlobalDeclMap[D];
35 if (Entry) return Entry;
36
37 QualType ASTTy = cast<ValueDecl>(D)->getType();
38 const llvm::Type *Ty = getTypes().ConvertType(ASTTy);
39 if (isa<FunctionDecl>(D)) {
40 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
41 // FIXME: param attributes for sext/zext etc.
42 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
43 D->getName(), &getModule());
44 }
45
46 assert(isa<FileVarDecl>(D) && "Unknown global decl!");
47
48 return Entry = new llvm::GlobalVariable(Ty, false,
49 llvm::GlobalValue::ExternalLinkage,
50 0, D->getName(), &getModule());
51}
52
Chris Lattner88a69ad2007-07-13 05:13:43 +000053void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
Reid Spencer5f016e22007-07-11 17:01:13 +000054 // If this is not a prototype, emit the body.
55 if (FD->getBody())
56 CodeGenFunction(*this).GenerateCode(FD);
57}
58
Chris Lattner75cf2882007-11-23 22:07:55 +000059static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
60 CodeGenModule& CGModule);
Devang Patel9e32d4b2007-10-30 21:27:20 +000061
Chris Lattner75cf2882007-11-23 22:07:55 +000062/// GenerateConversionToBool - Generate comparison to zero for conversion to
63/// bool
64static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
65 QualType Source) {
66 if (Source->isRealFloatingType()) {
67 // Compare against 0.0 for fp scalars.
68 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
69 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
70 Zero);
71 }
72
73 assert((Source->isIntegerType() || Source->isPointerType()) &&
74 "Unknown scalar type to convert");
75
76 // Compare against an integer or pointer null.
77 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
78 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
79}
80
81/// GenerateConstantCast - Generates a constant cast to convert the Expression
82/// into the Target type.
83static llvm::Constant *GenerateConstantCast(const Expr *Expression,
84 QualType Target,
85 CodeGenModule& CGModule) {
86 CodeGenTypes& Types = CGModule.getTypes();
87 QualType Source = Expression->getType().getCanonicalType();
88 Target = Target.getCanonicalType();
89
90 assert (!Target->isVoidType());
91
92 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGModule);
93
94 if (Source == Target)
95 return SubExpr;
96
97 // Handle conversions to bool first, they are special: comparisons against 0.
98 if (Target->isBooleanType())
99 return GenerateConversionToBool(SubExpr, Source);
100
101 const llvm::Type *SourceType = Types.ConvertType(Source);
102 const llvm::Type *TargetType = Types.ConvertType(Target);
103
104 // Ignore conversions like int -> uint.
105 if (SubExpr->getType() == TargetType)
106 return SubExpr;
107
108 // Handle pointer conversions next: pointers can only be converted to/from
109 // other pointers and integers.
110 if (isa<llvm::PointerType>(TargetType)) {
111 // The source value may be an integer, or a pointer.
112 if (isa<llvm::PointerType>(SubExpr->getType()))
113 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
114 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
115 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
116 }
117
118 if (isa<llvm::PointerType>(SourceType)) {
119 // Must be an ptr to int cast.
120 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
121 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
122 }
123
124 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
125 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
126 }
127
128 // Finally, we have the arithmetic types: real int/float.
129 if (isa<llvm::IntegerType>(SourceType)) {
130 bool InputSigned = Source->isSignedIntegerType();
131 if (isa<llvm::IntegerType>(TargetType))
132 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
133 InputSigned);
134 else if (InputSigned)
135 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
136 else
137 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
138 }
139
140 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
141 if (isa<llvm::IntegerType>(TargetType)) {
142 if (Target->isSignedIntegerType())
143 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
144 else
145 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
146 }
147
148 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
149 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
150 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
151 else
152 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
153
154 assert (!"Unsupported cast type in global intialiser.");
155 return 0;
156}
157
158/// GenerateStringLiteral -- returns a pointer to the first element of a
159/// character array containing the literal.
160static llvm::Constant *GenerateStringLiteral(const StringLiteral* E,
161 CodeGenModule& CGModule) {
162 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
163 const char *StrData = E->getStrData();
164 unsigned Len = E->getByteLength();
165
166 // FIXME: Can cache/reuse these within the module.
167 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
168
169 // Create a global variable for this.
170 C = new llvm::GlobalVariable(C->getType(), true,
171 llvm::GlobalValue::InternalLinkage,
172 C, ".str", &CGModule.getModule());
173 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
174 llvm::Constant *Zeros[] = { Zero, Zero };
175 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
176 return C;
177}
178
179/// GenerateAggregateInit - Generate a Constant initaliser for global array or
180/// struct typed variables.
181static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
182 CodeGenModule& CGModule) {
183 assert (ILE->getType()->isArrayType() || ILE->getType()->isStructureType());
184 CodeGenTypes& Types = CGModule.getTypes();
Devang Patel9e32d4b2007-10-30 21:27:20 +0000185
186 unsigned NumInitElements = ILE->getNumInits();
187
Chris Lattner75cf2882007-11-23 22:07:55 +0000188 const llvm::CompositeType *CType =
189 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
190 assert(CType);
191 std::vector<llvm::Constant*> Elts;
192
Devang Patel9e32d4b2007-10-30 21:27:20 +0000193 // Copy initializer elements.
194 unsigned i = 0;
195 for (i = 0; i < NumInitElements; ++i) {
Chris Lattner75cf2882007-11-23 22:07:55 +0000196 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGModule);
197 assert (C && "Failed to create initialiser expression");
198 Elts.push_back(C);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000199 }
200
Chris Lattner75cf2882007-11-23 22:07:55 +0000201 if (ILE->getType()->isStructureType())
202 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
203
204 // Initialising an array requires us to automatically initialise any
205 // elements that have not been initialised explicitly
206 const llvm::ArrayType *AType = cast<llvm::ArrayType>(CType);
207 assert(AType);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000208 const llvm::Type *AElemTy = AType->getElementType();
Chris Lattner75cf2882007-11-23 22:07:55 +0000209 unsigned NumArrayElements = AType->getNumElements();
210 // Initialize remaining array elements.
Devang Patel9e32d4b2007-10-30 21:27:20 +0000211 for (; i < NumArrayElements; ++i)
Chris Lattner75cf2882007-11-23 22:07:55 +0000212 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Devang Patel9e32d4b2007-10-30 21:27:20 +0000213
Chris Lattner75cf2882007-11-23 22:07:55 +0000214 return llvm::ConstantArray::get(AType, Elts);
215}
216
217/// GenerateConstantExpr - Recursively builds a constant initialiser for the
218/// given expression.
219static llvm::Constant *GenerateConstantExpr(const Expr* Expression,
220 CodeGenModule& CGModule) {
221 CodeGenTypes& Types = CGModule.getTypes();
222 ASTContext& Context = CGModule.getContext();
223 assert ((Expression->isConstantExpr(Context, 0) ||
224 Expression->getStmtClass() == Stmt::InitListExprClass) &&
225 "Only constant global initialisers are supported.");
226
227 QualType type = Expression->getType().getCanonicalType();
228
229 if (type->isIntegerType()) {
230 llvm::APSInt
231 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
232 if (Expression->isIntegerConstantExpr(Value, Context)) {
233 return llvm::ConstantInt::get(Value);
234 }
235 }
236
237 switch (Expression->getStmtClass()) {
238 // Generate constant for floating point literal values.
239 case Stmt::FloatingLiteralClass: {
240 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
241 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
242 }
243
244 // Generate constant for string literal values.
245 case Stmt::StringLiteralClass: {
246 const StringLiteral *SLiteral = cast<StringLiteral>(Expression);
247 return GenerateStringLiteral(SLiteral, CGModule);
248 }
249
250 // Elide parenthesis.
251 case Stmt::ParenExprClass:
252 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(),
253 CGModule);
254
255 // Generate constant for sizeof operator.
256 // FIXME: Need to support AlignOf
257 case Stmt::SizeOfAlignOfTypeExprClass: {
258 const SizeOfAlignOfTypeExpr *SOExpr =
259 cast<SizeOfAlignOfTypeExpr>(Expression);
260 assert (SOExpr->isSizeOf());
261 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
262 }
263
264 // Generate constant cast expressions.
265 case Stmt::CastExprClass:
266 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
267 CGModule);
268
269 case Stmt::ImplicitCastExprClass: {
270 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
271 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGModule);
272 }
273
274 // Generate a constant array access expression
275 // FIXME: Clang's semantic analysis incorrectly prevents array access in
276 // global initialisers, preventing us from testing this.
277 case Stmt::ArraySubscriptExprClass: {
278 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
279 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGModule);
280 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGModule);
281 return llvm::ConstantExpr::getExtractElement(Base, Index);
282 }
283
284 // Generate a constant expression to initialise an aggregate type, such as
285 // an array or struct.
286 case Stmt::InitListExprClass:
287 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGModule);
288
289 default:
290 assert (!"Unsupported expression in global initialiser.");
291 }
292 return 0;
293}
294
295llvm::Constant *CodeGenModule::EmitGlobalInit(const FileVarDecl *D,
296 llvm::GlobalVariable *GV) {
297 return GenerateConstantExpr(D->getInit(), *this);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000298}
299
Chris Lattner88a69ad2007-07-13 05:13:43 +0000300void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
301 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalDecl(D));
302
303 // If the storage class is external and there is no initializer, just leave it
304 // as a declaration.
305 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
306 return;
307
308 // Otherwise, convert the initializer, or use zero if appropriate.
Chris Lattner8f32f712007-07-14 00:23:28 +0000309 llvm::Constant *Init = 0;
310 if (D->getInit() == 0) {
Chris Lattner88a69ad2007-07-13 05:13:43 +0000311 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
Chris Lattner8f32f712007-07-14 00:23:28 +0000312 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiser7b660002007-10-17 15:00:17 +0000313 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner47f7dbf2007-09-04 02:34:27 +0000314 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner590b6642007-07-15 23:26:56 +0000315 if (D->getInit()->isIntegerConstantExpr(Value, Context))
Chris Lattner8f32f712007-07-14 00:23:28 +0000316 Init = llvm::ConstantInt::get(Value);
317 }
Devang Patel8e53e722007-10-26 16:31:40 +0000318
Devang Patel9e32d4b2007-10-30 21:27:20 +0000319 if (!Init)
320 Init = EmitGlobalInit(D, GV);
Devang Patel8e53e722007-10-26 16:31:40 +0000321
Devang Patel9e32d4b2007-10-30 21:27:20 +0000322 assert(Init && "FIXME: Global variable initializers unimp!");
Chris Lattner8f32f712007-07-14 00:23:28 +0000323
Chris Lattner88a69ad2007-07-13 05:13:43 +0000324 GV->setInitializer(Init);
325
326 // Set the llvm linkage type as appropriate.
327 // FIXME: This isn't right. This should handle common linkage and other
328 // stuff.
329 switch (D->getStorageClass()) {
330 case VarDecl::Auto:
331 case VarDecl::Register:
332 assert(0 && "Can't have auto or register globals");
333 case VarDecl::None:
334 case VarDecl::Extern:
335 // todo: common
336 break;
337 case VarDecl::Static:
338 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
339 break;
340 }
341}
Reid Spencer5f016e22007-07-11 17:01:13 +0000342
Chris Lattner32b266c2007-07-14 00:16:50 +0000343/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
344/// declarator chain.
345void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
346 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
347 EmitGlobalVar(D);
348}
Reid Spencer5f016e22007-07-11 17:01:13 +0000349
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000350/// getBuiltinLibFunction
351llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
352 if (BuiltinFunctions.size() <= BuiltinID)
353 BuiltinFunctions.resize(BuiltinID);
354
355 // Already available?
356 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
357 if (FunctionSlot)
358 return FunctionSlot;
359
360 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
361
362 // Get the name, skip over the __builtin_ prefix.
363 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
364
365 // Get the type for the builtin.
366 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
367 const llvm::FunctionType *Ty =
368 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
369
370 // FIXME: This has a serious problem with code like this:
371 // void abs() {}
372 // ... __builtin_abs(x);
373 // The two versions of abs will collide. The fix is for the builtin to win,
374 // and for the existing one to be turned into a constantexpr cast of the
375 // builtin. In the case where the existing one is a static function, it
376 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000377 if (llvm::Function *Existing = getModule().getFunction(Name)) {
378 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
379 return FunctionSlot = Existing;
380 assert(Existing == 0 && "FIXME: Name collision");
381 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000382
383 // FIXME: param attributes for sext/zext etc.
384 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
385 Name, &getModule());
386}
387
388
Reid Spencer5f016e22007-07-11 17:01:13 +0000389llvm::Function *CodeGenModule::getMemCpyFn() {
390 if (MemCpyFn) return MemCpyFn;
391 llvm::Intrinsic::ID IID;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000392 uint64_t Size; unsigned Align;
393 Context.Target.getPointerInfo(Size, Align, SourceLocation());
394 switch (Size) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 default: assert(0 && "Unknown ptr width");
396 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
397 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
398 }
399 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
400}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000401
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000402llvm::Constant *CodeGenModule::
403GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000404 llvm::StringMapEntry<llvm::Constant *> &Entry =
405 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
406
407 if (Entry.getValue())
408 return Entry.getValue();
409
410 std::vector<llvm::Constant*> Fields;
411
412 if (!CFConstantStringClassRef) {
413 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
414 Ty = llvm::ArrayType::get(Ty, 0);
415
416 CFConstantStringClassRef =
417 new llvm::GlobalVariable(Ty, false,
418 llvm::GlobalVariable::ExternalLinkage, 0,
419 "__CFConstantStringClassReference",
420 &getModule());
421 }
422
423 // Class pointer.
424 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
425 llvm::Constant *Zeros[] = { Zero, Zero };
426 llvm::Constant *C =
427 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
428 Fields.push_back(C);
429
430 // Flags.
431 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
432 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
433
434 // String pointer.
435 C = llvm::ConstantArray::get(str);
436 C = new llvm::GlobalVariable(C->getType(), true,
437 llvm::GlobalValue::InternalLinkage,
438 C, ".str", &getModule());
439
440 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
441 Fields.push_back(C);
442
443 // String length.
444 Ty = getTypes().ConvertType(getContext().LongTy);
445 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
446
447 // The struct.
448 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
449 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000450 llvm::GlobalVariable *GV =
451 new llvm::GlobalVariable(C->getType(), true,
452 llvm::GlobalVariable::InternalLinkage,
453 C, "", &getModule());
454 GV->setSection("__DATA,__cfstring");
455 Entry.setValue(GV);
456 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000457}