blob: b76d5e35eefc92e64a9993c2e5a716d7f5a3f7a7 [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//
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"
Chris Lattnerdb6be562007-11-28 05:34:05 +000018#include "clang/Basic/LangOptions.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Basic/TargetInfo.h"
20#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000022#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "llvm/Intrinsics.h"
24using namespace clang;
25using namespace CodeGen;
26
27
Chris Lattnerdb6be562007-11-28 05:34:05 +000028CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000029 llvm::Module &M, const llvm::TargetData &TD,
30 Diagnostic &diags)
31 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Devang Patela8fccb82007-10-31 20:01:01 +000032 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Chris Lattner4b009652007-07-25 00:24:17 +000033
Steve Naroffcb597472007-09-13 21:41:19 +000034llvm::Constant *CodeGenModule::GetAddrOfGlobalDecl(const ValueDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +000035 // See if it is already in the map.
36 llvm::Constant *&Entry = GlobalDeclMap[D];
37 if (Entry) return Entry;
38
39 QualType ASTTy = cast<ValueDecl>(D)->getType();
40 const llvm::Type *Ty = getTypes().ConvertType(ASTTy);
41 if (isa<FunctionDecl>(D)) {
42 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
Chris Lattner2568ae42007-12-02 05:56:05 +000043
44 // Check to see if the function already exists.
45 if (llvm::Function *F = getModule().getFunction(D->getName())) {
46 // If so, make sure it is the correct type.
47 return llvm::ConstantExpr::getBitCast(F, llvm::PointerType::get(FTy));
48 }
49
Chris Lattner4b009652007-07-25 00:24:17 +000050 // FIXME: param attributes for sext/zext etc.
51 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
52 D->getName(), &getModule());
53 }
54
55 assert(isa<FileVarDecl>(D) && "Unknown global decl!");
56
57 return Entry = new llvm::GlobalVariable(Ty, false,
58 llvm::GlobalValue::ExternalLinkage,
59 0, D->getName(), &getModule());
60}
61
62void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
63 // If this is not a prototype, emit the body.
64 if (FD->getBody())
65 CodeGenFunction(*this).GenerateCode(FD);
66}
67
Chris Lattnercef01ec2007-11-23 22:07:55 +000068static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
69 CodeGenModule& CGModule);
Devang Patel08a10cc2007-10-30 21:27:20 +000070
Chris Lattnercef01ec2007-11-23 22:07:55 +000071/// GenerateConversionToBool - Generate comparison to zero for conversion to
72/// bool
73static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
74 QualType Source) {
75 if (Source->isRealFloatingType()) {
76 // Compare against 0.0 for fp scalars.
77 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
78 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
79 Zero);
80 }
81
82 assert((Source->isIntegerType() || Source->isPointerType()) &&
83 "Unknown scalar type to convert");
84
85 // Compare against an integer or pointer null.
86 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
87 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
88}
89
90/// GenerateConstantCast - Generates a constant cast to convert the Expression
91/// into the Target type.
92static llvm::Constant *GenerateConstantCast(const Expr *Expression,
93 QualType Target,
94 CodeGenModule& CGModule) {
95 CodeGenTypes& Types = CGModule.getTypes();
96 QualType Source = Expression->getType().getCanonicalType();
97 Target = Target.getCanonicalType();
98
99 assert (!Target->isVoidType());
100
101 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGModule);
102
103 if (Source == Target)
104 return SubExpr;
105
106 // Handle conversions to bool first, they are special: comparisons against 0.
107 if (Target->isBooleanType())
108 return GenerateConversionToBool(SubExpr, Source);
109
110 const llvm::Type *SourceType = Types.ConvertType(Source);
111 const llvm::Type *TargetType = Types.ConvertType(Target);
112
113 // Ignore conversions like int -> uint.
114 if (SubExpr->getType() == TargetType)
115 return SubExpr;
116
117 // Handle pointer conversions next: pointers can only be converted to/from
118 // other pointers and integers.
119 if (isa<llvm::PointerType>(TargetType)) {
120 // The source value may be an integer, or a pointer.
121 if (isa<llvm::PointerType>(SubExpr->getType()))
122 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
123 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
124 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
125 }
126
127 if (isa<llvm::PointerType>(SourceType)) {
128 // Must be an ptr to int cast.
129 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
130 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
131 }
132
133 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
134 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
135 }
136
137 // Finally, we have the arithmetic types: real int/float.
138 if (isa<llvm::IntegerType>(SourceType)) {
139 bool InputSigned = Source->isSignedIntegerType();
140 if (isa<llvm::IntegerType>(TargetType))
141 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
142 InputSigned);
143 else if (InputSigned)
144 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
145 else
146 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
147 }
148
149 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
150 if (isa<llvm::IntegerType>(TargetType)) {
151 if (Target->isSignedIntegerType())
152 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
153 else
154 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
155 }
156
157 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
158 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
159 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
160 else
161 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
162
163 assert (!"Unsupported cast type in global intialiser.");
164 return 0;
165}
166
Chris Lattnercef01ec2007-11-23 22:07:55 +0000167/// GenerateAggregateInit - Generate a Constant initaliser for global array or
168/// struct typed variables.
169static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
170 CodeGenModule& CGModule) {
171 assert (ILE->getType()->isArrayType() || ILE->getType()->isStructureType());
172 CodeGenTypes& Types = CGModule.getTypes();
Devang Patel08a10cc2007-10-30 21:27:20 +0000173
174 unsigned NumInitElements = ILE->getNumInits();
175
Chris Lattnercef01ec2007-11-23 22:07:55 +0000176 const llvm::CompositeType *CType =
177 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
178 assert(CType);
179 std::vector<llvm::Constant*> Elts;
180
Devang Patel08a10cc2007-10-30 21:27:20 +0000181 // Copy initializer elements.
182 unsigned i = 0;
183 for (i = 0; i < NumInitElements; ++i) {
Chris Lattnercef01ec2007-11-23 22:07:55 +0000184 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGModule);
185 assert (C && "Failed to create initialiser expression");
186 Elts.push_back(C);
Devang Patel08a10cc2007-10-30 21:27:20 +0000187 }
188
Chris Lattnercef01ec2007-11-23 22:07:55 +0000189 if (ILE->getType()->isStructureType())
190 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
191
192 // Initialising an array requires us to automatically initialise any
193 // elements that have not been initialised explicitly
194 const llvm::ArrayType *AType = cast<llvm::ArrayType>(CType);
195 assert(AType);
Devang Patel08a10cc2007-10-30 21:27:20 +0000196 const llvm::Type *AElemTy = AType->getElementType();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000197 unsigned NumArrayElements = AType->getNumElements();
198 // Initialize remaining array elements.
Devang Patel08a10cc2007-10-30 21:27:20 +0000199 for (; i < NumArrayElements; ++i)
Chris Lattnercef01ec2007-11-23 22:07:55 +0000200 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Devang Patel08a10cc2007-10-30 21:27:20 +0000201
Chris Lattnercef01ec2007-11-23 22:07:55 +0000202 return llvm::ConstantArray::get(AType, Elts);
203}
204
205/// GenerateConstantExpr - Recursively builds a constant initialiser for the
206/// given expression.
207static llvm::Constant *GenerateConstantExpr(const Expr* Expression,
208 CodeGenModule& CGModule) {
209 CodeGenTypes& Types = CGModule.getTypes();
210 ASTContext& Context = CGModule.getContext();
211 assert ((Expression->isConstantExpr(Context, 0) ||
212 Expression->getStmtClass() == Stmt::InitListExprClass) &&
213 "Only constant global initialisers are supported.");
214
215 QualType type = Expression->getType().getCanonicalType();
216
217 if (type->isIntegerType()) {
218 llvm::APSInt
219 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
220 if (Expression->isIntegerConstantExpr(Value, Context)) {
221 return llvm::ConstantInt::get(Value);
222 }
223 }
224
225 switch (Expression->getStmtClass()) {
226 // Generate constant for floating point literal values.
227 case Stmt::FloatingLiteralClass: {
228 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
229 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
230 }
231
232 // Generate constant for string literal values.
233 case Stmt::StringLiteralClass: {
234 const StringLiteral *SLiteral = cast<StringLiteral>(Expression);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000235 const char *StrData = SLiteral->getStrData();
236 unsigned Len = SLiteral->getByteLength();
237 return CGModule.GetAddrOfConstantString(std::string(StrData,
238 StrData + Len));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000239 }
240
241 // Elide parenthesis.
242 case Stmt::ParenExprClass:
243 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(),
244 CGModule);
245
246 // Generate constant for sizeof operator.
247 // FIXME: Need to support AlignOf
248 case Stmt::SizeOfAlignOfTypeExprClass: {
249 const SizeOfAlignOfTypeExpr *SOExpr =
250 cast<SizeOfAlignOfTypeExpr>(Expression);
251 assert (SOExpr->isSizeOf());
252 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
253 }
254
255 // Generate constant cast expressions.
256 case Stmt::CastExprClass:
257 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
258 CGModule);
259
260 case Stmt::ImplicitCastExprClass: {
261 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
262 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGModule);
263 }
264
265 // Generate a constant array access expression
266 // FIXME: Clang's semantic analysis incorrectly prevents array access in
267 // global initialisers, preventing us from testing this.
268 case Stmt::ArraySubscriptExprClass: {
269 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
270 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGModule);
271 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGModule);
272 return llvm::ConstantExpr::getExtractElement(Base, Index);
273 }
274
275 // Generate a constant expression to initialise an aggregate type, such as
276 // an array or struct.
277 case Stmt::InitListExprClass:
278 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGModule);
279
280 default:
281 assert (!"Unsupported expression in global initialiser.");
282 }
283 return 0;
284}
285
Oliver Hunt253e0a72007-12-02 00:11:25 +0000286llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
287 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000288}
289
Chris Lattner4b009652007-07-25 00:24:17 +0000290void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
291 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalDecl(D));
292
293 // If the storage class is external and there is no initializer, just leave it
294 // as a declaration.
295 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
296 return;
297
298 // Otherwise, convert the initializer, or use zero if appropriate.
299 llvm::Constant *Init = 0;
300 if (D->getInit() == 0) {
301 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
302 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000303 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000304 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000305 if (D->getInit()->isIntegerConstantExpr(Value, Context))
306 Init = llvm::ConstantInt::get(Value);
307 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000308
Devang Patel08a10cc2007-10-30 21:27:20 +0000309 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000310 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000311
Devang Patel08a10cc2007-10-30 21:27:20 +0000312 assert(Init && "FIXME: Global variable initializers unimp!");
Chris Lattner4b009652007-07-25 00:24:17 +0000313
314 GV->setInitializer(Init);
315
316 // Set the llvm linkage type as appropriate.
317 // FIXME: This isn't right. This should handle common linkage and other
318 // stuff.
319 switch (D->getStorageClass()) {
320 case VarDecl::Auto:
321 case VarDecl::Register:
322 assert(0 && "Can't have auto or register globals");
323 case VarDecl::None:
324 case VarDecl::Extern:
325 // todo: common
326 break;
327 case VarDecl::Static:
328 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
329 break;
330 }
331}
332
333/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
334/// declarator chain.
335void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
336 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
337 EmitGlobalVar(D);
338}
339
Chris Lattnerab862cc2007-08-31 04:31:45 +0000340/// getBuiltinLibFunction
341llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
342 if (BuiltinFunctions.size() <= BuiltinID)
343 BuiltinFunctions.resize(BuiltinID);
344
345 // Already available?
346 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
347 if (FunctionSlot)
348 return FunctionSlot;
349
350 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
351
352 // Get the name, skip over the __builtin_ prefix.
353 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
354
355 // Get the type for the builtin.
356 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
357 const llvm::FunctionType *Ty =
358 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
359
360 // FIXME: This has a serious problem with code like this:
361 // void abs() {}
362 // ... __builtin_abs(x);
363 // The two versions of abs will collide. The fix is for the builtin to win,
364 // and for the existing one to be turned into a constantexpr cast of the
365 // builtin. In the case where the existing one is a static function, it
366 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000367 if (llvm::Function *Existing = getModule().getFunction(Name)) {
368 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
369 return FunctionSlot = Existing;
370 assert(Existing == 0 && "FIXME: Name collision");
371 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000372
373 // FIXME: param attributes for sext/zext etc.
374 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
375 Name, &getModule());
376}
377
378
Chris Lattner4b009652007-07-25 00:24:17 +0000379llvm::Function *CodeGenModule::getMemCpyFn() {
380 if (MemCpyFn) return MemCpyFn;
381 llvm::Intrinsic::ID IID;
382 uint64_t Size; unsigned Align;
383 Context.Target.getPointerInfo(Size, Align, SourceLocation());
384 switch (Size) {
385 default: assert(0 && "Unknown ptr width");
386 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
387 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
388 }
389 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
390}
Anders Carlsson36a04872007-08-21 00:21:21 +0000391
Chris Lattnerab862cc2007-08-31 04:31:45 +0000392llvm::Constant *CodeGenModule::
393GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000394 llvm::StringMapEntry<llvm::Constant *> &Entry =
395 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
396
397 if (Entry.getValue())
398 return Entry.getValue();
399
400 std::vector<llvm::Constant*> Fields;
401
402 if (!CFConstantStringClassRef) {
403 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
404 Ty = llvm::ArrayType::get(Ty, 0);
405
406 CFConstantStringClassRef =
407 new llvm::GlobalVariable(Ty, false,
408 llvm::GlobalVariable::ExternalLinkage, 0,
409 "__CFConstantStringClassReference",
410 &getModule());
411 }
412
413 // Class pointer.
414 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
415 llvm::Constant *Zeros[] = { Zero, Zero };
416 llvm::Constant *C =
417 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
418 Fields.push_back(C);
419
420 // Flags.
421 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
422 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
423
424 // String pointer.
425 C = llvm::ConstantArray::get(str);
426 C = new llvm::GlobalVariable(C->getType(), true,
427 llvm::GlobalValue::InternalLinkage,
428 C, ".str", &getModule());
429
430 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
431 Fields.push_back(C);
432
433 // String length.
434 Ty = getTypes().ConvertType(getContext().LongTy);
435 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
436
437 // The struct.
438 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
439 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000440 llvm::GlobalVariable *GV =
441 new llvm::GlobalVariable(C->getType(), true,
442 llvm::GlobalVariable::InternalLinkage,
443 C, "", &getModule());
444 GV->setSection("__DATA,__cfstring");
445 Entry.setValue(GV);
446 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000447}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000448
449/// GenerateWritableString -- Creates storage for a string literal
450static llvm::Constant *GenerateStringLiteral(const std::string &str,
451 bool constant,
452 CodeGenModule& CGModule) {
453 // Create Constant for this string literal
454 llvm::Constant *C=llvm::ConstantArray::get(str);
455
456 // Create a global variable for this string
457 C = new llvm::GlobalVariable(C->getType(), constant,
458 llvm::GlobalValue::InternalLinkage,
459 C, ".str", &CGModule.getModule());
460 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
461 llvm::Constant *Zeros[] = { Zero, Zero };
462 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
463 return C;
464}
465
466/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
467/// element of a character array containing the literal.
468llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
469 // Don't share any string literals if writable-strings is turned on.
470 if (Features.WritableStrings)
471 return GenerateStringLiteral(str, false, *this);
472
473 llvm::StringMapEntry<llvm::Constant *> &Entry =
474 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
475
476 if (Entry.getValue())
477 return Entry.getValue();
478
479 // Create a global variable for this.
480 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
481 Entry.setValue(C);
482 return C;
483}