blob: 17c7c016743b5c54333e761bedd6be7e31cd69e8 [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
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 contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "clang/AST/AST.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18using namespace llvm;
19using namespace clang;
20using namespace CodeGen;
21
Chris Lattnerd7f58862007-06-02 05:24:33 +000022//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000023// Miscellaneous Helper Methods
24//===--------------------------------------------------------------------===//
25
26/// EvaluateScalarValueToBool - Evaluate the specified expression value to a
27/// boolean (i1) truth value. This is equivalent to "Val == 0".
28Value *CodeGenFunction::EvaluateScalarValueToBool(ExprResult Val, QualType Ty) {
29 Ty = Ty.getCanonicalType();
30 Value *Result;
31 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
32 switch (BT->getKind()) {
33 default: assert(0 && "Unknown scalar value");
34 case BuiltinType::Bool:
35 Result = Val.getVal();
36 // Bool is already evaluated right.
37 assert(Result->getType() == llvm::Type::Int1Ty &&
38 "Unexpected bool value type!");
39 return Result;
Chris Lattnerb16f4552007-06-03 07:25:34 +000040 case BuiltinType::Char_S:
41 case BuiltinType::Char_U:
Chris Lattnerf0106d22007-06-02 19:33:17 +000042 case BuiltinType::SChar:
43 case BuiltinType::UChar:
44 case BuiltinType::Short:
45 case BuiltinType::UShort:
46 case BuiltinType::Int:
47 case BuiltinType::UInt:
48 case BuiltinType::Long:
49 case BuiltinType::ULong:
50 case BuiltinType::LongLong:
51 case BuiltinType::ULongLong:
52 // Code below handles simple integers.
53 break;
54 case BuiltinType::Float:
55 case BuiltinType::Double:
56 case BuiltinType::LongDouble: {
57 // Compare against 0.0 for fp scalars.
58 Result = Val.getVal();
59 llvm::Value *Zero = Constant::getNullValue(Result->getType());
60 // FIXME: llvm-gcc produces a une comparison: validate this is right.
61 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
62 return Result;
63 }
64
65 case BuiltinType::FloatComplex:
66 case BuiltinType::DoubleComplex:
67 case BuiltinType::LongDoubleComplex:
68 assert(0 && "comparisons against complex not implemented yet");
69 }
70 } else {
71 assert((isa<PointerType>(Ty) ||
72 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) &&
73 "Unknown scalar type");
74 // Code below handles this fine.
75 }
76
77 // Usual case for integers, pointers, and enums: compare against zero.
78 Result = Val.getVal();
Chris Lattnera45c5af2007-06-02 19:47:04 +000079
80 // Because of the type rules of C, we often end up computing a logical value,
81 // then zero extending it to int, then wanting it as a logical value again.
82 // Optimize this common case.
83 if (llvm::ZExtInst *ZI = dyn_cast<ZExtInst>(Result)) {
84 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
85 Result = ZI->getOperand(0);
86 ZI->eraseFromParent();
87 return Result;
88 }
89 }
90
Chris Lattnerf0106d22007-06-02 19:33:17 +000091 llvm::Value *Zero = Constant::getNullValue(Result->getType());
92 return Builder.CreateICmpNE(Result, Zero, "tobool");
93}
94
Chris Lattnera45c5af2007-06-02 19:47:04 +000095//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +000096// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +000097//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +000098
99LValue CodeGenFunction::EmitLValue(const Expr *E) {
100 switch (E->getStmtClass()) {
101 default:
102 printf("Unimplemented lvalue expr!\n");
103 E->dump();
104 return LValue::getAddr(UndefValue::get(
105 llvm::PointerType::get(llvm::Type::Int32Ty)));
106
107 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
108 }
109}
110
111
112LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
113 const Decl *D = E->getDecl();
114 if (isa<BlockVarDecl>(D)) {
115 Value *V = LocalDeclMap[D];
116 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
117 return LValue::getAddr(V);
118 }
119 assert(0 && "Unimp declref");
120}
Chris Lattnere47e4402007-06-01 18:02:12 +0000121
122//===--------------------------------------------------------------------===//
123// Expression Emission
124//===--------------------------------------------------------------------===//
125
126ExprResult CodeGenFunction::EmitExpr(const Expr *E) {
127 assert(E && "Null expression?");
128
129 switch (E->getStmtClass()) {
130 default:
131 printf("Unimplemented expr!\n");
132 E->dump();
133 return ExprResult::get(UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000134
135 // l-values.
136 case Expr::DeclRefExprClass: {
137 // FIXME: EnumConstantDecl's are not lvalues.
138 LValue LV = EmitLValue(E);
139 // FIXME: this is silly.
140 assert(!LV.isBitfield());
141 return ExprResult::get(Builder.CreateLoad(LV.getAddress(), "tmp"));
142 }
143
144 // Leaf expressions.
145 case Expr::IntegerLiteralClass:
Chris Lattnere47e4402007-06-01 18:02:12 +0000146 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
Chris Lattnerdb91b162007-06-02 00:16:28 +0000147
Chris Lattnerd7f58862007-06-02 05:24:33 +0000148 // Operators.
149 case Expr::ParenExprClass:
150 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000151 case Expr::UnaryOperatorClass:
152 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000153 case Expr::BinaryOperatorClass:
Chris Lattnerdb91b162007-06-02 00:16:28 +0000154 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattnere47e4402007-06-01 18:02:12 +0000155 }
156
157}
158
159ExprResult CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
160 return ExprResult::get(ConstantInt::get(E->getValue()));
161}
162
Chris Lattnerf0106d22007-06-02 19:33:17 +0000163//===--------------------------------------------------------------------===//
164// Unary Operator Emission
165//===--------------------------------------------------------------------===//
166
Chris Lattner6db1fb82007-06-02 22:49:07 +0000167ExprResult CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
168 QualType &ResTy) {
169 ResTy = E->getType().getCanonicalType();
170
171 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
172 // Functions are promoted to their address.
173 ResTy = getContext().getPointerType(ResTy);
174 return ExprResult::get(EmitLValue(E).getAddress());
175 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
176 // C99 6.3.2.1p3
177 ResTy = getContext().getPointerType(ary->getElementType());
178
179 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
180 // will not true when we add support for VLAs.
181 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
182
183 assert(isa<llvm::PointerType>(V->getType()) &&
184 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
185 ->getElementType()) &&
186 "Doesn't support VLAs yet!");
187 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
188 V = Builder.CreateGEP(V, Idx0, Idx0, "arraydecay");
189 return ExprResult::get(V);
190 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
191 // FIXME: this probably isn't right, pending clarification from Steve.
192 llvm::Value *Val = EmitExpr(E).getVal();
193
Chris Lattner6db1fb82007-06-02 22:49:07 +0000194 // If the input is a signed integer, sign extend to the destination.
195 if (ResTy->isSignedIntegerType()) {
196 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
197 } else {
198 // This handles unsigned types, including bool.
199 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
200 }
201 ResTy = getContext().IntTy;
202
203 return ExprResult::get(Val);
204 }
205
206 // Otherwise, this is a float, double, int, struct, etc.
207 return EmitExpr(E);
208}
209
210
Chris Lattnerf0106d22007-06-02 19:33:17 +0000211ExprResult CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
212 switch (E->getOpcode()) {
213 default:
214 printf("Unimplemented unary expr!\n");
215 E->dump();
216 return ExprResult::get(UndefValue::get(llvm::Type::Int32Ty));
217 case UnaryOperator::LNot: return EmitUnaryLNot(E);
218 }
219}
220
221/// C99 6.5.3.3
222ExprResult CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
Chris Lattner6db1fb82007-06-02 22:49:07 +0000223 QualType ResTy;
224 ExprResult Op = EmitExprWithUsualUnaryConversions(E->getSubExpr(), ResTy);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000225
226 // Compare to zero.
Chris Lattner6db1fb82007-06-02 22:49:07 +0000227 Value *BoolVal = EvaluateScalarValueToBool(Op, ResTy);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000228
229 // Invert value.
Chris Lattnera45c5af2007-06-02 19:47:04 +0000230 // TODO: Could dynamically modify easy computations here. For example, if
231 // the operand is an icmp ne, turn into icmp eq.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000232 BoolVal = Builder.CreateNot(BoolVal, "lnot");
233
234 // ZExt result to int.
Chris Lattner6db1fb82007-06-02 22:49:07 +0000235 const llvm::Type *ResLTy = ConvertType(E->getType(), E->getOperatorLoc());
236 return ExprResult::get(Builder.CreateZExt(BoolVal, ResLTy, "lnot.ext"));
Chris Lattnerf0106d22007-06-02 19:33:17 +0000237}
238
Chris Lattnere47e4402007-06-01 18:02:12 +0000239
Chris Lattnerdb91b162007-06-02 00:16:28 +0000240//===--------------------------------------------------------------------===//
241// Binary Operator Emission
242//===--------------------------------------------------------------------===//
243
244// FIXME describe.
Chris Lattnercf250242007-06-03 02:02:44 +0000245QualType CodeGenFunction::
246EmitUsualArithmeticConversions(const BinaryOperator *E, ExprResult &LHS,
247 ExprResult &RHS) {
Chris Lattnerc18f9d12007-06-02 22:51:30 +0000248 QualType LHSType, RHSType;
249 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
250 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
251
Chris Lattnercf250242007-06-03 02:02:44 +0000252 // If both operands have the same source type, we're done already.
253 if (LHSType == RHSType) return LHSType;
254
255 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
256 // The caller can deal with this (e.g. pointer + int).
257 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
258 return LHSType;
259
260 // At this point, we have two different arithmetic types.
261
262 // Handle complex types first (C99 6.3.1.8p1).
263 if (LHSType->isComplexType() || RHSType->isComplexType()) {
264 assert(0 && "FIXME: complex types unimp");
265#if 0
266 // if we have an integer operand, the result is the complex type.
267 if (rhs->isIntegerType())
268 return lhs;
269 if (lhs->isIntegerType())
270 return rhs;
271 return Context.maxComplexType(lhs, rhs);
272#endif
273 }
274
275 // If neither operand is complex, they must be scalars.
276 llvm::Value *LHSV = LHS.getVal();
277 llvm::Value *RHSV = RHS.getVal();
278
279 // If the LLVM types are already equal, then they only differed in sign, or it
280 // was something like char/signed char or double/long double.
281 if (LHSV->getType() == RHSV->getType())
282 return LHSType;
283
284 // Now handle "real" floating types (i.e. float, double, long double).
285 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
286 // if we have an integer operand, the result is the real floating type, and
287 // the integer converts to FP.
288 if (RHSType->isIntegerType()) {
289 // Promote the RHS to an FP type of the LHS, with the sign following the
290 // RHS.
291 if (RHSType->isSignedIntegerType())
292 RHS = ExprResult::get(Builder.CreateSIToFP(RHSV, LHSV->getType(),
293 "promote"));
294 else
295 RHS = ExprResult::get(Builder.CreateUIToFP(RHSV, LHSV->getType(),
296 "promote"));
297 return LHSType;
298 }
299
300 if (LHSType->isIntegerType()) {
301 // Promote the LHS to an FP type of the RHS, with the sign following the
302 // LHS.
303 if (LHSType->isSignedIntegerType())
304 LHS = ExprResult::get(Builder.CreateSIToFP(LHSV, RHSV->getType(),
305 "promote"));
306 else
307 LHS = ExprResult::get(Builder.CreateUIToFP(LHSV, RHSV->getType(),
308 "promote"));
309 return RHSType;
310 }
311
312 // Otherwise, they are two FP types. Promote the smaller operand to the
313 // bigger result.
314 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
315
316 if (BiggerType == LHSType)
317 RHS = ExprResult::get(Builder.CreateFPExt(RHSV, LHSV->getType(),
318 "promote"));
319 else
320 LHS = ExprResult::get(Builder.CreateFPExt(LHSV, RHSV->getType(),
321 "promote"));
322 return BiggerType;
323 }
324
325 // Finally, we have two integer types that are different according to C. Do
326 // a sign or zero extension if needed.
327
328 // Otherwise, one type is smaller than the other.
329 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
330
331 if (LHSType == ResTy) {
332 if (RHSType->isSignedIntegerType())
333 RHS = ExprResult::get(Builder.CreateSExt(RHSV, LHSV->getType(),
334 "promote"));
335 else
336 RHS = ExprResult::get(Builder.CreateZExt(RHSV, LHSV->getType(),
337 "promote"));
338 } else {
339 assert(RHSType == ResTy && "Unknown conversion");
340 if (LHSType->isSignedIntegerType())
341 LHS = ExprResult::get(Builder.CreateSExt(LHSV, RHSV->getType(),
342 "promote"));
343 else
344 LHS = ExprResult::get(Builder.CreateZExt(LHSV, RHSV->getType(),
345 "promote"));
346 }
347 return ResTy;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000348}
349
350
351ExprResult CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
352 switch (E->getOpcode()) {
353 default:
354 printf("Unimplemented expr!\n");
355 E->dump();
356 return ExprResult::get(UndefValue::get(llvm::Type::Int32Ty));
357 case BinaryOperator::Add: return EmitBinaryAdd(E);
358 }
359}
360
361
362ExprResult CodeGenFunction::EmitBinaryAdd(const BinaryOperator *E) {
363 ExprResult LHS, RHS;
364
365 EmitUsualArithmeticConversions(E, LHS, RHS);
366
367
368 return ExprResult::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "tmp"));
369}