blob: deaf0a89fe2fda9ab23a3eb0439b6d462b001909 [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;
254
255 // Handle conversions to bool first, they are special: comparisons against 0.
256 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstType))
257 if (DestBT->getKind() == BuiltinType::Bool)
258 return CGF.ConvertScalarValueToBool(RValue::get(Src), SrcType);
259
260 const llvm::Type *DstTy = ConvertType(DstType);
261
262 // Ignore conversions like int -> uint.
263 if (Src->getType() == DstTy)
264 return Src;
265
266 // Handle pointer conversions next: pointers can only be converted to/from
267 // other pointers and integers.
268 if (isa<PointerType>(DstType)) {
269 // The source value may be an integer, or a pointer.
270 if (isa<llvm::PointerType>(Src->getType()))
271 return Builder.CreateBitCast(Src, DstTy, "conv");
272 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
273 return Builder.CreateIntToPtr(Src, DstTy, "conv");
274 }
275
276 if (isa<PointerType>(SrcType)) {
277 // Must be an ptr to int cast.
278 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
279 return Builder.CreateIntToPtr(Src, DstTy, "conv");
280 }
281
282 // Finally, we have the arithmetic types: real int/float.
283 if (isa<llvm::IntegerType>(Src->getType())) {
284 bool InputSigned = SrcType->isSignedIntegerType();
285 if (isa<llvm::IntegerType>(DstTy))
286 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
287 else if (InputSigned)
288 return Builder.CreateSIToFP(Src, DstTy, "conv");
289 else
290 return Builder.CreateUIToFP(Src, DstTy, "conv");
291 }
292
293 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
294 if (isa<llvm::IntegerType>(DstTy)) {
295 if (DstType->isSignedIntegerType())
296 return Builder.CreateFPToSI(Src, DstTy, "conv");
297 else
298 return Builder.CreateFPToUI(Src, DstTy, "conv");
299 }
300
301 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
302 if (DstTy->getTypeID() < Src->getType()->getTypeID())
303 return Builder.CreateFPTrunc(Src, DstTy, "conv");
304 else
305 return Builder.CreateFPExt(Src, DstTy, "conv");
306}
307
Chris Lattner9fba49a2007-08-24 05:35:26 +0000308//===----------------------------------------------------------------------===//
309// Visitor Methods
310//===----------------------------------------------------------------------===//
311
312Value *ScalarExprEmitter::VisitExpr(Expr *E) {
313 fprintf(stderr, "Unimplemented scalar expr!\n");
314 E->dump();
315 if (E->getType()->isVoidType())
316 return 0;
317 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
318}
319
320Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
321 // Emit subscript expressions in rvalue context's. For most cases, this just
322 // loads the lvalue formed by the subscript expr. However, we have to be
323 // careful, because the base of a vector subscript is occasionally an rvalue,
324 // so we can't get it as an lvalue.
325 if (!E->getBase()->getType()->isVectorType())
326 return EmitLoadOfLValue(E);
327
328 // Handle the vector case. The base must be a vector, the index must be an
329 // integer value.
330 Value *Base = Visit(E->getBase());
331 Value *Idx = Visit(E->getIdx());
332
333 // FIXME: Convert Idx to i32 type.
334 return Builder.CreateExtractElement(Base, Idx, "vecext");
335}
336
337/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
338/// also handle things like function to pointer-to-function decay, and array to
339/// pointer decay.
340Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
341 const Expr *Op = E->getSubExpr();
342
343 // If this is due to array->pointer conversion, emit the array expression as
344 // an l-value.
345 if (Op->getType()->isArrayType()) {
346 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
347 // will not true when we add support for VLAs.
348 llvm::Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
349
350 assert(isa<llvm::PointerType>(V->getType()) &&
351 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
352 ->getElementType()) &&
353 "Doesn't support VLAs yet!");
354 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
355 return Builder.CreateGEP(V, Idx0, Idx0, "arraydecay");
356 }
357
358 return EmitCastExpr(Op, E->getType());
359}
360
361
362// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
363// have to handle a more broad range of conversions than explicit casts, as they
364// handle things like function to ptr-to-function decay etc.
365Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000366 // Handle cases where the source is an LLVM Scalar type.
367 if (!CGF.hasAggregateLLVMType(E->getType())) {
368 Value *Src = Visit(const_cast<Expr*>(E));
369
370 // If the destination is void, just evaluate the source.
371 if (DestTy->isVoidType()) return 0;
372
373 // Use EmitScalarConversion to perform the conversion.
374 return EmitScalarConversion(Src, E->getType(), DestTy);
375 }
376
Chris Lattner9fba49a2007-08-24 05:35:26 +0000377 RValue Src = CGF.EmitAnyExpr(E);
378
379 // If the destination is void, just evaluate the source.
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000380 if (DestTy->isVoidType()) return 0;
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000381
382 assert(0 && "Can't convert from an aggregate yet!");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000383}
384
385//===----------------------------------------------------------------------===//
386// Unary Operators
387//===----------------------------------------------------------------------===//
388
389Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000390 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000391 LValue LV = EmitLValue(E->getSubExpr());
392 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000393 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
394 E->getSubExpr()->getType()).getVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000395
396 int AmountVal = isInc ? 1 : -1;
397
398 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000399 if (isa<llvm::PointerType>(InVal->getType())) {
400 // FIXME: This isn't right for VLAs.
401 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
402 NextVal = Builder.CreateGEP(InVal, NextVal);
403 } else {
404 // Add the inc/dec to the real part.
405 if (isa<llvm::IntegerType>(InVal->getType()))
406 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
407 else
408 NextVal = llvm::ConstantFP::get(InVal->getType(), AmountVal);
409 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
410 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000411
412 // Store the updated result through the lvalue.
413 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
414 E->getSubExpr()->getType());
415
416 // If this is a postinc, return the value read from memory, otherwise use the
417 // updated value.
418 return isPre ? NextVal : InVal;
419}
420
421
422Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
423 Value *Op = Visit(E->getSubExpr());
424 return Builder.CreateNeg(Op, "neg");
425}
426
427Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
428 Value *Op = Visit(E->getSubExpr());
429 return Builder.CreateNot(Op, "neg");
430}
431
432Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
433 // Compare operand to zero.
434 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
435
436 // Invert value.
437 // TODO: Could dynamically modify easy computations here. For example, if
438 // the operand is an icmp ne, turn into icmp eq.
439 BoolVal = Builder.CreateNot(BoolVal, "lnot");
440
441 // ZExt result to int.
442 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
443}
444
445/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
446/// an integer (RetType).
447Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000448 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000449 /// FIXME: This doesn't handle VLAs yet!
450 std::pair<uint64_t, unsigned> Info =
451 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
452
453 uint64_t Val = isSizeOf ? Info.first : Info.second;
454 Val /= 8; // Return size in bytes, not bits.
455
456 assert(RetType->isIntegerType() && "Result type must be an integer!");
457
458 unsigned ResultWidth = CGF.getContext().getTypeSize(RetType,SourceLocation());
459 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
460}
461
Chris Lattner01211af2007-08-24 21:20:17 +0000462Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
463 Expr *Op = E->getSubExpr();
464 if (Op->getType()->isComplexType())
465 return CGF.EmitComplexExpr(Op).first;
466 return Visit(Op);
467}
468Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
469 Expr *Op = E->getSubExpr();
470 if (Op->getType()->isComplexType())
471 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000472
473 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
474 // effects are evaluated.
475 CGF.EmitScalarExpr(Op);
476 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000477}
478
479
Chris Lattner9fba49a2007-08-24 05:35:26 +0000480//===----------------------------------------------------------------------===//
481// Binary Operators
482//===----------------------------------------------------------------------===//
483
484BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
485 BinOpInfo Result;
486 Result.LHS = Visit(E->getLHS());
487 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000488 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000489 Result.E = E;
490 return Result;
491}
492
Chris Lattner660e31d2007-08-24 21:00:35 +0000493Value *ScalarExprEmitter::EmitCompoundAssign(const BinaryOperator *E,
494 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
495 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
496
497 BinOpInfo OpInfo;
498
499 // Load the LHS and RHS operands.
500 LValue LHSLV = EmitLValue(E->getLHS());
501 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
502
503 // FIXME: It is possible for the RHS to be complex.
504 OpInfo.RHS = Visit(E->getRHS());
505
506 // Convert the LHS/RHS values to the computation type.
507 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
508 QualType ComputeType = CAO->getComputationType();
509
510 // FIXME: it's possible for the computation type to be complex if the RHS
511 // is complex. Handle this!
Chris Lattnerb1497062007-08-26 07:08:39 +0000512 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000513
514 // Do not merge types for -= where the LHS is a pointer.
Chris Lattner42330c32007-08-25 21:56:20 +0000515 if (E->getOpcode() != BinaryOperator::SubAssign ||
516 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000517 // FIXME: the computation type may be complex.
518 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000519 }
520 OpInfo.Ty = ComputeType;
521 OpInfo.E = E;
522
523 // Expand the binary operator.
524 Value *Result = (this->*Func)(OpInfo);
525
526 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000527 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000528
529 // Store the result value into the LHS lvalue.
530 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
531
532 return Result;
533}
534
535
Chris Lattner9fba49a2007-08-24 05:35:26 +0000536Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
537 if (Ops.LHS->getType()->isFloatingPoint())
538 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000539 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000540 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
541 else
542 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
543}
544
545Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
546 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000547 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000548 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
549 else
550 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
551}
552
553
554Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000555 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000556 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000557
558 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000559 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
560 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
561 // int + pointer
562 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
563}
564
565Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
566 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
567 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
568
Chris Lattner660e31d2007-08-24 21:00:35 +0000569 // pointer - int
570 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
571 "ptr-ptr shouldn't get here");
572 // FIXME: The pointer could point to a VLA.
573 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
574 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
575}
576
577Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
578 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
579 // the compound assignment case it is invalid, so just handle it here.
580 if (!E->getRHS()->getType()->isPointerType())
581 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000582
583 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000584 Value *LHS = Visit(E->getLHS());
585 Value *RHS = Visit(E->getRHS());
586
587 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
588 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
589 "Can't subtract different pointer types");
590
Chris Lattner9fba49a2007-08-24 05:35:26 +0000591 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000592 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
593 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000594
595 const llvm::Type *ResultType = ConvertType(E->getType());
596 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
597 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
598 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000599
600 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
601 // remainder. As such, we handle common power-of-two cases here to generate
602 // better code.
603 if (llvm::isPowerOf2_64(ElementSize)) {
604 Value *ShAmt =
605 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
606 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
607 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000608
Chris Lattner9fba49a2007-08-24 05:35:26 +0000609 // Otherwise, do a full sdiv.
610 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
611 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
612}
613
Chris Lattner660e31d2007-08-24 21:00:35 +0000614
Chris Lattner9fba49a2007-08-24 05:35:26 +0000615Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
616 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
617 // RHS to the same size as the LHS.
618 Value *RHS = Ops.RHS;
619 if (Ops.LHS->getType() != RHS->getType())
620 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
621
622 return Builder.CreateShl(Ops.LHS, RHS, "shl");
623}
624
625Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
626 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
627 // RHS to the same size as the LHS.
628 Value *RHS = Ops.RHS;
629 if (Ops.LHS->getType() != RHS->getType())
630 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
631
Chris Lattner660e31d2007-08-24 21:00:35 +0000632 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000633 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
634 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
635}
636
637Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
638 unsigned SICmpOpc, unsigned FCmpOpc) {
639 llvm::Value *Result;
640 QualType LHSTy = E->getLHS()->getType();
641 if (!LHSTy->isComplexType()) {
642 Value *LHS = Visit(E->getLHS());
643 Value *RHS = Visit(E->getRHS());
644
645 if (LHS->getType()->isFloatingPoint()) {
646 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
647 LHS, RHS, "cmp");
648 } else if (LHSTy->isUnsignedIntegerType()) {
649 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
650 LHS, RHS, "cmp");
651 } else {
652 // Signed integers and pointers.
653 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
654 LHS, RHS, "cmp");
655 }
656 } else {
657 // Complex Comparison: can only be an equality comparison.
658 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
659 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
660
661 QualType CETy =
662 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
663
664 llvm::Value *ResultR, *ResultI;
665 if (CETy->isRealFloatingType()) {
666 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
667 LHS.first, RHS.first, "cmp.r");
668 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
669 LHS.second, RHS.second, "cmp.i");
670 } else {
671 // Complex comparisons can only be equality comparisons. As such, signed
672 // and unsigned opcodes are the same.
673 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
674 LHS.first, RHS.first, "cmp.r");
675 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
676 LHS.second, RHS.second, "cmp.i");
677 }
678
679 if (E->getOpcode() == BinaryOperator::EQ) {
680 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
681 } else {
682 assert(E->getOpcode() == BinaryOperator::NE &&
683 "Complex comparison other than == or != ?");
684 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
685 }
686 }
687
688 // ZExt result to int.
689 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
690}
691
692Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
693 LValue LHS = EmitLValue(E->getLHS());
694 Value *RHS = Visit(E->getRHS());
695
696 // Store the value into the LHS.
697 // FIXME: Volatility!
698 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
699
700 // Return the RHS.
701 return RHS;
702}
703
704Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
705 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
706
707 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
708 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
709
710 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
711 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
712
713 CGF.EmitBlock(RHSBlock);
714 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
715
716 // Reaquire the RHS block, as there may be subblocks inserted.
717 RHSBlock = Builder.GetInsertBlock();
718 CGF.EmitBlock(ContBlock);
719
720 // Create a PHI node. If we just evaluted the LHS condition, the result is
721 // false. If we evaluated both, the result is the RHS condition.
722 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
723 PN->reserveOperandSpace(2);
724 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
725 PN->addIncoming(RHSCond, RHSBlock);
726
727 // ZExt result to int.
728 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
729}
730
731Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
732 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
733
734 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
735 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
736
737 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
738 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
739
740 CGF.EmitBlock(RHSBlock);
741 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
742
743 // Reaquire the RHS block, as there may be subblocks inserted.
744 RHSBlock = Builder.GetInsertBlock();
745 CGF.EmitBlock(ContBlock);
746
747 // Create a PHI node. If we just evaluted the LHS condition, the result is
748 // true. If we evaluated both, the result is the RHS condition.
749 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
750 PN->reserveOperandSpace(2);
751 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
752 PN->addIncoming(RHSCond, RHSBlock);
753
754 // ZExt result to int.
755 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
756}
757
758Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
759 CGF.EmitStmt(E->getLHS());
760 return Visit(E->getRHS());
761}
762
763//===----------------------------------------------------------------------===//
764// Other Operators
765//===----------------------------------------------------------------------===//
766
767Value *ScalarExprEmitter::
768VisitConditionalOperator(const ConditionalOperator *E) {
769 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
770 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
771 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
772
773 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
774 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
775
776 CGF.EmitBlock(LHSBlock);
777
778 // Handle the GNU extension for missing LHS.
779 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
780 Builder.CreateBr(ContBlock);
781 LHSBlock = Builder.GetInsertBlock();
782
783 CGF.EmitBlock(RHSBlock);
784
785 Value *RHS = Visit(E->getRHS());
786 Builder.CreateBr(ContBlock);
787 RHSBlock = Builder.GetInsertBlock();
788
789 CGF.EmitBlock(ContBlock);
790
791 // Create a PHI node for the real part.
792 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
793 PN->reserveOperandSpace(2);
794 PN->addIncoming(LHS, LHSBlock);
795 PN->addIncoming(RHS, RHSBlock);
796 return PN;
797}
798
799Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
800 llvm::APSInt CondVal(32);
801 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
802 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
803
804 // Emit the LHS or RHS as appropriate.
805 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
806}
807
808//===----------------------------------------------------------------------===//
809// Entry Point into this File
810//===----------------------------------------------------------------------===//
811
812/// EmitComplexExpr - Emit the computation of the specified expression of
813/// complex type, ignoring the result.
814Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
815 assert(E && !hasAggregateLLVMType(E->getType()) &&
816 "Invalid scalar expression to emit");
817
818 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
819}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000820
821/// EmitScalarConversion - Emit a conversion from the specified type to the
822/// specified destination type, both of which are LLVM scalar types.
823llvm::Value *CodeGenFunction::EmitScalarConversion(llvm::Value *Src,
824 QualType SrcTy,
825 QualType DstTy) {
826 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
827 "Invalid scalar expression to emit");
828 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
829}