blob: d9114beb1145c78b2fe9c872edbe5082b61ffb9b [file] [log] [blame]
Chris Lattner9fba49a2007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
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 with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/Function.h"
19#include "llvm/Support/Compiler.h"
20using namespace clang;
21using namespace CodeGen;
22using llvm::Value;
23
24//===----------------------------------------------------------------------===//
25// Scalar Expression Emitter
26//===----------------------------------------------------------------------===//
27
28struct BinOpInfo {
29 Value *LHS;
30 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000031 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000032 const BinaryOperator *E;
33};
34
35namespace {
36class VISIBILITY_HIDDEN ScalarExprEmitter
37 : public StmtVisitor<ScalarExprEmitter, Value*> {
38 CodeGenFunction &CGF;
39 llvm::LLVMBuilder &Builder;
40public:
41
42 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
43 }
44
45
46 //===--------------------------------------------------------------------===//
47 // Utilities
48 //===--------------------------------------------------------------------===//
49
50 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
51 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
52
53 Value *EmitLoadOfLValue(LValue LV, QualType T) {
54 return CGF.EmitLoadOfLValue(LV, T).getVal();
55 }
56
57 /// EmitLoadOfLValue - Given an expression with complex type that represents a
58 /// value l-value, this method emits the address of the l-value, then loads
59 /// and returns the result.
60 Value *EmitLoadOfLValue(const Expr *E) {
61 // FIXME: Volatile
62 return EmitLoadOfLValue(EmitLValue(E), E->getType());
63 }
64
Chris Lattner4e05d1e2007-08-26 06:48:56 +000065 /// EmitScalarConversion - Emit a conversion from the specified type to the
66 /// specified destination type, both of which are LLVM scalar types.
67 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
68 QualType DstTy);
69
70
Chris Lattner9fba49a2007-08-24 05:35:26 +000071 //===--------------------------------------------------------------------===//
72 // Visitor Methods
73 //===--------------------------------------------------------------------===//
74
75 Value *VisitStmt(Stmt *S) {
76 S->dump();
77 assert(0 && "Stmt can't have complex result type!");
78 return 0;
79 }
80 Value *VisitExpr(Expr *S);
81 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
82
83 // Leaves.
84 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
85 return llvm::ConstantInt::get(E->getValue());
86 }
87 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
88 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
89 }
90 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
91 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
92 }
93 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
94 return llvm::ConstantInt::get(ConvertType(E->getType()),
95 E->typesAreCompatible());
96 }
97 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
98 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
99 }
100
101 // l-values.
102 Value *VisitDeclRefExpr(DeclRefExpr *E) {
103 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
104 return llvm::ConstantInt::get(EC->getInitVal());
105 return EmitLoadOfLValue(E);
106 }
107 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
108 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
109 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
110 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
111 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
112
113 // FIXME: CompoundLiteralExpr
114 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
115 Value *VisitCastExpr(const CastExpr *E) {
116 return EmitCastExpr(E->getSubExpr(), E->getType());
117 }
118 Value *EmitCastExpr(const Expr *E, QualType T);
119
120 Value *VisitCallExpr(const CallExpr *E) {
121 return CGF.EmitCallExpr(E).getVal();
122 }
123
124 // Unary Operators.
125 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
126 Value *VisitUnaryPostDec(const UnaryOperator *E) {
127 return VisitPrePostIncDec(E, false, false);
128 }
129 Value *VisitUnaryPostInc(const UnaryOperator *E) {
130 return VisitPrePostIncDec(E, true, false);
131 }
132 Value *VisitUnaryPreDec(const UnaryOperator *E) {
133 return VisitPrePostIncDec(E, false, true);
134 }
135 Value *VisitUnaryPreInc(const UnaryOperator *E) {
136 return VisitPrePostIncDec(E, true, true);
137 }
138 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
139 return EmitLValue(E->getSubExpr()).getAddress();
140 }
141 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
142 Value *VisitUnaryPlus(const UnaryOperator *E) {
143 return Visit(E->getSubExpr());
144 }
145 Value *VisitUnaryMinus (const UnaryOperator *E);
146 Value *VisitUnaryNot (const UnaryOperator *E);
147 Value *VisitUnaryLNot (const UnaryOperator *E);
148 Value *VisitUnarySizeOf (const UnaryOperator *E) {
149 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
150 }
151 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
152 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
153 }
154 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
155 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000156 Value *VisitUnaryReal (const UnaryOperator *E);
157 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000158 Value *VisitUnaryExtension(const UnaryOperator *E) {
159 return Visit(E->getSubExpr());
160 }
161
162 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000163 Value *EmitMul(const BinOpInfo &Ops) {
164 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
165 }
166 Value *EmitDiv(const BinOpInfo &Ops);
167 Value *EmitRem(const BinOpInfo &Ops);
168 Value *EmitAdd(const BinOpInfo &Ops);
169 Value *EmitSub(const BinOpInfo &Ops);
170 Value *EmitShl(const BinOpInfo &Ops);
171 Value *EmitShr(const BinOpInfo &Ops);
172 Value *EmitAnd(const BinOpInfo &Ops) {
173 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
174 }
175 Value *EmitXor(const BinOpInfo &Ops) {
176 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
177 }
178 Value *EmitOr (const BinOpInfo &Ops) {
179 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
180 }
181
Chris Lattner660e31d2007-08-24 21:00:35 +0000182 BinOpInfo EmitBinOps(const BinaryOperator *E);
183 Value *EmitCompoundAssign(const BinaryOperator *E,
184 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
185
186 // Binary operators and binary compound assignment operators.
187#define HANDLEBINOP(OP) \
188 Value *VisitBin ## OP(const BinaryOperator *E) { \
189 return Emit ## OP(EmitBinOps(E)); \
190 } \
191 Value *VisitBin ## OP ## Assign(const BinaryOperator *E) { \
192 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
193 }
194 HANDLEBINOP(Mul);
195 HANDLEBINOP(Div);
196 HANDLEBINOP(Rem);
197 HANDLEBINOP(Add);
198 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
199 HANDLEBINOP(Shl);
200 HANDLEBINOP(Shr);
201 HANDLEBINOP(And);
202 HANDLEBINOP(Xor);
203 HANDLEBINOP(Or);
204#undef HANDLEBINOP
205 Value *VisitBinSub(const BinaryOperator *E);
206 Value *VisitBinSubAssign(const BinaryOperator *E) {
207 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
208 }
209
Chris Lattner9fba49a2007-08-24 05:35:26 +0000210 // Comparisons.
211 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
212 unsigned SICmpOpc, unsigned FCmpOpc);
213#define VISITCOMP(CODE, UI, SI, FP) \
214 Value *VisitBin##CODE(const BinaryOperator *E) { \
215 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
216 llvm::FCmpInst::FP); }
217 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
218 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
219 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
220 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
221 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
222 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
223#undef VISITCOMP
224
225 Value *VisitBinAssign (const BinaryOperator *E);
226
227 Value *VisitBinLAnd (const BinaryOperator *E);
228 Value *VisitBinLOr (const BinaryOperator *E);
229
230 // FIXME: Compound assignment operators.
231 Value *VisitBinComma (const BinaryOperator *E);
232
233 // Other Operators.
234 Value *VisitConditionalOperator(const ConditionalOperator *CO);
235 Value *VisitChooseExpr(ChooseExpr *CE);
236 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
237 return CGF.EmitObjCStringLiteral(E);
238 }
239};
240} // end anonymous namespace.
241
242//===----------------------------------------------------------------------===//
243// Utilities
244//===----------------------------------------------------------------------===//
245
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000246/// EmitScalarConversion - Emit a conversion from the specified type to the
247/// specified destination type, both of which are LLVM scalar types.
248llvm::Value *ScalarExprEmitter::EmitScalarConversion(llvm::Value *Src,
249 QualType SrcType,
250 QualType DstType) {
251 SrcType = SrcType.getCanonicalType();
252 DstType = DstType.getCanonicalType();
253 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000254
255 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000256
257 // Handle conversions to bool first, they are special: comparisons against 0.
258 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstType))
259 if (DestBT->getKind() == BuiltinType::Bool)
260 return CGF.ConvertScalarValueToBool(RValue::get(Src), SrcType);
261
262 const llvm::Type *DstTy = ConvertType(DstType);
263
264 // Ignore conversions like int -> uint.
265 if (Src->getType() == DstTy)
266 return Src;
267
268 // Handle pointer conversions next: pointers can only be converted to/from
269 // other pointers and integers.
270 if (isa<PointerType>(DstType)) {
271 // The source value may be an integer, or a pointer.
272 if (isa<llvm::PointerType>(Src->getType()))
273 return Builder.CreateBitCast(Src, DstTy, "conv");
274 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
275 return Builder.CreateIntToPtr(Src, DstTy, "conv");
276 }
277
278 if (isa<PointerType>(SrcType)) {
279 // Must be an ptr to int cast.
280 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
281 return Builder.CreateIntToPtr(Src, DstTy, "conv");
282 }
283
284 // Finally, we have the arithmetic types: real int/float.
285 if (isa<llvm::IntegerType>(Src->getType())) {
286 bool InputSigned = SrcType->isSignedIntegerType();
287 if (isa<llvm::IntegerType>(DstTy))
288 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
289 else if (InputSigned)
290 return Builder.CreateSIToFP(Src, DstTy, "conv");
291 else
292 return Builder.CreateUIToFP(Src, DstTy, "conv");
293 }
294
295 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
296 if (isa<llvm::IntegerType>(DstTy)) {
297 if (DstType->isSignedIntegerType())
298 return Builder.CreateFPToSI(Src, DstTy, "conv");
299 else
300 return Builder.CreateFPToUI(Src, DstTy, "conv");
301 }
302
303 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
304 if (DstTy->getTypeID() < Src->getType()->getTypeID())
305 return Builder.CreateFPTrunc(Src, DstTy, "conv");
306 else
307 return Builder.CreateFPExt(Src, DstTy, "conv");
308}
309
Chris Lattner9fba49a2007-08-24 05:35:26 +0000310//===----------------------------------------------------------------------===//
311// Visitor Methods
312//===----------------------------------------------------------------------===//
313
314Value *ScalarExprEmitter::VisitExpr(Expr *E) {
315 fprintf(stderr, "Unimplemented scalar expr!\n");
316 E->dump();
317 if (E->getType()->isVoidType())
318 return 0;
319 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
320}
321
322Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
323 // Emit subscript expressions in rvalue context's. For most cases, this just
324 // loads the lvalue formed by the subscript expr. However, we have to be
325 // careful, because the base of a vector subscript is occasionally an rvalue,
326 // so we can't get it as an lvalue.
327 if (!E->getBase()->getType()->isVectorType())
328 return EmitLoadOfLValue(E);
329
330 // Handle the vector case. The base must be a vector, the index must be an
331 // integer value.
332 Value *Base = Visit(E->getBase());
333 Value *Idx = Visit(E->getIdx());
334
335 // FIXME: Convert Idx to i32 type.
336 return Builder.CreateExtractElement(Base, Idx, "vecext");
337}
338
339/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
340/// also handle things like function to pointer-to-function decay, and array to
341/// pointer decay.
342Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
343 const Expr *Op = E->getSubExpr();
344
345 // If this is due to array->pointer conversion, emit the array expression as
346 // an l-value.
347 if (Op->getType()->isArrayType()) {
348 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
349 // will not true when we add support for VLAs.
350 llvm::Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
351
352 assert(isa<llvm::PointerType>(V->getType()) &&
353 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
354 ->getElementType()) &&
355 "Doesn't support VLAs yet!");
356 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
357 return Builder.CreateGEP(V, Idx0, Idx0, "arraydecay");
358 }
359
360 return EmitCastExpr(Op, E->getType());
361}
362
363
364// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
365// have to handle a more broad range of conversions than explicit casts, as they
366// handle things like function to ptr-to-function decay etc.
367Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000368 // Handle cases where the source is an non-complex type.
369 const ComplexType *CT = E->getType()->getAsComplexType();
370 if (!CT) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000371 Value *Src = Visit(const_cast<Expr*>(E));
372
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000373 // Use EmitScalarConversion to perform the conversion.
374 return EmitScalarConversion(Src, E->getType(), DestTy);
375 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000376
Chris Lattner82e10392007-08-26 07:26:12 +0000377 // Handle cases where the source is a complex type.
378
379 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
380 // the imaginary part of the complex value is discarded and the value of the
381 // real part is converted according to the conversion rules for the
382 // corresponding real type.
383 Value *Src = CGF.EmitComplexExpr(E).first;
384 return EmitScalarConversion(Src, CT->getElementType(), DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000385}
386
387//===----------------------------------------------------------------------===//
388// Unary Operators
389//===----------------------------------------------------------------------===//
390
391Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000392 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000393 LValue LV = EmitLValue(E->getSubExpr());
394 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000395 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
396 E->getSubExpr()->getType()).getVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000397
398 int AmountVal = isInc ? 1 : -1;
399
400 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000401 if (isa<llvm::PointerType>(InVal->getType())) {
402 // FIXME: This isn't right for VLAs.
403 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
404 NextVal = Builder.CreateGEP(InVal, NextVal);
405 } else {
406 // Add the inc/dec to the real part.
407 if (isa<llvm::IntegerType>(InVal->getType()))
408 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
409 else
410 NextVal = llvm::ConstantFP::get(InVal->getType(), AmountVal);
411 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
412 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000413
414 // Store the updated result through the lvalue.
415 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
416 E->getSubExpr()->getType());
417
418 // If this is a postinc, return the value read from memory, otherwise use the
419 // updated value.
420 return isPre ? NextVal : InVal;
421}
422
423
424Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
425 Value *Op = Visit(E->getSubExpr());
426 return Builder.CreateNeg(Op, "neg");
427}
428
429Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
430 Value *Op = Visit(E->getSubExpr());
431 return Builder.CreateNot(Op, "neg");
432}
433
434Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
435 // Compare operand to zero.
436 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
437
438 // Invert value.
439 // TODO: Could dynamically modify easy computations here. For example, if
440 // the operand is an icmp ne, turn into icmp eq.
441 BoolVal = Builder.CreateNot(BoolVal, "lnot");
442
443 // ZExt result to int.
444 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
445}
446
447/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
448/// an integer (RetType).
449Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000450 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000451 /// FIXME: This doesn't handle VLAs yet!
452 std::pair<uint64_t, unsigned> Info =
453 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
454
455 uint64_t Val = isSizeOf ? Info.first : Info.second;
456 Val /= 8; // Return size in bytes, not bits.
457
458 assert(RetType->isIntegerType() && "Result type must be an integer!");
459
460 unsigned ResultWidth = CGF.getContext().getTypeSize(RetType,SourceLocation());
461 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
462}
463
Chris Lattner01211af2007-08-24 21:20:17 +0000464Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
465 Expr *Op = E->getSubExpr();
466 if (Op->getType()->isComplexType())
467 return CGF.EmitComplexExpr(Op).first;
468 return Visit(Op);
469}
470Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
471 Expr *Op = E->getSubExpr();
472 if (Op->getType()->isComplexType())
473 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000474
475 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
476 // effects are evaluated.
477 CGF.EmitScalarExpr(Op);
478 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000479}
480
481
Chris Lattner9fba49a2007-08-24 05:35:26 +0000482//===----------------------------------------------------------------------===//
483// Binary Operators
484//===----------------------------------------------------------------------===//
485
486BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
487 BinOpInfo Result;
488 Result.LHS = Visit(E->getLHS());
489 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000490 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000491 Result.E = E;
492 return Result;
493}
494
Chris Lattner660e31d2007-08-24 21:00:35 +0000495Value *ScalarExprEmitter::EmitCompoundAssign(const BinaryOperator *E,
496 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
497 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
498
499 BinOpInfo OpInfo;
500
501 // Load the LHS and RHS operands.
502 LValue LHSLV = EmitLValue(E->getLHS());
503 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
504
505 // FIXME: It is possible for the RHS to be complex.
506 OpInfo.RHS = Visit(E->getRHS());
507
508 // Convert the LHS/RHS values to the computation type.
509 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
510 QualType ComputeType = CAO->getComputationType();
511
512 // FIXME: it's possible for the computation type to be complex if the RHS
513 // is complex. Handle this!
Chris Lattnerb1497062007-08-26 07:08:39 +0000514 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000515
516 // Do not merge types for -= where the LHS is a pointer.
Chris Lattner42330c32007-08-25 21:56:20 +0000517 if (E->getOpcode() != BinaryOperator::SubAssign ||
518 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000519 // FIXME: the computation type may be complex.
520 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000521 }
522 OpInfo.Ty = ComputeType;
523 OpInfo.E = E;
524
525 // Expand the binary operator.
526 Value *Result = (this->*Func)(OpInfo);
527
528 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000529 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000530
531 // Store the result value into the LHS lvalue.
532 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
533
534 return Result;
535}
536
537
Chris Lattner9fba49a2007-08-24 05:35:26 +0000538Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
539 if (Ops.LHS->getType()->isFloatingPoint())
540 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000541 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000542 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
543 else
544 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
545}
546
547Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
548 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000549 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000550 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
551 else
552 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
553}
554
555
556Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000557 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000558 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000559
560 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000561 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
562 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
563 // int + pointer
564 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
565}
566
567Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
568 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
569 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
570
Chris Lattner660e31d2007-08-24 21:00:35 +0000571 // pointer - int
572 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
573 "ptr-ptr shouldn't get here");
574 // FIXME: The pointer could point to a VLA.
575 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
576 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
577}
578
579Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
580 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
581 // the compound assignment case it is invalid, so just handle it here.
582 if (!E->getRHS()->getType()->isPointerType())
583 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000584
585 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000586 Value *LHS = Visit(E->getLHS());
587 Value *RHS = Visit(E->getRHS());
588
589 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
590 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
591 "Can't subtract different pointer types");
592
Chris Lattner9fba49a2007-08-24 05:35:26 +0000593 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000594 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
595 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000596
597 const llvm::Type *ResultType = ConvertType(E->getType());
598 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
599 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
600 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000601
602 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
603 // remainder. As such, we handle common power-of-two cases here to generate
604 // better code.
605 if (llvm::isPowerOf2_64(ElementSize)) {
606 Value *ShAmt =
607 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
608 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
609 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000610
Chris Lattner9fba49a2007-08-24 05:35:26 +0000611 // Otherwise, do a full sdiv.
612 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
613 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
614}
615
Chris Lattner660e31d2007-08-24 21:00:35 +0000616
Chris Lattner9fba49a2007-08-24 05:35:26 +0000617Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
618 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
619 // RHS to the same size as the LHS.
620 Value *RHS = Ops.RHS;
621 if (Ops.LHS->getType() != RHS->getType())
622 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
623
624 return Builder.CreateShl(Ops.LHS, RHS, "shl");
625}
626
627Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
628 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
629 // RHS to the same size as the LHS.
630 Value *RHS = Ops.RHS;
631 if (Ops.LHS->getType() != RHS->getType())
632 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
633
Chris Lattner660e31d2007-08-24 21:00:35 +0000634 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000635 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
636 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
637}
638
639Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
640 unsigned SICmpOpc, unsigned FCmpOpc) {
641 llvm::Value *Result;
642 QualType LHSTy = E->getLHS()->getType();
643 if (!LHSTy->isComplexType()) {
644 Value *LHS = Visit(E->getLHS());
645 Value *RHS = Visit(E->getRHS());
646
647 if (LHS->getType()->isFloatingPoint()) {
648 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
649 LHS, RHS, "cmp");
650 } else if (LHSTy->isUnsignedIntegerType()) {
651 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
652 LHS, RHS, "cmp");
653 } else {
654 // Signed integers and pointers.
655 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
656 LHS, RHS, "cmp");
657 }
658 } else {
659 // Complex Comparison: can only be an equality comparison.
660 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
661 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
662
663 QualType CETy =
664 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
665
666 llvm::Value *ResultR, *ResultI;
667 if (CETy->isRealFloatingType()) {
668 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
669 LHS.first, RHS.first, "cmp.r");
670 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
671 LHS.second, RHS.second, "cmp.i");
672 } else {
673 // Complex comparisons can only be equality comparisons. As such, signed
674 // and unsigned opcodes are the same.
675 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
676 LHS.first, RHS.first, "cmp.r");
677 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
678 LHS.second, RHS.second, "cmp.i");
679 }
680
681 if (E->getOpcode() == BinaryOperator::EQ) {
682 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
683 } else {
684 assert(E->getOpcode() == BinaryOperator::NE &&
685 "Complex comparison other than == or != ?");
686 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
687 }
688 }
689
690 // ZExt result to int.
691 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
692}
693
694Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
695 LValue LHS = EmitLValue(E->getLHS());
696 Value *RHS = Visit(E->getRHS());
697
698 // Store the value into the LHS.
699 // FIXME: Volatility!
700 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
701
702 // Return the RHS.
703 return RHS;
704}
705
706Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
707 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
708
709 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
710 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
711
712 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
713 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
714
715 CGF.EmitBlock(RHSBlock);
716 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
717
718 // Reaquire the RHS block, as there may be subblocks inserted.
719 RHSBlock = Builder.GetInsertBlock();
720 CGF.EmitBlock(ContBlock);
721
722 // Create a PHI node. If we just evaluted the LHS condition, the result is
723 // false. If we evaluated both, the result is the RHS condition.
724 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
725 PN->reserveOperandSpace(2);
726 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
727 PN->addIncoming(RHSCond, RHSBlock);
728
729 // ZExt result to int.
730 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
731}
732
733Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
734 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
735
736 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
737 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
738
739 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
740 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
741
742 CGF.EmitBlock(RHSBlock);
743 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
744
745 // Reaquire the RHS block, as there may be subblocks inserted.
746 RHSBlock = Builder.GetInsertBlock();
747 CGF.EmitBlock(ContBlock);
748
749 // Create a PHI node. If we just evaluted the LHS condition, the result is
750 // true. If we evaluated both, the result is the RHS condition.
751 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
752 PN->reserveOperandSpace(2);
753 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
754 PN->addIncoming(RHSCond, RHSBlock);
755
756 // ZExt result to int.
757 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
758}
759
760Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
761 CGF.EmitStmt(E->getLHS());
762 return Visit(E->getRHS());
763}
764
765//===----------------------------------------------------------------------===//
766// Other Operators
767//===----------------------------------------------------------------------===//
768
769Value *ScalarExprEmitter::
770VisitConditionalOperator(const ConditionalOperator *E) {
771 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
772 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
773 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
774
775 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
776 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
777
778 CGF.EmitBlock(LHSBlock);
779
780 // Handle the GNU extension for missing LHS.
781 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
782 Builder.CreateBr(ContBlock);
783 LHSBlock = Builder.GetInsertBlock();
784
785 CGF.EmitBlock(RHSBlock);
786
787 Value *RHS = Visit(E->getRHS());
788 Builder.CreateBr(ContBlock);
789 RHSBlock = Builder.GetInsertBlock();
790
791 CGF.EmitBlock(ContBlock);
792
793 // Create a PHI node for the real part.
794 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
795 PN->reserveOperandSpace(2);
796 PN->addIncoming(LHS, LHSBlock);
797 PN->addIncoming(RHS, RHSBlock);
798 return PN;
799}
800
801Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
802 llvm::APSInt CondVal(32);
803 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
804 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
805
806 // Emit the LHS or RHS as appropriate.
807 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
808}
809
810//===----------------------------------------------------------------------===//
811// Entry Point into this File
812//===----------------------------------------------------------------------===//
813
814/// EmitComplexExpr - Emit the computation of the specified expression of
815/// complex type, ignoring the result.
816Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
817 assert(E && !hasAggregateLLVMType(E->getType()) &&
818 "Invalid scalar expression to emit");
819
820 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
821}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000822
823/// EmitScalarConversion - Emit a conversion from the specified type to the
824/// specified destination type, both of which are LLVM scalar types.
825llvm::Value *CodeGenFunction::EmitScalarConversion(llvm::Value *Src,
826 QualType SrcTy,
827 QualType DstTy) {
828 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
829 "Invalid scalar expression to emit");
830 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
831}