blob: ebe25c5a88f40a26a4c176e85b02d54179502287 [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 Lattner4e05d1e2007-08-26 06:48:56 +0000368 // Handle cases where the source is an LLVM Scalar type.
369 if (!CGF.hasAggregateLLVMType(E->getType())) {
370 Value *Src = Visit(const_cast<Expr*>(E));
371
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000372 // Use EmitScalarConversion to perform the conversion.
373 return EmitScalarConversion(Src, E->getType(), DestTy);
374 }
375
Chris Lattnere133d7f2007-08-26 07:21:11 +0000376 if (const ComplexType *CT = E->getType()->getAsComplexType()) {
377 // Emit the complex value, only keeping the real component. C99 6.3.1.7p2:
378 // "When a value of complex type is converted to a real type, the imaginary
379 // part of the complex value is discarded and the value of the real part is
380 // converted according to the conversion rules for the corresponding real
381 // type.
382 Value *Src = CGF.EmitComplexExpr(E).first;
383 return EmitScalarConversion(Src, CT->getElementType(), DestTy);
384 }
385
Chris Lattner9fba49a2007-08-24 05:35:26 +0000386 RValue Src = CGF.EmitAnyExpr(E);
387
388 // If the destination is void, just evaluate the source.
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000389 if (DestTy->isVoidType()) return 0;
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000390
391 assert(0 && "Can't convert from an aggregate yet!");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000392}
393
394//===----------------------------------------------------------------------===//
395// Unary Operators
396//===----------------------------------------------------------------------===//
397
398Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000399 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000400 LValue LV = EmitLValue(E->getSubExpr());
401 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000402 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
403 E->getSubExpr()->getType()).getVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000404
405 int AmountVal = isInc ? 1 : -1;
406
407 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000408 if (isa<llvm::PointerType>(InVal->getType())) {
409 // FIXME: This isn't right for VLAs.
410 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
411 NextVal = Builder.CreateGEP(InVal, NextVal);
412 } else {
413 // Add the inc/dec to the real part.
414 if (isa<llvm::IntegerType>(InVal->getType()))
415 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
416 else
417 NextVal = llvm::ConstantFP::get(InVal->getType(), AmountVal);
418 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
419 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000420
421 // Store the updated result through the lvalue.
422 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
423 E->getSubExpr()->getType());
424
425 // If this is a postinc, return the value read from memory, otherwise use the
426 // updated value.
427 return isPre ? NextVal : InVal;
428}
429
430
431Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
432 Value *Op = Visit(E->getSubExpr());
433 return Builder.CreateNeg(Op, "neg");
434}
435
436Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
437 Value *Op = Visit(E->getSubExpr());
438 return Builder.CreateNot(Op, "neg");
439}
440
441Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
442 // Compare operand to zero.
443 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
444
445 // Invert value.
446 // TODO: Could dynamically modify easy computations here. For example, if
447 // the operand is an icmp ne, turn into icmp eq.
448 BoolVal = Builder.CreateNot(BoolVal, "lnot");
449
450 // ZExt result to int.
451 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
452}
453
454/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
455/// an integer (RetType).
456Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000457 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000458 /// FIXME: This doesn't handle VLAs yet!
459 std::pair<uint64_t, unsigned> Info =
460 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
461
462 uint64_t Val = isSizeOf ? Info.first : Info.second;
463 Val /= 8; // Return size in bytes, not bits.
464
465 assert(RetType->isIntegerType() && "Result type must be an integer!");
466
467 unsigned ResultWidth = CGF.getContext().getTypeSize(RetType,SourceLocation());
468 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
469}
470
Chris Lattner01211af2007-08-24 21:20:17 +0000471Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
472 Expr *Op = E->getSubExpr();
473 if (Op->getType()->isComplexType())
474 return CGF.EmitComplexExpr(Op).first;
475 return Visit(Op);
476}
477Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
478 Expr *Op = E->getSubExpr();
479 if (Op->getType()->isComplexType())
480 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000481
482 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
483 // effects are evaluated.
484 CGF.EmitScalarExpr(Op);
485 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000486}
487
488
Chris Lattner9fba49a2007-08-24 05:35:26 +0000489//===----------------------------------------------------------------------===//
490// Binary Operators
491//===----------------------------------------------------------------------===//
492
493BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
494 BinOpInfo Result;
495 Result.LHS = Visit(E->getLHS());
496 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000497 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000498 Result.E = E;
499 return Result;
500}
501
Chris Lattner660e31d2007-08-24 21:00:35 +0000502Value *ScalarExprEmitter::EmitCompoundAssign(const BinaryOperator *E,
503 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
504 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
505
506 BinOpInfo OpInfo;
507
508 // Load the LHS and RHS operands.
509 LValue LHSLV = EmitLValue(E->getLHS());
510 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
511
512 // FIXME: It is possible for the RHS to be complex.
513 OpInfo.RHS = Visit(E->getRHS());
514
515 // Convert the LHS/RHS values to the computation type.
516 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
517 QualType ComputeType = CAO->getComputationType();
518
519 // FIXME: it's possible for the computation type to be complex if the RHS
520 // is complex. Handle this!
Chris Lattnerb1497062007-08-26 07:08:39 +0000521 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000522
523 // Do not merge types for -= where the LHS is a pointer.
Chris Lattner42330c32007-08-25 21:56:20 +0000524 if (E->getOpcode() != BinaryOperator::SubAssign ||
525 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000526 // FIXME: the computation type may be complex.
527 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000528 }
529 OpInfo.Ty = ComputeType;
530 OpInfo.E = E;
531
532 // Expand the binary operator.
533 Value *Result = (this->*Func)(OpInfo);
534
535 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000536 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000537
538 // Store the result value into the LHS lvalue.
539 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
540
541 return Result;
542}
543
544
Chris Lattner9fba49a2007-08-24 05:35:26 +0000545Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
546 if (Ops.LHS->getType()->isFloatingPoint())
547 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000548 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000549 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
550 else
551 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
552}
553
554Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
555 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000556 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000557 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
558 else
559 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
560}
561
562
563Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000564 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000565 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000566
567 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000568 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
569 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
570 // int + pointer
571 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
572}
573
574Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
575 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
576 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
577
Chris Lattner660e31d2007-08-24 21:00:35 +0000578 // pointer - int
579 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
580 "ptr-ptr shouldn't get here");
581 // FIXME: The pointer could point to a VLA.
582 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
583 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
584}
585
586Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
587 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
588 // the compound assignment case it is invalid, so just handle it here.
589 if (!E->getRHS()->getType()->isPointerType())
590 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000591
592 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000593 Value *LHS = Visit(E->getLHS());
594 Value *RHS = Visit(E->getRHS());
595
596 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
597 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
598 "Can't subtract different pointer types");
599
Chris Lattner9fba49a2007-08-24 05:35:26 +0000600 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000601 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
602 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000603
604 const llvm::Type *ResultType = ConvertType(E->getType());
605 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
606 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
607 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000608
609 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
610 // remainder. As such, we handle common power-of-two cases here to generate
611 // better code.
612 if (llvm::isPowerOf2_64(ElementSize)) {
613 Value *ShAmt =
614 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
615 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
616 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000617
Chris Lattner9fba49a2007-08-24 05:35:26 +0000618 // Otherwise, do a full sdiv.
619 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
620 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
621}
622
Chris Lattner660e31d2007-08-24 21:00:35 +0000623
Chris Lattner9fba49a2007-08-24 05:35:26 +0000624Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
625 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
626 // RHS to the same size as the LHS.
627 Value *RHS = Ops.RHS;
628 if (Ops.LHS->getType() != RHS->getType())
629 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
630
631 return Builder.CreateShl(Ops.LHS, RHS, "shl");
632}
633
634Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
635 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
636 // RHS to the same size as the LHS.
637 Value *RHS = Ops.RHS;
638 if (Ops.LHS->getType() != RHS->getType())
639 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
640
Chris Lattner660e31d2007-08-24 21:00:35 +0000641 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000642 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
643 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
644}
645
646Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
647 unsigned SICmpOpc, unsigned FCmpOpc) {
648 llvm::Value *Result;
649 QualType LHSTy = E->getLHS()->getType();
650 if (!LHSTy->isComplexType()) {
651 Value *LHS = Visit(E->getLHS());
652 Value *RHS = Visit(E->getRHS());
653
654 if (LHS->getType()->isFloatingPoint()) {
655 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
656 LHS, RHS, "cmp");
657 } else if (LHSTy->isUnsignedIntegerType()) {
658 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
659 LHS, RHS, "cmp");
660 } else {
661 // Signed integers and pointers.
662 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
663 LHS, RHS, "cmp");
664 }
665 } else {
666 // Complex Comparison: can only be an equality comparison.
667 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
668 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
669
670 QualType CETy =
671 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
672
673 llvm::Value *ResultR, *ResultI;
674 if (CETy->isRealFloatingType()) {
675 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
676 LHS.first, RHS.first, "cmp.r");
677 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
678 LHS.second, RHS.second, "cmp.i");
679 } else {
680 // Complex comparisons can only be equality comparisons. As such, signed
681 // and unsigned opcodes are the same.
682 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
683 LHS.first, RHS.first, "cmp.r");
684 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
685 LHS.second, RHS.second, "cmp.i");
686 }
687
688 if (E->getOpcode() == BinaryOperator::EQ) {
689 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
690 } else {
691 assert(E->getOpcode() == BinaryOperator::NE &&
692 "Complex comparison other than == or != ?");
693 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
694 }
695 }
696
697 // ZExt result to int.
698 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
699}
700
701Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
702 LValue LHS = EmitLValue(E->getLHS());
703 Value *RHS = Visit(E->getRHS());
704
705 // Store the value into the LHS.
706 // FIXME: Volatility!
707 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
708
709 // Return the RHS.
710 return RHS;
711}
712
713Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
714 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
715
716 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
717 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
718
719 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
720 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
721
722 CGF.EmitBlock(RHSBlock);
723 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
724
725 // Reaquire the RHS block, as there may be subblocks inserted.
726 RHSBlock = Builder.GetInsertBlock();
727 CGF.EmitBlock(ContBlock);
728
729 // Create a PHI node. If we just evaluted the LHS condition, the result is
730 // false. If we evaluated both, the result is the RHS condition.
731 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
732 PN->reserveOperandSpace(2);
733 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
734 PN->addIncoming(RHSCond, RHSBlock);
735
736 // ZExt result to int.
737 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
738}
739
740Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
741 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
742
743 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
744 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
745
746 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
747 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
748
749 CGF.EmitBlock(RHSBlock);
750 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
751
752 // Reaquire the RHS block, as there may be subblocks inserted.
753 RHSBlock = Builder.GetInsertBlock();
754 CGF.EmitBlock(ContBlock);
755
756 // Create a PHI node. If we just evaluted the LHS condition, the result is
757 // true. If we evaluated both, the result is the RHS condition.
758 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
759 PN->reserveOperandSpace(2);
760 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
761 PN->addIncoming(RHSCond, RHSBlock);
762
763 // ZExt result to int.
764 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
765}
766
767Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
768 CGF.EmitStmt(E->getLHS());
769 return Visit(E->getRHS());
770}
771
772//===----------------------------------------------------------------------===//
773// Other Operators
774//===----------------------------------------------------------------------===//
775
776Value *ScalarExprEmitter::
777VisitConditionalOperator(const ConditionalOperator *E) {
778 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
779 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
780 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
781
782 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
783 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
784
785 CGF.EmitBlock(LHSBlock);
786
787 // Handle the GNU extension for missing LHS.
788 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
789 Builder.CreateBr(ContBlock);
790 LHSBlock = Builder.GetInsertBlock();
791
792 CGF.EmitBlock(RHSBlock);
793
794 Value *RHS = Visit(E->getRHS());
795 Builder.CreateBr(ContBlock);
796 RHSBlock = Builder.GetInsertBlock();
797
798 CGF.EmitBlock(ContBlock);
799
800 // Create a PHI node for the real part.
801 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
802 PN->reserveOperandSpace(2);
803 PN->addIncoming(LHS, LHSBlock);
804 PN->addIncoming(RHS, RHSBlock);
805 return PN;
806}
807
808Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
809 llvm::APSInt CondVal(32);
810 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
811 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
812
813 // Emit the LHS or RHS as appropriate.
814 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
815}
816
817//===----------------------------------------------------------------------===//
818// Entry Point into this File
819//===----------------------------------------------------------------------===//
820
821/// EmitComplexExpr - Emit the computation of the specified expression of
822/// complex type, ignoring the result.
823Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
824 assert(E && !hasAggregateLLVMType(E->getType()) &&
825 "Invalid scalar expression to emit");
826
827 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
828}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000829
830/// EmitScalarConversion - Emit a conversion from the specified type to the
831/// specified destination type, both of which are LLVM scalar types.
832llvm::Value *CodeGenFunction::EmitScalarConversion(llvm::Value *Src,
833 QualType SrcTy,
834 QualType DstTy) {
835 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
836 "Invalid scalar expression to emit");
837 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
838}