blob: ee0ccd644e2a80a424977ff92ca7f338d410c16b [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 Lattnerd8d44222007-08-26 16:42:57 +000065 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000066 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000067 Value *EmitConversionToBool(Value *Src, QualType DstTy);
68
Chris Lattner4e05d1e2007-08-26 06:48:56 +000069 /// EmitScalarConversion - Emit a conversion from the specified type to the
70 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000071 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
72
73 /// EmitComplexToScalarConversion - Emit a conversion from the specified
74 /// complex type to the specified destination type, where the destination
75 /// type is an LLVM scalar type.
76 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
77 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000078
Chris Lattner9fba49a2007-08-24 05:35:26 +000079 //===--------------------------------------------------------------------===//
80 // Visitor Methods
81 //===--------------------------------------------------------------------===//
82
83 Value *VisitStmt(Stmt *S) {
84 S->dump();
85 assert(0 && "Stmt can't have complex result type!");
86 return 0;
87 }
88 Value *VisitExpr(Expr *S);
89 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
90
91 // Leaves.
92 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
93 return llvm::ConstantInt::get(E->getValue());
94 }
95 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
96 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
97 }
98 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
99 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
100 }
101 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
102 return llvm::ConstantInt::get(ConvertType(E->getType()),
103 E->typesAreCompatible());
104 }
105 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
106 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
107 }
108
109 // l-values.
110 Value *VisitDeclRefExpr(DeclRefExpr *E) {
111 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
112 return llvm::ConstantInt::get(EC->getInitVal());
113 return EmitLoadOfLValue(E);
114 }
115 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
116 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
117 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
118 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
119 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
120
121 // FIXME: CompoundLiteralExpr
122 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
123 Value *VisitCastExpr(const CastExpr *E) {
124 return EmitCastExpr(E->getSubExpr(), E->getType());
125 }
126 Value *EmitCastExpr(const Expr *E, QualType T);
127
128 Value *VisitCallExpr(const CallExpr *E) {
129 return CGF.EmitCallExpr(E).getVal();
130 }
131
132 // Unary Operators.
133 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
134 Value *VisitUnaryPostDec(const UnaryOperator *E) {
135 return VisitPrePostIncDec(E, false, false);
136 }
137 Value *VisitUnaryPostInc(const UnaryOperator *E) {
138 return VisitPrePostIncDec(E, true, false);
139 }
140 Value *VisitUnaryPreDec(const UnaryOperator *E) {
141 return VisitPrePostIncDec(E, false, true);
142 }
143 Value *VisitUnaryPreInc(const UnaryOperator *E) {
144 return VisitPrePostIncDec(E, true, true);
145 }
146 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
147 return EmitLValue(E->getSubExpr()).getAddress();
148 }
149 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
150 Value *VisitUnaryPlus(const UnaryOperator *E) {
151 return Visit(E->getSubExpr());
152 }
153 Value *VisitUnaryMinus (const UnaryOperator *E);
154 Value *VisitUnaryNot (const UnaryOperator *E);
155 Value *VisitUnaryLNot (const UnaryOperator *E);
156 Value *VisitUnarySizeOf (const UnaryOperator *E) {
157 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
158 }
159 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
160 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
161 }
162 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
163 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000164 Value *VisitUnaryReal (const UnaryOperator *E);
165 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000166 Value *VisitUnaryExtension(const UnaryOperator *E) {
167 return Visit(E->getSubExpr());
168 }
169
170 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000171 Value *EmitMul(const BinOpInfo &Ops) {
172 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
173 }
174 Value *EmitDiv(const BinOpInfo &Ops);
175 Value *EmitRem(const BinOpInfo &Ops);
176 Value *EmitAdd(const BinOpInfo &Ops);
177 Value *EmitSub(const BinOpInfo &Ops);
178 Value *EmitShl(const BinOpInfo &Ops);
179 Value *EmitShr(const BinOpInfo &Ops);
180 Value *EmitAnd(const BinOpInfo &Ops) {
181 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
182 }
183 Value *EmitXor(const BinOpInfo &Ops) {
184 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
185 }
186 Value *EmitOr (const BinOpInfo &Ops) {
187 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
188 }
189
Chris Lattner660e31d2007-08-24 21:00:35 +0000190 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000191 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000192 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
193
194 // Binary operators and binary compound assignment operators.
195#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000196 Value *VisitBin ## OP(const BinaryOperator *E) { \
197 return Emit ## OP(EmitBinOps(E)); \
198 } \
199 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
200 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000201 }
202 HANDLEBINOP(Mul);
203 HANDLEBINOP(Div);
204 HANDLEBINOP(Rem);
205 HANDLEBINOP(Add);
206 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
207 HANDLEBINOP(Shl);
208 HANDLEBINOP(Shr);
209 HANDLEBINOP(And);
210 HANDLEBINOP(Xor);
211 HANDLEBINOP(Or);
212#undef HANDLEBINOP
213 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000214 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000215 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
216 }
217
Chris Lattner9fba49a2007-08-24 05:35:26 +0000218 // Comparisons.
219 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
220 unsigned SICmpOpc, unsigned FCmpOpc);
221#define VISITCOMP(CODE, UI, SI, FP) \
222 Value *VisitBin##CODE(const BinaryOperator *E) { \
223 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
224 llvm::FCmpInst::FP); }
225 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
226 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
227 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
228 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
229 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
230 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
231#undef VISITCOMP
232
233 Value *VisitBinAssign (const BinaryOperator *E);
234
235 Value *VisitBinLAnd (const BinaryOperator *E);
236 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000237 Value *VisitBinComma (const BinaryOperator *E);
238
239 // Other Operators.
240 Value *VisitConditionalOperator(const ConditionalOperator *CO);
241 Value *VisitChooseExpr(ChooseExpr *CE);
242 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
243 return CGF.EmitObjCStringLiteral(E);
244 }
245};
246} // end anonymous namespace.
247
248//===----------------------------------------------------------------------===//
249// Utilities
250//===----------------------------------------------------------------------===//
251
Chris Lattnerd8d44222007-08-26 16:42:57 +0000252/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000253/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000254Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
255 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
256
257 if (SrcType->isRealFloatingType()) {
258 // Compare against 0.0 for fp scalars.
259 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000260 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
261 }
262
263 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
264 "Unknown scalar type to convert");
265
266 // Because of the type rules of C, we often end up computing a logical value,
267 // then zero extending it to int, then wanting it as a logical value again.
268 // Optimize this common case.
269 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
270 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
271 Value *Result = ZI->getOperand(0);
272 ZI->eraseFromParent();
273 return Result;
274 }
275 }
276
277 // Compare against an integer or pointer null.
278 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
279 return Builder.CreateICmpNE(Src, Zero, "tobool");
280}
281
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000282/// EmitScalarConversion - Emit a conversion from the specified type to the
283/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000284Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
285 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000286 SrcType = SrcType.getCanonicalType();
287 DstType = DstType.getCanonicalType();
288 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000289
290 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000291
292 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000293 if (DstType->isBooleanType())
294 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000295
296 const llvm::Type *DstTy = ConvertType(DstType);
297
298 // Ignore conversions like int -> uint.
299 if (Src->getType() == DstTy)
300 return Src;
301
302 // Handle pointer conversions next: pointers can only be converted to/from
303 // other pointers and integers.
304 if (isa<PointerType>(DstType)) {
305 // The source value may be an integer, or a pointer.
306 if (isa<llvm::PointerType>(Src->getType()))
307 return Builder.CreateBitCast(Src, DstTy, "conv");
308 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
309 return Builder.CreateIntToPtr(Src, DstTy, "conv");
310 }
311
312 if (isa<PointerType>(SrcType)) {
313 // Must be an ptr to int cast.
314 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
315 return Builder.CreateIntToPtr(Src, DstTy, "conv");
316 }
317
318 // Finally, we have the arithmetic types: real int/float.
319 if (isa<llvm::IntegerType>(Src->getType())) {
320 bool InputSigned = SrcType->isSignedIntegerType();
321 if (isa<llvm::IntegerType>(DstTy))
322 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
323 else if (InputSigned)
324 return Builder.CreateSIToFP(Src, DstTy, "conv");
325 else
326 return Builder.CreateUIToFP(Src, DstTy, "conv");
327 }
328
329 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
330 if (isa<llvm::IntegerType>(DstTy)) {
331 if (DstType->isSignedIntegerType())
332 return Builder.CreateFPToSI(Src, DstTy, "conv");
333 else
334 return Builder.CreateFPToUI(Src, DstTy, "conv");
335 }
336
337 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
338 if (DstTy->getTypeID() < Src->getType()->getTypeID())
339 return Builder.CreateFPTrunc(Src, DstTy, "conv");
340 else
341 return Builder.CreateFPExt(Src, DstTy, "conv");
342}
343
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000344/// EmitComplexToScalarConversion - Emit a conversion from the specified
345/// complex type to the specified destination type, where the destination
346/// type is an LLVM scalar type.
347Value *ScalarExprEmitter::
348EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
349 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000350 // Get the source element type.
351 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
352
353 // Handle conversions to bool first, they are special: comparisons against 0.
354 if (DstTy->isBooleanType()) {
355 // Complex != 0 -> (Real != 0) | (Imag != 0)
356 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
357 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
358 return Builder.CreateOr(Src.first, Src.second, "tobool");
359 }
360
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000361 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
362 // the imaginary part of the complex value is discarded and the value of the
363 // real part is converted according to the conversion rules for the
364 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000365 return EmitScalarConversion(Src.first, SrcTy, DstTy);
366}
367
368
Chris Lattner9fba49a2007-08-24 05:35:26 +0000369//===----------------------------------------------------------------------===//
370// Visitor Methods
371//===----------------------------------------------------------------------===//
372
373Value *ScalarExprEmitter::VisitExpr(Expr *E) {
374 fprintf(stderr, "Unimplemented scalar expr!\n");
375 E->dump();
376 if (E->getType()->isVoidType())
377 return 0;
378 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
379}
380
381Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
382 // Emit subscript expressions in rvalue context's. For most cases, this just
383 // loads the lvalue formed by the subscript expr. However, we have to be
384 // careful, because the base of a vector subscript is occasionally an rvalue,
385 // so we can't get it as an lvalue.
386 if (!E->getBase()->getType()->isVectorType())
387 return EmitLoadOfLValue(E);
388
389 // Handle the vector case. The base must be a vector, the index must be an
390 // integer value.
391 Value *Base = Visit(E->getBase());
392 Value *Idx = Visit(E->getIdx());
393
394 // FIXME: Convert Idx to i32 type.
395 return Builder.CreateExtractElement(Base, Idx, "vecext");
396}
397
398/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
399/// also handle things like function to pointer-to-function decay, and array to
400/// pointer decay.
401Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
402 const Expr *Op = E->getSubExpr();
403
404 // If this is due to array->pointer conversion, emit the array expression as
405 // an l-value.
406 if (Op->getType()->isArrayType()) {
407 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
408 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000409 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000410
411 assert(isa<llvm::PointerType>(V->getType()) &&
412 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
413 ->getElementType()) &&
414 "Doesn't support VLAs yet!");
415 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
416 return Builder.CreateGEP(V, Idx0, Idx0, "arraydecay");
417 }
418
419 return EmitCastExpr(Op, E->getType());
420}
421
422
423// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
424// have to handle a more broad range of conversions than explicit casts, as they
425// handle things like function to ptr-to-function decay etc.
426Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000427 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000428 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000429 Value *Src = Visit(const_cast<Expr*>(E));
430
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000431 // Use EmitScalarConversion to perform the conversion.
432 return EmitScalarConversion(Src, E->getType(), DestTy);
433 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000434
Chris Lattner82e10392007-08-26 07:26:12 +0000435 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000436 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
437 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000438}
439
440//===----------------------------------------------------------------------===//
441// Unary Operators
442//===----------------------------------------------------------------------===//
443
444Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000445 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000446 LValue LV = EmitLValue(E->getSubExpr());
447 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000448 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
449 E->getSubExpr()->getType()).getVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000450
451 int AmountVal = isInc ? 1 : -1;
452
453 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000454 if (isa<llvm::PointerType>(InVal->getType())) {
455 // FIXME: This isn't right for VLAs.
456 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
457 NextVal = Builder.CreateGEP(InVal, NextVal);
458 } else {
459 // Add the inc/dec to the real part.
460 if (isa<llvm::IntegerType>(InVal->getType()))
461 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
462 else
463 NextVal = llvm::ConstantFP::get(InVal->getType(), AmountVal);
464 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
465 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000466
467 // Store the updated result through the lvalue.
468 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
469 E->getSubExpr()->getType());
470
471 // If this is a postinc, return the value read from memory, otherwise use the
472 // updated value.
473 return isPre ? NextVal : InVal;
474}
475
476
477Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
478 Value *Op = Visit(E->getSubExpr());
479 return Builder.CreateNeg(Op, "neg");
480}
481
482Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
483 Value *Op = Visit(E->getSubExpr());
484 return Builder.CreateNot(Op, "neg");
485}
486
487Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
488 // Compare operand to zero.
489 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
490
491 // Invert value.
492 // TODO: Could dynamically modify easy computations here. For example, if
493 // the operand is an icmp ne, turn into icmp eq.
494 BoolVal = Builder.CreateNot(BoolVal, "lnot");
495
496 // ZExt result to int.
497 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
498}
499
500/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
501/// an integer (RetType).
502Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000503 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000504 /// FIXME: This doesn't handle VLAs yet!
505 std::pair<uint64_t, unsigned> Info =
506 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
507
508 uint64_t Val = isSizeOf ? Info.first : Info.second;
509 Val /= 8; // Return size in bytes, not bits.
510
511 assert(RetType->isIntegerType() && "Result type must be an integer!");
512
513 unsigned ResultWidth = CGF.getContext().getTypeSize(RetType,SourceLocation());
514 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
515}
516
Chris Lattner01211af2007-08-24 21:20:17 +0000517Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
518 Expr *Op = E->getSubExpr();
519 if (Op->getType()->isComplexType())
520 return CGF.EmitComplexExpr(Op).first;
521 return Visit(Op);
522}
523Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
524 Expr *Op = E->getSubExpr();
525 if (Op->getType()->isComplexType())
526 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000527
528 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
529 // effects are evaluated.
530 CGF.EmitScalarExpr(Op);
531 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000532}
533
534
Chris Lattner9fba49a2007-08-24 05:35:26 +0000535//===----------------------------------------------------------------------===//
536// Binary Operators
537//===----------------------------------------------------------------------===//
538
539BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
540 BinOpInfo Result;
541 Result.LHS = Visit(E->getLHS());
542 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000543 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000544 Result.E = E;
545 return Result;
546}
547
Chris Lattner0d965302007-08-26 21:41:21 +0000548Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000549 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
550 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
551
552 BinOpInfo OpInfo;
553
554 // Load the LHS and RHS operands.
555 LValue LHSLV = EmitLValue(E->getLHS());
556 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
557
558 // FIXME: It is possible for the RHS to be complex.
559 OpInfo.RHS = Visit(E->getRHS());
560
561 // Convert the LHS/RHS values to the computation type.
Chris Lattner0d965302007-08-26 21:41:21 +0000562 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000563
564 // FIXME: it's possible for the computation type to be complex if the RHS
565 // is complex. Handle this!
Chris Lattnerb1497062007-08-26 07:08:39 +0000566 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000567
568 // Do not merge types for -= where the LHS is a pointer.
Chris Lattner42330c32007-08-25 21:56:20 +0000569 if (E->getOpcode() != BinaryOperator::SubAssign ||
570 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000571 // FIXME: the computation type may be complex.
572 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000573 }
574 OpInfo.Ty = ComputeType;
575 OpInfo.E = E;
576
577 // Expand the binary operator.
578 Value *Result = (this->*Func)(OpInfo);
579
580 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000581 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000582
583 // Store the result value into the LHS lvalue.
584 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
585
586 return Result;
587}
588
589
Chris Lattner9fba49a2007-08-24 05:35:26 +0000590Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
591 if (Ops.LHS->getType()->isFloatingPoint())
592 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000593 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000594 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
595 else
596 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
597}
598
599Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
600 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000601 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000602 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
603 else
604 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
605}
606
607
608Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000609 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000610 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000611
612 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000613 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
614 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
615 // int + pointer
616 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
617}
618
619Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
620 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
621 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
622
Chris Lattner660e31d2007-08-24 21:00:35 +0000623 // pointer - int
624 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
625 "ptr-ptr shouldn't get here");
626 // FIXME: The pointer could point to a VLA.
627 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
628 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
629}
630
631Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
632 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
633 // the compound assignment case it is invalid, so just handle it here.
634 if (!E->getRHS()->getType()->isPointerType())
635 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000636
637 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000638 Value *LHS = Visit(E->getLHS());
639 Value *RHS = Visit(E->getRHS());
640
641 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
642 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
643 "Can't subtract different pointer types");
644
Chris Lattner9fba49a2007-08-24 05:35:26 +0000645 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000646 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
647 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000648
649 const llvm::Type *ResultType = ConvertType(E->getType());
650 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
651 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
652 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000653
654 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
655 // remainder. As such, we handle common power-of-two cases here to generate
656 // better code.
657 if (llvm::isPowerOf2_64(ElementSize)) {
658 Value *ShAmt =
659 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
660 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
661 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000662
Chris Lattner9fba49a2007-08-24 05:35:26 +0000663 // Otherwise, do a full sdiv.
664 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
665 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
666}
667
Chris Lattner660e31d2007-08-24 21:00:35 +0000668
Chris Lattner9fba49a2007-08-24 05:35:26 +0000669Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
670 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
671 // RHS to the same size as the LHS.
672 Value *RHS = Ops.RHS;
673 if (Ops.LHS->getType() != RHS->getType())
674 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
675
676 return Builder.CreateShl(Ops.LHS, RHS, "shl");
677}
678
679Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
680 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
681 // RHS to the same size as the LHS.
682 Value *RHS = Ops.RHS;
683 if (Ops.LHS->getType() != RHS->getType())
684 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
685
Chris Lattner660e31d2007-08-24 21:00:35 +0000686 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000687 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
688 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
689}
690
691Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
692 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000693 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000694 QualType LHSTy = E->getLHS()->getType();
695 if (!LHSTy->isComplexType()) {
696 Value *LHS = Visit(E->getLHS());
697 Value *RHS = Visit(E->getRHS());
698
699 if (LHS->getType()->isFloatingPoint()) {
700 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
701 LHS, RHS, "cmp");
702 } else if (LHSTy->isUnsignedIntegerType()) {
703 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
704 LHS, RHS, "cmp");
705 } else {
706 // Signed integers and pointers.
707 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
708 LHS, RHS, "cmp");
709 }
710 } else {
711 // Complex Comparison: can only be an equality comparison.
712 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
713 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
714
715 QualType CETy =
716 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
717
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000718 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000719 if (CETy->isRealFloatingType()) {
720 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
721 LHS.first, RHS.first, "cmp.r");
722 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
723 LHS.second, RHS.second, "cmp.i");
724 } else {
725 // Complex comparisons can only be equality comparisons. As such, signed
726 // and unsigned opcodes are the same.
727 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
728 LHS.first, RHS.first, "cmp.r");
729 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
730 LHS.second, RHS.second, "cmp.i");
731 }
732
733 if (E->getOpcode() == BinaryOperator::EQ) {
734 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
735 } else {
736 assert(E->getOpcode() == BinaryOperator::NE &&
737 "Complex comparison other than == or != ?");
738 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
739 }
740 }
741
742 // ZExt result to int.
743 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
744}
745
746Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
747 LValue LHS = EmitLValue(E->getLHS());
748 Value *RHS = Visit(E->getRHS());
749
750 // Store the value into the LHS.
751 // FIXME: Volatility!
752 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
753
754 // Return the RHS.
755 return RHS;
756}
757
758Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
759 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
760
761 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
762 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
763
764 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
765 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
766
767 CGF.EmitBlock(RHSBlock);
768 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
769
770 // Reaquire the RHS block, as there may be subblocks inserted.
771 RHSBlock = Builder.GetInsertBlock();
772 CGF.EmitBlock(ContBlock);
773
774 // Create a PHI node. If we just evaluted the LHS condition, the result is
775 // false. If we evaluated both, the result is the RHS condition.
776 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
777 PN->reserveOperandSpace(2);
778 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
779 PN->addIncoming(RHSCond, RHSBlock);
780
781 // ZExt result to int.
782 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
783}
784
785Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
786 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
787
788 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
789 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
790
791 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
792 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
793
794 CGF.EmitBlock(RHSBlock);
795 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
796
797 // Reaquire the RHS block, as there may be subblocks inserted.
798 RHSBlock = Builder.GetInsertBlock();
799 CGF.EmitBlock(ContBlock);
800
801 // Create a PHI node. If we just evaluted the LHS condition, the result is
802 // true. If we evaluated both, the result is the RHS condition.
803 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
804 PN->reserveOperandSpace(2);
805 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
806 PN->addIncoming(RHSCond, RHSBlock);
807
808 // ZExt result to int.
809 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
810}
811
812Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
813 CGF.EmitStmt(E->getLHS());
814 return Visit(E->getRHS());
815}
816
817//===----------------------------------------------------------------------===//
818// Other Operators
819//===----------------------------------------------------------------------===//
820
821Value *ScalarExprEmitter::
822VisitConditionalOperator(const ConditionalOperator *E) {
823 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
824 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
825 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
826
827 Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
828 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
829
830 CGF.EmitBlock(LHSBlock);
831
832 // Handle the GNU extension for missing LHS.
833 Value *LHS = E->getLHS() ? Visit(E->getLHS()) : Cond;
834 Builder.CreateBr(ContBlock);
835 LHSBlock = Builder.GetInsertBlock();
836
837 CGF.EmitBlock(RHSBlock);
838
839 Value *RHS = Visit(E->getRHS());
840 Builder.CreateBr(ContBlock);
841 RHSBlock = Builder.GetInsertBlock();
842
843 CGF.EmitBlock(ContBlock);
844
845 // Create a PHI node for the real part.
846 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
847 PN->reserveOperandSpace(2);
848 PN->addIncoming(LHS, LHSBlock);
849 PN->addIncoming(RHS, RHSBlock);
850 return PN;
851}
852
853Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
854 llvm::APSInt CondVal(32);
855 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, CGF.getContext());
856 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
857
858 // Emit the LHS or RHS as appropriate.
859 return Visit(CondVal != 0 ? E->getLHS() : E->getRHS());
860}
861
862//===----------------------------------------------------------------------===//
863// Entry Point into this File
864//===----------------------------------------------------------------------===//
865
866/// EmitComplexExpr - Emit the computation of the specified expression of
867/// complex type, ignoring the result.
868Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
869 assert(E && !hasAggregateLLVMType(E->getType()) &&
870 "Invalid scalar expression to emit");
871
872 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
873}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000874
875/// EmitScalarConversion - Emit a conversion from the specified type to the
876/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000877Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
878 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000879 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
880 "Invalid scalar expression to emit");
881 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
882}
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000883
884/// EmitComplexToScalarConversion - Emit a conversion from the specified
885/// complex type to the specified destination type, where the destination
886/// type is an LLVM scalar type.
887Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
888 QualType SrcTy,
889 QualType DstTy) {
890 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
891 "Invalid complex -> scalar conversion");
892 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
893 DstTy);
894}