blob: 0af76beff61847befe18e17f8d195bd357fcfc48 [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"
Chris Lattner4347e3692007-06-06 04:54:52 +000018#include "llvm/Function.h"
19#include "llvm/GlobalVariable.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000020using namespace llvm;
21using namespace clang;
22using namespace CodeGen;
23
Chris Lattnerd7f58862007-06-02 05:24:33 +000024//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000025// Miscellaneous Helper Methods
26//===--------------------------------------------------------------------===//
27
Chris Lattner8394d792007-06-05 20:53:16 +000028
29/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
30/// expression and compare the result against zero, returning an Int1Ty value.
31Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
32 QualType Ty;
33 RValue Val = EmitExprWithUsualUnaryConversions(E, Ty);
34 return ConvertScalarValueToBool(Val, Ty);
35}
36
37//===--------------------------------------------------------------------===//
38// Conversions
39//===--------------------------------------------------------------------===//
40
41/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
42/// the type specified by DstTy, following the rules of C99 6.3.
43RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
Chris Lattnercf106ab2007-06-06 04:05:39 +000044 QualType DstTy, SourceLocation Loc) {
Chris Lattner8394d792007-06-05 20:53:16 +000045 ValTy = ValTy.getCanonicalType();
46 DstTy = DstTy.getCanonicalType();
47 if (ValTy == DstTy) return Val;
Chris Lattner83b484b2007-06-06 04:39:08 +000048
49 // Handle conversions to bool first, they are special: comparisons against 0.
50 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
51 if (DestBT->getKind() == BuiltinType::Bool)
52 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
Chris Lattner8394d792007-06-05 20:53:16 +000053
Chris Lattner83b484b2007-06-06 04:39:08 +000054 // Handle pointer conversions next: pointers can only be converted to/from
55 // other pointers and integers.
Chris Lattnercf106ab2007-06-06 04:05:39 +000056 if (isa<PointerType>(DstTy)) {
57 const llvm::Type *DestTy = ConvertType(DstTy, Loc);
58
59 // The source value may be an integer, or a pointer.
60 assert(Val.isScalar() && "Can only convert from integer or pointer");
61 if (isa<llvm::PointerType>(Val.getVal()->getType()))
62 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
63 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
64 return RValue::get(Builder.CreatePtrToInt(Val.getVal(), DestTy, "conv"));
Chris Lattner83b484b2007-06-06 04:39:08 +000065 }
66
67 if (isa<PointerType>(ValTy)) {
Chris Lattnercf106ab2007-06-06 04:05:39 +000068 // Must be an ptr to int cast.
69 const llvm::Type *DestTy = ConvertType(DstTy, Loc);
70 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
71 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner8394d792007-06-05 20:53:16 +000072 }
Chris Lattner83b484b2007-06-06 04:39:08 +000073
74 // Finally, we have the arithmetic types: real int/float and complex
75 // int/float. Handle real->real conversions first, they are the most
76 // common.
77 if (Val.isScalar() && DstTy->isRealType()) {
78 // We know that these are representable as scalars in LLVM, convert to LLVM
79 // types since they are easier to reason about.
80 Value *SrcVal = Val.getVal();
81 const llvm::Type *DestTy = ConvertType(DstTy, Loc);
82 if (SrcVal->getType() == DestTy) return Val;
83
84 Value *Result;
85 if (isa<llvm::IntegerType>(SrcVal->getType())) {
86 bool InputSigned = ValTy->isSignedIntegerType();
87 if (isa<llvm::IntegerType>(DestTy))
88 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
89 else if (InputSigned)
90 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
91 else
92 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
93 } else {
94 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
95 if (isa<llvm::IntegerType>(DestTy)) {
96 if (DstTy->isSignedIntegerType())
97 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
98 else
99 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
100 } else {
101 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
102 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
103 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
104 else
105 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
106 }
107 }
108 return RValue::get(Result);
109 }
110
111 assert(0 && "FIXME: We don't support complex conversions yet!");
Chris Lattner8394d792007-06-05 20:53:16 +0000112}
113
114
115/// ConvertScalarValueToBool - Convert the specified expression value to a
Chris Lattnerf0106d22007-06-02 19:33:17 +0000116/// boolean (i1) truth value. This is equivalent to "Val == 0".
Chris Lattner8394d792007-06-05 20:53:16 +0000117Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000118 Ty = Ty.getCanonicalType();
119 Value *Result;
120 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
121 switch (BT->getKind()) {
122 default: assert(0 && "Unknown scalar value");
123 case BuiltinType::Bool:
124 Result = Val.getVal();
125 // Bool is already evaluated right.
126 assert(Result->getType() == llvm::Type::Int1Ty &&
127 "Unexpected bool value type!");
128 return Result;
Chris Lattnerb16f4552007-06-03 07:25:34 +0000129 case BuiltinType::Char_S:
130 case BuiltinType::Char_U:
Chris Lattnerf0106d22007-06-02 19:33:17 +0000131 case BuiltinType::SChar:
132 case BuiltinType::UChar:
133 case BuiltinType::Short:
134 case BuiltinType::UShort:
135 case BuiltinType::Int:
136 case BuiltinType::UInt:
137 case BuiltinType::Long:
138 case BuiltinType::ULong:
139 case BuiltinType::LongLong:
140 case BuiltinType::ULongLong:
141 // Code below handles simple integers.
142 break;
143 case BuiltinType::Float:
144 case BuiltinType::Double:
145 case BuiltinType::LongDouble: {
146 // Compare against 0.0 for fp scalars.
147 Result = Val.getVal();
148 llvm::Value *Zero = Constant::getNullValue(Result->getType());
149 // FIXME: llvm-gcc produces a une comparison: validate this is right.
150 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
151 return Result;
152 }
153
154 case BuiltinType::FloatComplex:
155 case BuiltinType::DoubleComplex:
156 case BuiltinType::LongDoubleComplex:
157 assert(0 && "comparisons against complex not implemented yet");
158 }
159 } else {
160 assert((isa<PointerType>(Ty) ||
161 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) &&
162 "Unknown scalar type");
163 // Code below handles this fine.
164 }
165
166 // Usual case for integers, pointers, and enums: compare against zero.
167 Result = Val.getVal();
Chris Lattnera45c5af2007-06-02 19:47:04 +0000168
169 // Because of the type rules of C, we often end up computing a logical value,
170 // then zero extending it to int, then wanting it as a logical value again.
171 // Optimize this common case.
172 if (llvm::ZExtInst *ZI = dyn_cast<ZExtInst>(Result)) {
173 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
174 Result = ZI->getOperand(0);
175 ZI->eraseFromParent();
176 return Result;
177 }
178 }
179
Chris Lattnerf0106d22007-06-02 19:33:17 +0000180 llvm::Value *Zero = Constant::getNullValue(Result->getType());
181 return Builder.CreateICmpNE(Result, Zero, "tobool");
182}
183
Chris Lattnera45c5af2007-06-02 19:47:04 +0000184//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000185// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000186//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000187
Chris Lattner8394d792007-06-05 20:53:16 +0000188/// EmitLValue - Emit code to compute a designator that specifies the location
189/// of the expression.
190///
191/// This can return one of two things: a simple address or a bitfield
192/// reference. In either case, the LLVM Value* in the LValue structure is
193/// guaranteed to be an LLVM pointer type.
194///
195/// If this returns a bitfield reference, nothing about the pointee type of
196/// the LLVM value is known: For example, it may not be a pointer to an
197/// integer.
198///
199/// If this returns a normal address, and if the lvalue's C type is fixed
200/// size, this method guarantees that the returned pointer type will point to
201/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
202/// variable length type, this is not possible.
203///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000204LValue CodeGenFunction::EmitLValue(const Expr *E) {
205 switch (E->getStmtClass()) {
206 default:
Chris Lattner8394d792007-06-05 20:53:16 +0000207 fprintf(stderr, "Unimplemented lvalue expr!\n");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000208 E->dump();
209 return LValue::getAddr(UndefValue::get(
210 llvm::PointerType::get(llvm::Type::Int32Ty)));
211
212 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Chris Lattner946aa312007-06-05 03:59:43 +0000213 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner4347e3692007-06-06 04:54:52 +0000214 case Expr::StringLiteralClass:
215 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000216
217 case Expr::UnaryOperatorClass:
218 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000219 }
220}
221
Chris Lattner8394d792007-06-05 20:53:16 +0000222/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
223/// this method emits the address of the lvalue, then loads the result as an
224/// rvalue, returning the rvalue.
225RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
226 LValue LV = EmitLValue(E);
227
228 QualType ExprTy = E->getType().getCanonicalType();
229
230 // FIXME: this is silly and obviously wrong for non-scalars.
231 assert(!LV.isBitfield());
232 return RValue::get(Builder.CreateLoad(LV.getAddress(), "tmp"));
233}
234
235/// EmitStoreThroughLValue - Store the specified rvalue into the specified
236/// lvalue, where both are guaranteed to the have the same type, and that type
237/// is 'Ty'.
238void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
239 QualType Ty) {
240 // FIXME: This is obviously bogus.
241 assert(!Dst.isBitfield() && "FIXME: Don't support store to bitfield yet");
242 assert(Src.isScalar() && "FIXME: Don't support store of aggregate yet");
243
244 // TODO: Handle volatility etc.
245 Value *Addr = Dst.getAddress();
246 const llvm::Type *SrcTy = Src.getVal()->getType();
247 const llvm::Type *AddrTy =
248 cast<llvm::PointerType>(Addr->getType())->getElementType();
249
250 if (AddrTy != SrcTy)
251 Addr = Builder.CreateBitCast(Addr, llvm::PointerType::get(SrcTy),
252 "storetmp");
253 Builder.CreateStore(Src.getVal(), Addr);
254}
255
Chris Lattnerd7f58862007-06-02 05:24:33 +0000256
257LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
258 const Decl *D = E->getDecl();
259 if (isa<BlockVarDecl>(D)) {
260 Value *V = LocalDeclMap[D];
261 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
262 return LValue::getAddr(V);
263 }
264 assert(0 && "Unimp declref");
265}
Chris Lattnere47e4402007-06-01 18:02:12 +0000266
Chris Lattner8394d792007-06-05 20:53:16 +0000267LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
268 // __extension__ doesn't affect lvalue-ness.
269 if (E->getOpcode() == UnaryOperator::Extension)
270 return EmitLValue(E->getSubExpr());
271
272 assert(E->getOpcode() == UnaryOperator::Deref &&
273 "'*' is the only unary operator that produces an lvalue");
274 return LValue::getAddr(EmitExpr(E->getSubExpr()).getVal());
275}
276
Chris Lattner4347e3692007-06-06 04:54:52 +0000277LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
278 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
279 const char *StrData = E->getStrData();
280 unsigned Len = E->getByteLength();
281
282 // FIXME: Can cache/reuse these within the module.
283 Constant *C = llvm::ConstantArray::get(std::string(StrData, StrData+Len));
284
285 // Create a global variable for this.
286 C = new llvm::GlobalVariable(C->getType(), true, GlobalValue::InternalLinkage,
287 C, ".str", CurFn->getParent());
288 Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
289 Constant *Zeros[] = { Zero, Zero };
290 C = ConstantExpr::getGetElementPtr(C, Zeros, 2);
291 return LValue::getAddr(C);
292}
293
Chris Lattnere47e4402007-06-01 18:02:12 +0000294//===--------------------------------------------------------------------===//
295// Expression Emission
296//===--------------------------------------------------------------------===//
297
Chris Lattner8394d792007-06-05 20:53:16 +0000298RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattnere47e4402007-06-01 18:02:12 +0000299 assert(E && "Null expression?");
300
301 switch (E->getStmtClass()) {
302 default:
303 printf("Unimplemented expr!\n");
304 E->dump();
Chris Lattner8394d792007-06-05 20:53:16 +0000305 return RValue::get(UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000306
307 // l-values.
Chris Lattner8394d792007-06-05 20:53:16 +0000308 case Expr::DeclRefExprClass:
309 // FIXME: EnumConstantDecl's are not lvalues. This is wrong for them.
310 return EmitLoadOfLValue(E);
Chris Lattner4347e3692007-06-06 04:54:52 +0000311 case Expr::StringLiteralClass:
312 return RValue::get(EmitLValue(E).getAddress());
Chris Lattnerd7f58862007-06-02 05:24:33 +0000313
314 // Leaf expressions.
315 case Expr::IntegerLiteralClass:
Chris Lattnere47e4402007-06-01 18:02:12 +0000316 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
Chris Lattnerdb91b162007-06-02 00:16:28 +0000317
Chris Lattnerd7f58862007-06-02 05:24:33 +0000318 // Operators.
319 case Expr::ParenExprClass:
320 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000321 case Expr::UnaryOperatorClass:
322 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000323 case Expr::CastExprClass:
324 return EmitCastExpr(cast<CastExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000325 case Expr::BinaryOperatorClass:
Chris Lattnerdb91b162007-06-02 00:16:28 +0000326 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattnere47e4402007-06-01 18:02:12 +0000327 }
328
329}
330
Chris Lattner8394d792007-06-05 20:53:16 +0000331RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
332 return RValue::get(ConstantInt::get(E->getValue()));
Chris Lattnere47e4402007-06-01 18:02:12 +0000333}
334
Chris Lattner8394d792007-06-05 20:53:16 +0000335RValue CodeGenFunction::EmitCastExpr(const CastExpr *E) {
336 QualType SrcTy;
337 RValue Src = EmitExprWithUsualUnaryConversions(E->getSubExpr(), SrcTy);
338
339 // If the destination is void, just evaluate the source.
340 if (E->getType()->isVoidType())
341 return RValue::getAggregate(0);
342
Chris Lattnercf106ab2007-06-06 04:05:39 +0000343 return EmitConversion(Src, SrcTy, E->getType(), E->getLParenLoc());
Chris Lattner8394d792007-06-05 20:53:16 +0000344}
Chris Lattnerf0106d22007-06-02 19:33:17 +0000345
Chris Lattner8394d792007-06-05 20:53:16 +0000346//===----------------------------------------------------------------------===//
347// Unary Operator Emission
348//===----------------------------------------------------------------------===//
349
350RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
351 QualType &ResTy) {
Chris Lattner6db1fb82007-06-02 22:49:07 +0000352 ResTy = E->getType().getCanonicalType();
353
354 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
355 // Functions are promoted to their address.
356 ResTy = getContext().getPointerType(ResTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000357 return RValue::get(EmitLValue(E).getAddress());
Chris Lattner6db1fb82007-06-02 22:49:07 +0000358 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
359 // C99 6.3.2.1p3
360 ResTy = getContext().getPointerType(ary->getElementType());
361
362 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
363 // will not true when we add support for VLAs.
364 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
365
366 assert(isa<llvm::PointerType>(V->getType()) &&
367 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
368 ->getElementType()) &&
369 "Doesn't support VLAs yet!");
370 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Chris Lattner8394d792007-06-05 20:53:16 +0000371 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
Chris Lattner6db1fb82007-06-02 22:49:07 +0000372 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
373 // FIXME: this probably isn't right, pending clarification from Steve.
374 llvm::Value *Val = EmitExpr(E).getVal();
375
Chris Lattner6db1fb82007-06-02 22:49:07 +0000376 // If the input is a signed integer, sign extend to the destination.
377 if (ResTy->isSignedIntegerType()) {
378 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
379 } else {
380 // This handles unsigned types, including bool.
381 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
382 }
383 ResTy = getContext().IntTy;
384
Chris Lattner8394d792007-06-05 20:53:16 +0000385 return RValue::get(Val);
Chris Lattner6db1fb82007-06-02 22:49:07 +0000386 }
387
388 // Otherwise, this is a float, double, int, struct, etc.
389 return EmitExpr(E);
390}
391
392
Chris Lattner8394d792007-06-05 20:53:16 +0000393RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000394 switch (E->getOpcode()) {
395 default:
396 printf("Unimplemented unary expr!\n");
397 E->dump();
Chris Lattner8394d792007-06-05 20:53:16 +0000398 return RValue::get(UndefValue::get(llvm::Type::Int32Ty));
399 // FIXME: pre/post inc/dec
400 case UnaryOperator::AddrOf: return EmitUnaryAddrOf(E);
401 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
402 case UnaryOperator::Plus : return EmitUnaryPlus(E);
403 case UnaryOperator::Minus : return EmitUnaryMinus(E);
404 case UnaryOperator::Not : return EmitUnaryNot(E);
405 case UnaryOperator::LNot : return EmitUnaryLNot(E);
406 // FIXME: SIZEOF/ALIGNOF(expr).
407 // FIXME: real/imag
408 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000409 }
410}
411
Chris Lattner8394d792007-06-05 20:53:16 +0000412/// C99 6.5.3.2
413RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
414 // The address of the operand is just its lvalue. It cannot be a bitfield.
415 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
416}
417
418RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
419 // Unary plus just performs promotions on its arithmetic operand.
420 QualType Ty;
421 return EmitExprWithUsualUnaryConversions(E, Ty);
422}
423
424RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
425 // Unary minus performs promotions, then negates its arithmetic operand.
426 QualType Ty;
427 RValue V = EmitExprWithUsualUnaryConversions(E, Ty);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000428
Chris Lattner8394d792007-06-05 20:53:16 +0000429 if (V.isScalar())
430 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
431
432 assert(0 && "FIXME: This doesn't handle complex operands yet");
433}
434
435RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
436 // Unary not performs promotions, then complements its integer operand.
437 QualType Ty;
438 RValue V = EmitExprWithUsualUnaryConversions(E, Ty);
439
440 if (V.isScalar())
441 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
442
443 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
444}
445
446
447/// C99 6.5.3.3
448RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
449 // Compare operand to zero.
450 Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000451
452 // Invert value.
Chris Lattnera45c5af2007-06-02 19:47:04 +0000453 // TODO: Could dynamically modify easy computations here. For example, if
454 // the operand is an icmp ne, turn into icmp eq.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000455 BoolVal = Builder.CreateNot(BoolVal, "lnot");
456
457 // ZExt result to int.
Chris Lattner8394d792007-06-05 20:53:16 +0000458 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
Chris Lattnerf0106d22007-06-02 19:33:17 +0000459}
460
Chris Lattnere47e4402007-06-01 18:02:12 +0000461
Chris Lattnerdb91b162007-06-02 00:16:28 +0000462//===--------------------------------------------------------------------===//
463// Binary Operator Emission
464//===--------------------------------------------------------------------===//
465
466// FIXME describe.
Chris Lattnercf250242007-06-03 02:02:44 +0000467QualType CodeGenFunction::
Chris Lattner8394d792007-06-05 20:53:16 +0000468EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
469 RValue &RHS) {
Chris Lattnerc18f9d12007-06-02 22:51:30 +0000470 QualType LHSType, RHSType;
471 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
472 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
473
Chris Lattnercf250242007-06-03 02:02:44 +0000474 // If both operands have the same source type, we're done already.
475 if (LHSType == RHSType) return LHSType;
476
477 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
478 // The caller can deal with this (e.g. pointer + int).
479 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
480 return LHSType;
481
482 // At this point, we have two different arithmetic types.
483
484 // Handle complex types first (C99 6.3.1.8p1).
485 if (LHSType->isComplexType() || RHSType->isComplexType()) {
486 assert(0 && "FIXME: complex types unimp");
487#if 0
488 // if we have an integer operand, the result is the complex type.
489 if (rhs->isIntegerType())
490 return lhs;
491 if (lhs->isIntegerType())
492 return rhs;
493 return Context.maxComplexType(lhs, rhs);
494#endif
495 }
496
497 // If neither operand is complex, they must be scalars.
498 llvm::Value *LHSV = LHS.getVal();
499 llvm::Value *RHSV = RHS.getVal();
500
501 // If the LLVM types are already equal, then they only differed in sign, or it
502 // was something like char/signed char or double/long double.
503 if (LHSV->getType() == RHSV->getType())
504 return LHSType;
505
506 // Now handle "real" floating types (i.e. float, double, long double).
507 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
508 // if we have an integer operand, the result is the real floating type, and
509 // the integer converts to FP.
510 if (RHSType->isIntegerType()) {
511 // Promote the RHS to an FP type of the LHS, with the sign following the
512 // RHS.
513 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000514 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000515 else
Chris Lattner8394d792007-06-05 20:53:16 +0000516 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000517 return LHSType;
518 }
519
520 if (LHSType->isIntegerType()) {
521 // Promote the LHS to an FP type of the RHS, with the sign following the
522 // LHS.
523 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000524 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000525 else
Chris Lattner8394d792007-06-05 20:53:16 +0000526 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000527 return RHSType;
528 }
529
530 // Otherwise, they are two FP types. Promote the smaller operand to the
531 // bigger result.
532 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
533
534 if (BiggerType == LHSType)
Chris Lattner8394d792007-06-05 20:53:16 +0000535 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000536 else
Chris Lattner8394d792007-06-05 20:53:16 +0000537 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000538 return BiggerType;
539 }
540
541 // Finally, we have two integer types that are different according to C. Do
542 // a sign or zero extension if needed.
543
544 // Otherwise, one type is smaller than the other.
545 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
546
547 if (LHSType == ResTy) {
548 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000549 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000550 else
Chris Lattner8394d792007-06-05 20:53:16 +0000551 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000552 } else {
553 assert(RHSType == ResTy && "Unknown conversion");
554 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000555 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000556 else
Chris Lattner8394d792007-06-05 20:53:16 +0000557 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000558 }
559 return ResTy;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000560}
561
562
Chris Lattner8394d792007-06-05 20:53:16 +0000563RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
Chris Lattnerdb91b162007-06-02 00:16:28 +0000564 switch (E->getOpcode()) {
565 default:
Chris Lattner8394d792007-06-05 20:53:16 +0000566 fprintf(stderr, "Unimplemented expr!\n");
Chris Lattnerdb91b162007-06-02 00:16:28 +0000567 E->dump();
Chris Lattner8394d792007-06-05 20:53:16 +0000568 return RValue::get(UndefValue::get(llvm::Type::Int32Ty));
569 case BinaryOperator::Mul: return EmitBinaryMul(E);
570 case BinaryOperator::Div: return EmitBinaryDiv(E);
571 case BinaryOperator::Rem: return EmitBinaryRem(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +0000572 case BinaryOperator::Add: return EmitBinaryAdd(E);
Chris Lattner8394d792007-06-05 20:53:16 +0000573 case BinaryOperator::Sub: return EmitBinarySub(E);
574 case BinaryOperator::Shl: return EmitBinaryShl(E);
575 case BinaryOperator::Shr: return EmitBinaryShr(E);
576
577 // FIXME: relational
578
579 case BinaryOperator::And: return EmitBinaryAnd(E);
580 case BinaryOperator::Xor: return EmitBinaryXor(E);
581 case BinaryOperator::Or : return EmitBinaryOr(E);
582 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
583 case BinaryOperator::LOr: return EmitBinaryLOr(E);
584
585 case BinaryOperator::Assign: return EmitBinaryAssign(E);
586 // FIXME: Assignment.
587 case BinaryOperator::Comma: return EmitBinaryComma(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +0000588 }
589}
590
Chris Lattner8394d792007-06-05 20:53:16 +0000591RValue CodeGenFunction::EmitBinaryMul(const BinaryOperator *E) {
592 RValue LHS, RHS;
593 EmitUsualArithmeticConversions(E, LHS, RHS);
Chris Lattnerdb91b162007-06-02 00:16:28 +0000594
Chris Lattner8394d792007-06-05 20:53:16 +0000595 if (LHS.isScalar())
596 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
597
598 assert(0 && "FIXME: This doesn't handle complex operands yet");
599}
600
601RValue CodeGenFunction::EmitBinaryDiv(const BinaryOperator *E) {
602 RValue LHS, RHS;
603 EmitUsualArithmeticConversions(E, LHS, RHS);
604
605 if (LHS.isScalar()) {
606 Value *RV;
607 if (LHS.getVal()->getType()->isFloatingPoint())
608 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
609 else if (E->getType()->isUnsignedIntegerType())
610 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
611 else
612 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
613 return RValue::get(RV);
614 }
615 assert(0 && "FIXME: This doesn't handle complex operands yet");
616}
617
618RValue CodeGenFunction::EmitBinaryRem(const BinaryOperator *E) {
619 RValue LHS, RHS;
620 EmitUsualArithmeticConversions(E, LHS, RHS);
621
622 if (LHS.isScalar()) {
623 Value *RV;
624 // Rem in C can't be a floating point type: C99 6.5.5p2.
625 if (E->getType()->isUnsignedIntegerType())
626 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
627 else
628 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
629 return RValue::get(RV);
630 }
631
632 assert(0 && "FIXME: This doesn't handle complex operands yet");
633}
634
635RValue CodeGenFunction::EmitBinaryAdd(const BinaryOperator *E) {
636 RValue LHS, RHS;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000637 EmitUsualArithmeticConversions(E, LHS, RHS);
638
Chris Lattner8394d792007-06-05 20:53:16 +0000639 // FIXME: This doesn't handle ptr+int etc yet.
640
641 if (LHS.isScalar())
642 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
643
644 assert(0 && "FIXME: This doesn't handle complex operands yet");
645
646}
647
648RValue CodeGenFunction::EmitBinarySub(const BinaryOperator *E) {
649 RValue LHS, RHS;
650 EmitUsualArithmeticConversions(E, LHS, RHS);
651
652 // FIXME: This doesn't handle ptr-int or ptr-ptr, etc yet.
653
654 if (LHS.isScalar())
655 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
656
657 assert(0 && "FIXME: This doesn't handle complex operands yet");
658
659}
660
661RValue CodeGenFunction::EmitBinaryShl(const BinaryOperator *E) {
662 // For shifts, integer promotions are performed, but the usual arithmetic
663 // conversions are not. The LHS and RHS need not have the same type.
664
665 QualType ResTy;
666 Value *LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy).getVal();
667 Value *RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy).getVal();
668
669 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
670 // RHS to the same size as the LHS.
671 if (LHS->getType() != RHS->getType())
672 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
673
674 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
675}
676
677RValue CodeGenFunction::EmitBinaryShr(const BinaryOperator *E) {
678 // For shifts, integer promotions are performed, but the usual arithmetic
679 // conversions are not. The LHS and RHS need not have the same type.
680
681 QualType ResTy;
682 Value *LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy).getVal();
683 Value *RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy).getVal();
684
685 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
686 // RHS to the same size as the LHS.
687 if (LHS->getType() != RHS->getType())
688 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
689
690 if (E->getType()->isUnsignedIntegerType())
691 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
692 else
693 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
694}
695
696RValue CodeGenFunction::EmitBinaryAnd(const BinaryOperator *E) {
697 RValue LHS, RHS;
698 EmitUsualArithmeticConversions(E, LHS, RHS);
699
700 if (LHS.isScalar())
701 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
702
703 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
704}
705
706RValue CodeGenFunction::EmitBinaryXor(const BinaryOperator *E) {
707 RValue LHS, RHS;
708 EmitUsualArithmeticConversions(E, LHS, RHS);
709
710 if (LHS.isScalar())
711 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
712
713 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
714}
715
716RValue CodeGenFunction::EmitBinaryOr(const BinaryOperator *E) {
717 RValue LHS, RHS;
718 EmitUsualArithmeticConversions(E, LHS, RHS);
719
720 if (LHS.isScalar())
721 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
722
723 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
724}
725
726RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
727 Value *LHSCond = EvaluateExprAsBool(E->getLHS());
728
729 BasicBlock *ContBlock = new BasicBlock("land_cont");
730 BasicBlock *RHSBlock = new BasicBlock("land_rhs");
731
732 BasicBlock *OrigBlock = Builder.GetInsertBlock();
733 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
734
735 EmitBlock(RHSBlock);
736 Value *RHSCond = EvaluateExprAsBool(E->getRHS());
737
738 // Reaquire the RHS block, as there may be subblocks inserted.
739 RHSBlock = Builder.GetInsertBlock();
740 EmitBlock(ContBlock);
741
742 // Create a PHI node. If we just evaluted the LHS condition, the result is
743 // false. If we evaluated both, the result is the RHS condition.
744 PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
745 PN->reserveOperandSpace(2);
746 PN->addIncoming(ConstantInt::getFalse(), OrigBlock);
747 PN->addIncoming(RHSCond, RHSBlock);
748
749 // ZExt result to int.
750 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
751}
752
753RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
754 Value *LHSCond = EvaluateExprAsBool(E->getLHS());
755
756 BasicBlock *ContBlock = new BasicBlock("lor_cont");
757 BasicBlock *RHSBlock = new BasicBlock("lor_rhs");
758
759 BasicBlock *OrigBlock = Builder.GetInsertBlock();
760 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
761
762 EmitBlock(RHSBlock);
763 Value *RHSCond = EvaluateExprAsBool(E->getRHS());
764
765 // Reaquire the RHS block, as there may be subblocks inserted.
766 RHSBlock = Builder.GetInsertBlock();
767 EmitBlock(ContBlock);
768
769 // Create a PHI node. If we just evaluted the LHS condition, the result is
770 // true. If we evaluated both, the result is the RHS condition.
771 PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
772 PN->reserveOperandSpace(2);
773 PN->addIncoming(ConstantInt::getTrue(), OrigBlock);
774 PN->addIncoming(RHSCond, RHSBlock);
775
776 // ZExt result to int.
777 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
778}
779
780RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
781 LValue LHS = EmitLValue(E->getLHS());
782
783 QualType RHSTy;
784 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
785
786 // Convert the RHS to the type of the LHS.
Chris Lattnercf106ab2007-06-06 04:05:39 +0000787 // FIXME: I'm not thrilled about having to call getLocStart() here... :(
788 RHS = EmitConversion(RHS, RHSTy, E->getType(), E->getLocStart());
Chris Lattner8394d792007-06-05 20:53:16 +0000789
790 // Store the value into the LHS.
791 EmitStoreThroughLValue(RHS, LHS, E->getType());
792
793 // Return the converted RHS.
794 return RHS;
795}
796
797
798RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
799 EmitExpr(E->getLHS());
800 return EmitExpr(E->getRHS());
801}