blob: f1989893e7867d6481e94261ed0d594f84d594bb [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 Lattner9fba49a2007-08-24 05:35:26 +0000381
382 // FIXME: Refactor EmitConversion to not return an RValue. Sink it into this
383 // method.
384 return CGF.EmitConversion(Src, E->getType(), DestTy).getVal();
385}
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!
514 OpInfo.LHS = CGF.EmitConversion(RValue::get(OpInfo.LHS), LHSTy,
515 ComputeType).getVal();
516
517 // Do not merge types for -= where the LHS is a pointer.
Chris Lattner42330c32007-08-25 21:56:20 +0000518 if (E->getOpcode() != BinaryOperator::SubAssign ||
519 !E->getLHS()->getType()->isPointerType()) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000520 OpInfo.RHS = CGF.EmitConversion(RValue::get(OpInfo.RHS), RHSTy,
521 ComputeType).getVal();
522 }
523 OpInfo.Ty = ComputeType;
524 OpInfo.E = E;
525
526 // Expand the binary operator.
527 Value *Result = (this->*Func)(OpInfo);
528
529 // Truncate the result back to the LHS type.
530 Result = CGF.EmitConversion(RValue::get(Result), ComputeType, LHSTy).getVal();
531
532 // Store the result value into the LHS lvalue.
533 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
534
535 return Result;
536}
537
538
Chris Lattner9fba49a2007-08-24 05:35:26 +0000539Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
540 if (Ops.LHS->getType()->isFloatingPoint())
541 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000542 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000543 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
544 else
545 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
546}
547
548Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
549 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000550 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000551 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
552 else
553 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
554}
555
556
557Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000558 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000559 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000560
561 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000562 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
563 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
564 // int + pointer
565 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
566}
567
568Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
569 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
570 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
571
Chris Lattner660e31d2007-08-24 21:00:35 +0000572 // pointer - int
573 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
574 "ptr-ptr shouldn't get here");
575 // FIXME: The pointer could point to a VLA.
576 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
577 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
578}
579
580Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
581 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
582 // the compound assignment case it is invalid, so just handle it here.
583 if (!E->getRHS()->getType()->isPointerType())
584 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000585
586 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000587 Value *LHS = Visit(E->getLHS());
588 Value *RHS = Visit(E->getRHS());
589
590 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
591 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
592 "Can't subtract different pointer types");
593
Chris Lattner9fba49a2007-08-24 05:35:26 +0000594 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000595 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
596 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000597
598 const llvm::Type *ResultType = ConvertType(E->getType());
599 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
600 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
601 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000602
603 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
604 // remainder. As such, we handle common power-of-two cases here to generate
605 // better code.
606 if (llvm::isPowerOf2_64(ElementSize)) {
607 Value *ShAmt =
608 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
609 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
610 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000611
Chris Lattner9fba49a2007-08-24 05:35:26 +0000612 // Otherwise, do a full sdiv.
613 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
614 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
615}
616
Chris Lattner660e31d2007-08-24 21:00:35 +0000617
Chris Lattner9fba49a2007-08-24 05:35:26 +0000618Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
619 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
620 // RHS to the same size as the LHS.
621 Value *RHS = Ops.RHS;
622 if (Ops.LHS->getType() != RHS->getType())
623 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
624
625 return Builder.CreateShl(Ops.LHS, RHS, "shl");
626}
627
628Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
629 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
630 // RHS to the same size as the LHS.
631 Value *RHS = Ops.RHS;
632 if (Ops.LHS->getType() != RHS->getType())
633 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
634
Chris Lattner660e31d2007-08-24 21:00:35 +0000635 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000636 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
637 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
638}
639
640Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
641 unsigned SICmpOpc, unsigned FCmpOpc) {
642 llvm::Value *Result;
643 QualType LHSTy = E->getLHS()->getType();
644 if (!LHSTy->isComplexType()) {
645 Value *LHS = Visit(E->getLHS());
646 Value *RHS = Visit(E->getRHS());
647
648 if (LHS->getType()->isFloatingPoint()) {
649 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
650 LHS, RHS, "cmp");
651 } else if (LHSTy->isUnsignedIntegerType()) {
652 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
653 LHS, RHS, "cmp");
654 } else {
655 // Signed integers and pointers.
656 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
657 LHS, RHS, "cmp");
658 }
659 } else {
660 // Complex Comparison: can only be an equality comparison.
661 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
662 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
663
664 QualType CETy =
665 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
666
667 llvm::Value *ResultR, *ResultI;
668 if (CETy->isRealFloatingType()) {
669 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
670 LHS.first, RHS.first, "cmp.r");
671 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
672 LHS.second, RHS.second, "cmp.i");
673 } else {
674 // Complex comparisons can only be equality comparisons. As such, signed
675 // and unsigned opcodes are the same.
676 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
677 LHS.first, RHS.first, "cmp.r");
678 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
679 LHS.second, RHS.second, "cmp.i");
680 }
681
682 if (E->getOpcode() == BinaryOperator::EQ) {
683 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
684 } else {
685 assert(E->getOpcode() == BinaryOperator::NE &&
686 "Complex comparison other than == or != ?");
687 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
688 }
689 }
690
691 // ZExt result to int.
692 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
693}
694
695Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
696 LValue LHS = EmitLValue(E->getLHS());
697 Value *RHS = Visit(E->getRHS());
698
699 // Store the value into the LHS.
700 // FIXME: Volatility!
701 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
702
703 // Return the RHS.
704 return RHS;
705}
706
707Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
708 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
709
710 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
711 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
712
713 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
714 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
715
716 CGF.EmitBlock(RHSBlock);
717 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
718
719 // Reaquire the RHS block, as there may be subblocks inserted.
720 RHSBlock = Builder.GetInsertBlock();
721 CGF.EmitBlock(ContBlock);
722
723 // Create a PHI node. If we just evaluted the LHS condition, the result is
724 // false. If we evaluated both, the result is the RHS condition.
725 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
726 PN->reserveOperandSpace(2);
727 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
728 PN->addIncoming(RHSCond, RHSBlock);
729
730 // ZExt result to int.
731 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
732}
733
734Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
735 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
736
737 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
738 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
739
740 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
741 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
742
743 CGF.EmitBlock(RHSBlock);
744 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
745
746 // Reaquire the RHS block, as there may be subblocks inserted.
747 RHSBlock = Builder.GetInsertBlock();
748 CGF.EmitBlock(ContBlock);
749
750 // Create a PHI node. If we just evaluted the LHS condition, the result is
751 // true. If we evaluated both, the result is the RHS condition.
752 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
753 PN->reserveOperandSpace(2);
754 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
755 PN->addIncoming(RHSCond, RHSBlock);
756
757 // ZExt result to int.
758 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
759}
760
761Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
762 CGF.EmitStmt(E->getLHS());
763 return Visit(E->getRHS());
764}
765
766//===----------------------------------------------------------------------===//
767// Other Operators
768//===----------------------------------------------------------------------===//
769
770Value *ScalarExprEmitter::
771VisitConditionalOperator(const ConditionalOperator *E) {
772 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
773 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
774 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
775
776 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
777 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
778
779 CGF.EmitBlock(LHSBlock);
780
781 // Handle the GNU extension for missing LHS.
782 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
783 Builder.CreateBr(ContBlock);
784 LHSBlock = Builder.GetInsertBlock();
785
786 CGF.EmitBlock(RHSBlock);
787
788 Value *RHS = Visit(E->getRHS());
789 Builder.CreateBr(ContBlock);
790 RHSBlock = Builder.GetInsertBlock();
791
792 CGF.EmitBlock(ContBlock);
793
794 // Create a PHI node for the real part.
795 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
796 PN->reserveOperandSpace(2);
797 PN->addIncoming(LHS, LHSBlock);
798 PN->addIncoming(RHS, RHSBlock);
799 return PN;
800}
801
802Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
803 llvm::APSInt CondVal(32);
804 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
805 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
806
807 // Emit the LHS or RHS as appropriate.
808 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
809}
810
811//===----------------------------------------------------------------------===//
812// Entry Point into this File
813//===----------------------------------------------------------------------===//
814
815/// EmitComplexExpr - Emit the computation of the specified expression of
816/// complex type, ignoring the result.
817Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
818 assert(E && !hasAggregateLLVMType(E->getType()) &&
819 "Invalid scalar expression to emit");
820
821 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
822}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000823
824/// EmitScalarConversion - Emit a conversion from the specified type to the
825/// specified destination type, both of which are LLVM scalar types.
826llvm::Value *CodeGenFunction::EmitScalarConversion(llvm::Value *Src,
827 QualType SrcTy,
828 QualType DstTy) {
829 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
830 "Invalid scalar expression to emit");
831 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
832}