blob: 7639d82f6bdf0d9a71644cbe2464eea63e5fdb39 [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"
Anders Carlsson36f07d82007-10-29 05:01:08 +000019#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000020#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Support/Compiler.h"
22using namespace clang;
23using namespace CodeGen;
24using llvm::Value;
25
26//===----------------------------------------------------------------------===//
27// Scalar Expression Emitter
28//===----------------------------------------------------------------------===//
29
30struct BinOpInfo {
31 Value *LHS;
32 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000033 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000034 const BinaryOperator *E;
35};
36
37namespace {
38class VISIBILITY_HIDDEN ScalarExprEmitter
39 : public StmtVisitor<ScalarExprEmitter, Value*> {
40 CodeGenFunction &CGF;
Devang Patel638b64c2007-10-09 19:49:58 +000041 llvm::LLVMFoldingBuilder &Builder;
Chris Lattner9fba49a2007-08-24 05:35:26 +000042public:
43
44 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
45 }
46
47
48 //===--------------------------------------------------------------------===//
49 // Utilities
50 //===--------------------------------------------------------------------===//
51
52 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
53 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
54
55 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000056 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000057 }
58
59 /// EmitLoadOfLValue - Given an expression with complex type that represents a
60 /// value l-value, this method emits the address of the l-value, then loads
61 /// and returns the result.
62 Value *EmitLoadOfLValue(const Expr *E) {
63 // FIXME: Volatile
64 return EmitLoadOfLValue(EmitLValue(E), E->getType());
65 }
66
Chris Lattnerd8d44222007-08-26 16:42:57 +000067 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000068 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000069 Value *EmitConversionToBool(Value *Src, QualType DstTy);
70
Chris Lattner4e05d1e2007-08-26 06:48:56 +000071 /// EmitScalarConversion - Emit a conversion from the specified type to the
72 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000073 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
74
75 /// EmitComplexToScalarConversion - Emit a conversion from the specified
76 /// complex type to the specified destination type, where the destination
77 /// type is an LLVM scalar type.
78 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
79 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000080
Chris Lattner9fba49a2007-08-24 05:35:26 +000081 //===--------------------------------------------------------------------===//
82 // Visitor Methods
83 //===--------------------------------------------------------------------===//
84
85 Value *VisitStmt(Stmt *S) {
Chris Lattner1aef6212007-09-13 01:17:29 +000086 S->dump(CGF.getContext().SourceMgr);
Chris Lattner9fba49a2007-08-24 05:35:26 +000087 assert(0 && "Stmt can't have complex result type!");
88 return 0;
89 }
90 Value *VisitExpr(Expr *S);
91 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
92
93 // Leaves.
94 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
95 return llvm::ConstantInt::get(E->getValue());
96 }
97 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner7f298762007-09-22 18:47:25 +000098 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +000099 }
100 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
101 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
102 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000103 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
104 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
105 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000106 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
107 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000108 CGF.getContext().typesAreCompatible(
109 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000110 }
111 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
112 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
113 }
114
115 // l-values.
116 Value *VisitDeclRefExpr(DeclRefExpr *E) {
117 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
118 return llvm::ConstantInt::get(EC->getInitVal());
119 return EmitLoadOfLValue(E);
120 }
121 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
122 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
123 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
124 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
125 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000126
127 Value *VisitInitListExpr(InitListExpr *E) {
Devang Patel01ab1302007-10-24 17:18:43 +0000128 unsigned N = E->getNumInits();
Devang Patel32c39832007-10-24 18:05:48 +0000129 QualType T = E->getInit(0)->getType();
130 Value *V = llvm::UndefValue::get(llvm::VectorType::get(ConvertType(T), N));
Devang Patel01ab1302007-10-24 17:18:43 +0000131 for (unsigned i = 0; i < N; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000132 Value *NewV = Visit(E->getInit(i));
133 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
134 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000135 }
Devang Patel32c39832007-10-24 18:05:48 +0000136 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000137 }
138
139 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
140 return Visit(E->getInitializer());
141 }
142
Chris Lattner9fba49a2007-08-24 05:35:26 +0000143 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
144 Value *VisitCastExpr(const CastExpr *E) {
145 return EmitCastExpr(E->getSubExpr(), E->getType());
146 }
147 Value *EmitCastExpr(const Expr *E, QualType T);
148
149 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000150 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000151 }
152
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000153 Value *VisitStmtExpr(const StmtExpr *E);
154
Chris Lattner9fba49a2007-08-24 05:35:26 +0000155 // Unary Operators.
156 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
157 Value *VisitUnaryPostDec(const UnaryOperator *E) {
158 return VisitPrePostIncDec(E, false, false);
159 }
160 Value *VisitUnaryPostInc(const UnaryOperator *E) {
161 return VisitPrePostIncDec(E, true, false);
162 }
163 Value *VisitUnaryPreDec(const UnaryOperator *E) {
164 return VisitPrePostIncDec(E, false, true);
165 }
166 Value *VisitUnaryPreInc(const UnaryOperator *E) {
167 return VisitPrePostIncDec(E, true, true);
168 }
169 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
170 return EmitLValue(E->getSubExpr()).getAddress();
171 }
172 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
173 Value *VisitUnaryPlus(const UnaryOperator *E) {
174 return Visit(E->getSubExpr());
175 }
176 Value *VisitUnaryMinus (const UnaryOperator *E);
177 Value *VisitUnaryNot (const UnaryOperator *E);
178 Value *VisitUnaryLNot (const UnaryOperator *E);
179 Value *VisitUnarySizeOf (const UnaryOperator *E) {
180 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
181 }
182 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
183 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
184 }
185 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
186 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000187 Value *VisitUnaryReal (const UnaryOperator *E);
188 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000189 Value *VisitUnaryExtension(const UnaryOperator *E) {
190 return Visit(E->getSubExpr());
191 }
192
193 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000194 Value *EmitMul(const BinOpInfo &Ops) {
195 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
196 }
197 Value *EmitDiv(const BinOpInfo &Ops);
198 Value *EmitRem(const BinOpInfo &Ops);
199 Value *EmitAdd(const BinOpInfo &Ops);
200 Value *EmitSub(const BinOpInfo &Ops);
201 Value *EmitShl(const BinOpInfo &Ops);
202 Value *EmitShr(const BinOpInfo &Ops);
203 Value *EmitAnd(const BinOpInfo &Ops) {
204 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
205 }
206 Value *EmitXor(const BinOpInfo &Ops) {
207 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
208 }
209 Value *EmitOr (const BinOpInfo &Ops) {
210 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
211 }
212
Chris Lattner660e31d2007-08-24 21:00:35 +0000213 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000214 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000215 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
216
217 // Binary operators and binary compound assignment operators.
218#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000219 Value *VisitBin ## OP(const BinaryOperator *E) { \
220 return Emit ## OP(EmitBinOps(E)); \
221 } \
222 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
223 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000224 }
225 HANDLEBINOP(Mul);
226 HANDLEBINOP(Div);
227 HANDLEBINOP(Rem);
228 HANDLEBINOP(Add);
229 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
230 HANDLEBINOP(Shl);
231 HANDLEBINOP(Shr);
232 HANDLEBINOP(And);
233 HANDLEBINOP(Xor);
234 HANDLEBINOP(Or);
235#undef HANDLEBINOP
236 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000237 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000238 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
239 }
240
Chris Lattner9fba49a2007-08-24 05:35:26 +0000241 // Comparisons.
242 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
243 unsigned SICmpOpc, unsigned FCmpOpc);
244#define VISITCOMP(CODE, UI, SI, FP) \
245 Value *VisitBin##CODE(const BinaryOperator *E) { \
246 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
247 llvm::FCmpInst::FP); }
248 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
249 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
250 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
251 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
252 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
253 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
254#undef VISITCOMP
255
256 Value *VisitBinAssign (const BinaryOperator *E);
257
258 Value *VisitBinLAnd (const BinaryOperator *E);
259 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000260 Value *VisitBinComma (const BinaryOperator *E);
261
262 // Other Operators.
263 Value *VisitConditionalOperator(const ConditionalOperator *CO);
264 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000265 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000266 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
267 return CGF.EmitObjCStringLiteral(E);
268 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000269 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000270};
271} // end anonymous namespace.
272
273//===----------------------------------------------------------------------===//
274// Utilities
275//===----------------------------------------------------------------------===//
276
Chris Lattnerd8d44222007-08-26 16:42:57 +0000277/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000278/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000279Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
280 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
281
282 if (SrcType->isRealFloatingType()) {
283 // Compare against 0.0 for fp scalars.
284 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000285 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
286 }
287
288 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
289 "Unknown scalar type to convert");
290
291 // Because of the type rules of C, we often end up computing a logical value,
292 // then zero extending it to int, then wanting it as a logical value again.
293 // Optimize this common case.
294 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
295 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
296 Value *Result = ZI->getOperand(0);
297 ZI->eraseFromParent();
298 return Result;
299 }
300 }
301
302 // Compare against an integer or pointer null.
303 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
304 return Builder.CreateICmpNE(Src, Zero, "tobool");
305}
306
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000307/// EmitScalarConversion - Emit a conversion from the specified type to the
308/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000309Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
310 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000311 SrcType = SrcType.getCanonicalType();
312 DstType = DstType.getCanonicalType();
313 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000314
315 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000316
317 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000318 if (DstType->isBooleanType())
319 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000320
321 const llvm::Type *DstTy = ConvertType(DstType);
322
323 // Ignore conversions like int -> uint.
324 if (Src->getType() == DstTy)
325 return Src;
326
327 // Handle pointer conversions next: pointers can only be converted to/from
328 // other pointers and integers.
329 if (isa<PointerType>(DstType)) {
330 // The source value may be an integer, or a pointer.
331 if (isa<llvm::PointerType>(Src->getType()))
332 return Builder.CreateBitCast(Src, DstTy, "conv");
333 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
334 return Builder.CreateIntToPtr(Src, DstTy, "conv");
335 }
336
337 if (isa<PointerType>(SrcType)) {
338 // Must be an ptr to int cast.
339 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000340 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000341 }
342
343 // Finally, we have the arithmetic types: real int/float.
344 if (isa<llvm::IntegerType>(Src->getType())) {
345 bool InputSigned = SrcType->isSignedIntegerType();
346 if (isa<llvm::IntegerType>(DstTy))
347 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
348 else if (InputSigned)
349 return Builder.CreateSIToFP(Src, DstTy, "conv");
350 else
351 return Builder.CreateUIToFP(Src, DstTy, "conv");
352 }
353
354 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
355 if (isa<llvm::IntegerType>(DstTy)) {
356 if (DstType->isSignedIntegerType())
357 return Builder.CreateFPToSI(Src, DstTy, "conv");
358 else
359 return Builder.CreateFPToUI(Src, DstTy, "conv");
360 }
361
362 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
363 if (DstTy->getTypeID() < Src->getType()->getTypeID())
364 return Builder.CreateFPTrunc(Src, DstTy, "conv");
365 else
366 return Builder.CreateFPExt(Src, DstTy, "conv");
367}
368
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000369/// EmitComplexToScalarConversion - Emit a conversion from the specified
370/// complex type to the specified destination type, where the destination
371/// type is an LLVM scalar type.
372Value *ScalarExprEmitter::
373EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
374 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000375 // Get the source element type.
376 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
377
378 // Handle conversions to bool first, they are special: comparisons against 0.
379 if (DstTy->isBooleanType()) {
380 // Complex != 0 -> (Real != 0) | (Imag != 0)
381 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
382 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
383 return Builder.CreateOr(Src.first, Src.second, "tobool");
384 }
385
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000386 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
387 // the imaginary part of the complex value is discarded and the value of the
388 // real part is converted according to the conversion rules for the
389 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000390 return EmitScalarConversion(Src.first, SrcTy, DstTy);
391}
392
393
Chris Lattner9fba49a2007-08-24 05:35:26 +0000394//===----------------------------------------------------------------------===//
395// Visitor Methods
396//===----------------------------------------------------------------------===//
397
398Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000399 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000400 if (E->getType()->isVoidType())
401 return 0;
402 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
403}
404
405Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
406 // Emit subscript expressions in rvalue context's. For most cases, this just
407 // loads the lvalue formed by the subscript expr. However, we have to be
408 // careful, because the base of a vector subscript is occasionally an rvalue,
409 // so we can't get it as an lvalue.
410 if (!E->getBase()->getType()->isVectorType())
411 return EmitLoadOfLValue(E);
412
413 // Handle the vector case. The base must be a vector, the index must be an
414 // integer value.
415 Value *Base = Visit(E->getBase());
416 Value *Idx = Visit(E->getIdx());
417
418 // FIXME: Convert Idx to i32 type.
419 return Builder.CreateExtractElement(Base, Idx, "vecext");
420}
421
422/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
423/// also handle things like function to pointer-to-function decay, and array to
424/// pointer decay.
425Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
426 const Expr *Op = E->getSubExpr();
427
428 // If this is due to array->pointer conversion, emit the array expression as
429 // an l-value.
430 if (Op->getType()->isArrayType()) {
431 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
432 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000433 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000434
435 assert(isa<llvm::PointerType>(V->getType()) &&
436 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
437 ->getElementType()) &&
438 "Doesn't support VLAs yet!");
439 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000440
441 llvm::Value *Ops[] = {Idx0, Idx0};
442 return Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000443 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000444 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
445 getReferenceeType() ==
446 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000447
448 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000449 }
450
451 return EmitCastExpr(Op, E->getType());
452}
453
454
455// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
456// have to handle a more broad range of conversions than explicit casts, as they
457// handle things like function to ptr-to-function decay etc.
458Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000459 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000460 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000461 Value *Src = Visit(const_cast<Expr*>(E));
462
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000463 // Use EmitScalarConversion to perform the conversion.
464 return EmitScalarConversion(Src, E->getType(), DestTy);
465 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000466
Chris Lattner82e10392007-08-26 07:26:12 +0000467 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000468 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
469 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000470}
471
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000472Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000473 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000474}
475
476
Chris Lattner9fba49a2007-08-24 05:35:26 +0000477//===----------------------------------------------------------------------===//
478// Unary Operators
479//===----------------------------------------------------------------------===//
480
481Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000482 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000483 LValue LV = EmitLValue(E->getSubExpr());
484 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000485 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000486 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000487
488 int AmountVal = isInc ? 1 : -1;
489
490 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000491 if (isa<llvm::PointerType>(InVal->getType())) {
492 // FIXME: This isn't right for VLAs.
493 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
494 NextVal = Builder.CreateGEP(InVal, NextVal);
495 } else {
496 // Add the inc/dec to the real part.
497 if (isa<llvm::IntegerType>(InVal->getType()))
498 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000499 else if (InVal->getType() == llvm::Type::FloatTy)
500 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000501 NextVal =
502 llvm::ConstantFP::get(InVal->getType(),
503 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000504 else {
505 // FIXME: Handle long double.
506 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000507 NextVal =
508 llvm::ConstantFP::get(InVal->getType(),
509 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000510 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000511 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
512 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000513
514 // Store the updated result through the lvalue.
515 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
516 E->getSubExpr()->getType());
517
518 // If this is a postinc, return the value read from memory, otherwise use the
519 // updated value.
520 return isPre ? NextVal : InVal;
521}
522
523
524Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
525 Value *Op = Visit(E->getSubExpr());
526 return Builder.CreateNeg(Op, "neg");
527}
528
529Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
530 Value *Op = Visit(E->getSubExpr());
531 return Builder.CreateNot(Op, "neg");
532}
533
534Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
535 // Compare operand to zero.
536 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
537
538 // Invert value.
539 // TODO: Could dynamically modify easy computations here. For example, if
540 // the operand is an icmp ne, turn into icmp eq.
541 BoolVal = Builder.CreateNot(BoolVal, "lnot");
542
543 // ZExt result to int.
544 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
545}
546
547/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
548/// an integer (RetType).
549Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000550 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000551 /// FIXME: This doesn't handle VLAs yet!
552 std::pair<uint64_t, unsigned> Info =
553 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
554
555 uint64_t Val = isSizeOf ? Info.first : Info.second;
556 Val /= 8; // Return size in bytes, not bits.
557
558 assert(RetType->isIntegerType() && "Result type must be an integer!");
559
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000560 uint32_t ResultWidth = static_cast<uint32_t>(
561 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000562 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
563}
564
Chris Lattner01211af2007-08-24 21:20:17 +0000565Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
566 Expr *Op = E->getSubExpr();
567 if (Op->getType()->isComplexType())
568 return CGF.EmitComplexExpr(Op).first;
569 return Visit(Op);
570}
571Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
572 Expr *Op = E->getSubExpr();
573 if (Op->getType()->isComplexType())
574 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000575
576 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
577 // effects are evaluated.
578 CGF.EmitScalarExpr(Op);
579 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000580}
581
582
Chris Lattner9fba49a2007-08-24 05:35:26 +0000583//===----------------------------------------------------------------------===//
584// Binary Operators
585//===----------------------------------------------------------------------===//
586
587BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
588 BinOpInfo Result;
589 Result.LHS = Visit(E->getLHS());
590 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000591 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000592 Result.E = E;
593 return Result;
594}
595
Chris Lattner0d965302007-08-26 21:41:21 +0000596Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000597 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
598 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
599
600 BinOpInfo OpInfo;
601
602 // Load the LHS and RHS operands.
603 LValue LHSLV = EmitLValue(E->getLHS());
604 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000605
606 // Determine the computation type. If the RHS is complex, then this is one of
607 // the add/sub/mul/div operators. All of these operators can be computed in
608 // with just their real component even though the computation domain really is
609 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000610 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000611
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000612 // If the computation type is complex, then the RHS is complex. Emit the RHS.
613 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
614 ComputeType = CT->getElementType();
615
616 // Emit the RHS, only keeping the real component.
617 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
618 RHSTy = RHSTy->getAsComplexType()->getElementType();
619 } else {
620 // Otherwise the RHS is a simple scalar value.
621 OpInfo.RHS = Visit(E->getRHS());
622 }
623
624 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000625 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000626
Devang Patel04011802007-10-25 22:19:13 +0000627 // Do not merge types for -= or += where the LHS is a pointer.
628 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000629 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000630 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000631 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000632 }
633 OpInfo.Ty = ComputeType;
634 OpInfo.E = E;
635
636 // Expand the binary operator.
637 Value *Result = (this->*Func)(OpInfo);
638
639 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000640 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000641
642 // Store the result value into the LHS lvalue.
643 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
644
645 return Result;
646}
647
648
Chris Lattner9fba49a2007-08-24 05:35:26 +0000649Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
650 if (Ops.LHS->getType()->isFloatingPoint())
651 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000652 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000653 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
654 else
655 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
656}
657
658Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
659 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000660 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000661 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
662 else
663 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
664}
665
666
667Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000668 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000669 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000670
671 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000672 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
673 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
674 // int + pointer
675 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
676}
677
678Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
679 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
680 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
681
Chris Lattner660e31d2007-08-24 21:00:35 +0000682 // pointer - int
683 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
684 "ptr-ptr shouldn't get here");
685 // FIXME: The pointer could point to a VLA.
686 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
687 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
688}
689
690Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
691 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
692 // the compound assignment case it is invalid, so just handle it here.
693 if (!E->getRHS()->getType()->isPointerType())
694 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000695
696 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000697 Value *LHS = Visit(E->getLHS());
698 Value *RHS = Visit(E->getRHS());
699
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000700 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
701 const QualType RHSType = E->getRHS()->getType().getCanonicalType();
702 assert(LHSType == RHSType && "Can't subtract different pointer types");
Chris Lattner660e31d2007-08-24 21:00:35 +0000703
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000704 QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000705 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
706 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000707
708 const llvm::Type *ResultType = ConvertType(E->getType());
709 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
710 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
711 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000712
713 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
714 // remainder. As such, we handle common power-of-two cases here to generate
715 // better code.
716 if (llvm::isPowerOf2_64(ElementSize)) {
717 Value *ShAmt =
718 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
719 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
720 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000721
Chris Lattner9fba49a2007-08-24 05:35:26 +0000722 // Otherwise, do a full sdiv.
723 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
724 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
725}
726
Chris Lattner660e31d2007-08-24 21:00:35 +0000727
Chris Lattner9fba49a2007-08-24 05:35:26 +0000728Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
729 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
730 // RHS to the same size as the LHS.
731 Value *RHS = Ops.RHS;
732 if (Ops.LHS->getType() != RHS->getType())
733 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
734
735 return Builder.CreateShl(Ops.LHS, RHS, "shl");
736}
737
738Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
739 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
740 // RHS to the same size as the LHS.
741 Value *RHS = Ops.RHS;
742 if (Ops.LHS->getType() != RHS->getType())
743 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
744
Chris Lattner660e31d2007-08-24 21:00:35 +0000745 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000746 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
747 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
748}
749
750Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
751 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000752 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000753 QualType LHSTy = E->getLHS()->getType();
754 if (!LHSTy->isComplexType()) {
755 Value *LHS = Visit(E->getLHS());
756 Value *RHS = Visit(E->getRHS());
757
758 if (LHS->getType()->isFloatingPoint()) {
759 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
760 LHS, RHS, "cmp");
761 } else if (LHSTy->isUnsignedIntegerType()) {
762 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
763 LHS, RHS, "cmp");
764 } else {
765 // Signed integers and pointers.
766 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
767 LHS, RHS, "cmp");
768 }
769 } else {
770 // Complex Comparison: can only be an equality comparison.
771 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
772 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
773
774 QualType CETy =
775 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
776
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000777 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000778 if (CETy->isRealFloatingType()) {
779 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
780 LHS.first, RHS.first, "cmp.r");
781 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
782 LHS.second, RHS.second, "cmp.i");
783 } else {
784 // Complex comparisons can only be equality comparisons. As such, signed
785 // and unsigned opcodes are the same.
786 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
787 LHS.first, RHS.first, "cmp.r");
788 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
789 LHS.second, RHS.second, "cmp.i");
790 }
791
792 if (E->getOpcode() == BinaryOperator::EQ) {
793 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
794 } else {
795 assert(E->getOpcode() == BinaryOperator::NE &&
796 "Complex comparison other than == or != ?");
797 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
798 }
799 }
800
801 // ZExt result to int.
802 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
803}
804
805Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
806 LValue LHS = EmitLValue(E->getLHS());
807 Value *RHS = Visit(E->getRHS());
808
809 // Store the value into the LHS.
810 // FIXME: Volatility!
811 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
812
813 // Return the RHS.
814 return RHS;
815}
816
817Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
818 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
819
820 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
821 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
822
823 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
824 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
825
826 CGF.EmitBlock(RHSBlock);
827 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
828
829 // Reaquire the RHS block, as there may be subblocks inserted.
830 RHSBlock = Builder.GetInsertBlock();
831 CGF.EmitBlock(ContBlock);
832
833 // Create a PHI node. If we just evaluted the LHS condition, the result is
834 // false. If we evaluated both, the result is the RHS condition.
835 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
836 PN->reserveOperandSpace(2);
837 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
838 PN->addIncoming(RHSCond, RHSBlock);
839
840 // ZExt result to int.
841 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
842}
843
844Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
845 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
846
847 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
848 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
849
850 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
851 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
852
853 CGF.EmitBlock(RHSBlock);
854 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
855
856 // Reaquire the RHS block, as there may be subblocks inserted.
857 RHSBlock = Builder.GetInsertBlock();
858 CGF.EmitBlock(ContBlock);
859
860 // Create a PHI node. If we just evaluted the LHS condition, the result is
861 // true. If we evaluated both, the result is the RHS condition.
862 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
863 PN->reserveOperandSpace(2);
864 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
865 PN->addIncoming(RHSCond, RHSBlock);
866
867 // ZExt result to int.
868 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
869}
870
871Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
872 CGF.EmitStmt(E->getLHS());
873 return Visit(E->getRHS());
874}
875
876//===----------------------------------------------------------------------===//
877// Other Operators
878//===----------------------------------------------------------------------===//
879
880Value *ScalarExprEmitter::
881VisitConditionalOperator(const ConditionalOperator *E) {
882 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
883 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
884 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
885
Chris Lattner98a425c2007-11-26 01:40:58 +0000886 // Evaluate the conditional, then convert it to bool. We do this explicitly
887 // because we need the unconverted value if this is a GNU ?: expression with
888 // missing middle value.
889 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
890 Value *CondBoolVal = CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
891 CGF.getContext().BoolTy);
892 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000893
894 CGF.EmitBlock(LHSBlock);
895
896 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +0000897 Value *LHS;
898 if (E->getLHS())
899 LHS = Visit(E->getLHS());
900 else // Perform promotions, to handle cases like "short ?: int"
901 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
902
Chris Lattner9fba49a2007-08-24 05:35:26 +0000903 Builder.CreateBr(ContBlock);
904 LHSBlock = Builder.GetInsertBlock();
905
906 CGF.EmitBlock(RHSBlock);
907
908 Value *RHS = Visit(E->getRHS());
909 Builder.CreateBr(ContBlock);
910 RHSBlock = Builder.GetInsertBlock();
911
912 CGF.EmitBlock(ContBlock);
913
Chris Lattner307da022007-11-30 17:56:23 +0000914 if (!LHS) {
915 assert(E->getType()->isVoidType() && "Non-void value should have a value");
916 return 0;
917 }
918
Chris Lattner9fba49a2007-08-24 05:35:26 +0000919 // Create a PHI node for the real part.
920 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
921 PN->reserveOperandSpace(2);
922 PN->addIncoming(LHS, LHSBlock);
923 PN->addIncoming(RHS, RHSBlock);
924 return PN;
925}
926
927Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000928 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000929 return
930 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000931}
932
Chris Lattner307da022007-11-30 17:56:23 +0000933Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +0000934 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
935
936 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
937 return V;
938}
939
Chris Lattner307da022007-11-30 17:56:23 +0000940Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +0000941 std::string str;
942
943 CGF.getContext().getObjcEncodingForType(E->getEncodedType(), str);
944
945 llvm::Constant *C = llvm::ConstantArray::get(str);
946 C = new llvm::GlobalVariable(C->getType(), true,
947 llvm::GlobalValue::InternalLinkage,
948 C, ".str", &CGF.CGM.getModule());
949 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
950 llvm::Constant *Zeros[] = { Zero, Zero };
951 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
952
953 return C;
954}
955
Chris Lattner9fba49a2007-08-24 05:35:26 +0000956//===----------------------------------------------------------------------===//
957// Entry Point into this File
958//===----------------------------------------------------------------------===//
959
960/// EmitComplexExpr - Emit the computation of the specified expression of
961/// complex type, ignoring the result.
962Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
963 assert(E && !hasAggregateLLVMType(E->getType()) &&
964 "Invalid scalar expression to emit");
965
966 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
967}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000968
969/// EmitScalarConversion - Emit a conversion from the specified type to the
970/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000971Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
972 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000973 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
974 "Invalid scalar expression to emit");
975 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
976}
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000977
978/// EmitComplexToScalarConversion - Emit a conversion from the specified
979/// complex type to the specified destination type, where the destination
980/// type is an LLVM scalar type.
981Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
982 QualType SrcTy,
983 QualType DstTy) {
984 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
985 "Invalid complex -> scalar conversion");
986 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
987 DstTy);
988}