blob: 37389dcd4475067ccbb21e629a62b500e807c266 [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) {
399 fprintf(stderr, "Unimplemented scalar expr!\n");
Chris Lattner1aef6212007-09-13 01:17:29 +0000400 E->dump(CGF.getContext().SourceMgr);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000401 if (E->getType()->isVoidType())
402 return 0;
403 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
404}
405
406Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
407 // Emit subscript expressions in rvalue context's. For most cases, this just
408 // loads the lvalue formed by the subscript expr. However, we have to be
409 // careful, because the base of a vector subscript is occasionally an rvalue,
410 // so we can't get it as an lvalue.
411 if (!E->getBase()->getType()->isVectorType())
412 return EmitLoadOfLValue(E);
413
414 // Handle the vector case. The base must be a vector, the index must be an
415 // integer value.
416 Value *Base = Visit(E->getBase());
417 Value *Idx = Visit(E->getIdx());
418
419 // FIXME: Convert Idx to i32 type.
420 return Builder.CreateExtractElement(Base, Idx, "vecext");
421}
422
423/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
424/// also handle things like function to pointer-to-function decay, and array to
425/// pointer decay.
426Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
427 const Expr *Op = E->getSubExpr();
428
429 // If this is due to array->pointer conversion, emit the array expression as
430 // an l-value.
431 if (Op->getType()->isArrayType()) {
432 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
433 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000434 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000435
436 assert(isa<llvm::PointerType>(V->getType()) &&
437 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
438 ->getElementType()) &&
439 "Doesn't support VLAs yet!");
440 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000441
442 llvm::Value *Ops[] = {Idx0, Idx0};
443 return Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000444 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000445 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
446 getReferenceeType() ==
447 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000448
449 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000450 }
451
452 return EmitCastExpr(Op, E->getType());
453}
454
455
456// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
457// have to handle a more broad range of conversions than explicit casts, as they
458// handle things like function to ptr-to-function decay etc.
459Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000460 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000461 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000462 Value *Src = Visit(const_cast<Expr*>(E));
463
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000464 // Use EmitScalarConversion to perform the conversion.
465 return EmitScalarConversion(Src, E->getType(), DestTy);
466 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000467
Chris Lattner82e10392007-08-26 07:26:12 +0000468 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000469 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
470 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000471}
472
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000473Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000474 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000475}
476
477
Chris Lattner9fba49a2007-08-24 05:35:26 +0000478//===----------------------------------------------------------------------===//
479// Unary Operators
480//===----------------------------------------------------------------------===//
481
482Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000483 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000484 LValue LV = EmitLValue(E->getSubExpr());
485 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000486 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000487 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000488
489 int AmountVal = isInc ? 1 : -1;
490
491 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000492 if (isa<llvm::PointerType>(InVal->getType())) {
493 // FIXME: This isn't right for VLAs.
494 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
495 NextVal = Builder.CreateGEP(InVal, NextVal);
496 } else {
497 // Add the inc/dec to the real part.
498 if (isa<llvm::IntegerType>(InVal->getType()))
499 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000500 else if (InVal->getType() == llvm::Type::FloatTy)
501 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000502 NextVal =
503 llvm::ConstantFP::get(InVal->getType(),
504 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000505 else {
506 // FIXME: Handle long double.
507 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000508 NextVal =
509 llvm::ConstantFP::get(InVal->getType(),
510 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000511 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000512 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
513 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000514
515 // Store the updated result through the lvalue.
516 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
517 E->getSubExpr()->getType());
518
519 // If this is a postinc, return the value read from memory, otherwise use the
520 // updated value.
521 return isPre ? NextVal : InVal;
522}
523
524
525Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
526 Value *Op = Visit(E->getSubExpr());
527 return Builder.CreateNeg(Op, "neg");
528}
529
530Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
531 Value *Op = Visit(E->getSubExpr());
532 return Builder.CreateNot(Op, "neg");
533}
534
535Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
536 // Compare operand to zero.
537 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
538
539 // Invert value.
540 // TODO: Could dynamically modify easy computations here. For example, if
541 // the operand is an icmp ne, turn into icmp eq.
542 BoolVal = Builder.CreateNot(BoolVal, "lnot");
543
544 // ZExt result to int.
545 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
546}
547
548/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
549/// an integer (RetType).
550Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000551 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000552 /// FIXME: This doesn't handle VLAs yet!
553 std::pair<uint64_t, unsigned> Info =
554 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
555
556 uint64_t Val = isSizeOf ? Info.first : Info.second;
557 Val /= 8; // Return size in bytes, not bits.
558
559 assert(RetType->isIntegerType() && "Result type must be an integer!");
560
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000561 uint32_t ResultWidth = static_cast<uint32_t>(
562 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000563 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
564}
565
Chris Lattner01211af2007-08-24 21:20:17 +0000566Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
567 Expr *Op = E->getSubExpr();
568 if (Op->getType()->isComplexType())
569 return CGF.EmitComplexExpr(Op).first;
570 return Visit(Op);
571}
572Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
573 Expr *Op = E->getSubExpr();
574 if (Op->getType()->isComplexType())
575 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000576
577 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
578 // effects are evaluated.
579 CGF.EmitScalarExpr(Op);
580 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000581}
582
583
Chris Lattner9fba49a2007-08-24 05:35:26 +0000584//===----------------------------------------------------------------------===//
585// Binary Operators
586//===----------------------------------------------------------------------===//
587
588BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
589 BinOpInfo Result;
590 Result.LHS = Visit(E->getLHS());
591 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000592 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000593 Result.E = E;
594 return Result;
595}
596
Chris Lattner0d965302007-08-26 21:41:21 +0000597Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000598 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
599 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
600
601 BinOpInfo OpInfo;
602
603 // Load the LHS and RHS operands.
604 LValue LHSLV = EmitLValue(E->getLHS());
605 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000606
607 // Determine the computation type. If the RHS is complex, then this is one of
608 // the add/sub/mul/div operators. All of these operators can be computed in
609 // with just their real component even though the computation domain really is
610 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000611 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000612
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000613 // If the computation type is complex, then the RHS is complex. Emit the RHS.
614 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
615 ComputeType = CT->getElementType();
616
617 // Emit the RHS, only keeping the real component.
618 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
619 RHSTy = RHSTy->getAsComplexType()->getElementType();
620 } else {
621 // Otherwise the RHS is a simple scalar value.
622 OpInfo.RHS = Visit(E->getRHS());
623 }
624
625 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000626 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000627
Devang Patel04011802007-10-25 22:19:13 +0000628 // Do not merge types for -= or += where the LHS is a pointer.
629 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000630 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000631 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000632 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000633 }
634 OpInfo.Ty = ComputeType;
635 OpInfo.E = E;
636
637 // Expand the binary operator.
638 Value *Result = (this->*Func)(OpInfo);
639
640 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000641 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000642
643 // Store the result value into the LHS lvalue.
644 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
645
646 return Result;
647}
648
649
Chris Lattner9fba49a2007-08-24 05:35:26 +0000650Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
651 if (Ops.LHS->getType()->isFloatingPoint())
652 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000653 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000654 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
655 else
656 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
657}
658
659Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
660 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000661 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000662 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
663 else
664 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
665}
666
667
668Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000669 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000670 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000671
672 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000673 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
674 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
675 // int + pointer
676 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
677}
678
679Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
680 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
681 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
682
Chris Lattner660e31d2007-08-24 21:00:35 +0000683 // pointer - int
684 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
685 "ptr-ptr shouldn't get here");
686 // FIXME: The pointer could point to a VLA.
687 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
688 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
689}
690
691Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
692 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
693 // the compound assignment case it is invalid, so just handle it here.
694 if (!E->getRHS()->getType()->isPointerType())
695 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000696
697 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000698 Value *LHS = Visit(E->getLHS());
699 Value *RHS = Visit(E->getRHS());
700
701 const PointerType *LHSPtrType = E->getLHS()->getType()->getAsPointerType();
702 assert(LHSPtrType == E->getRHS()->getType()->getAsPointerType() &&
703 "Can't subtract different pointer types");
704
Chris Lattner9fba49a2007-08-24 05:35:26 +0000705 QualType LHSElementType = LHSPtrType->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000706 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
707 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000708
709 const llvm::Type *ResultType = ConvertType(E->getType());
710 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
711 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
712 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000713
714 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
715 // remainder. As such, we handle common power-of-two cases here to generate
716 // better code.
717 if (llvm::isPowerOf2_64(ElementSize)) {
718 Value *ShAmt =
719 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
720 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
721 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000722
Chris Lattner9fba49a2007-08-24 05:35:26 +0000723 // Otherwise, do a full sdiv.
724 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
725 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
726}
727
Chris Lattner660e31d2007-08-24 21:00:35 +0000728
Chris Lattner9fba49a2007-08-24 05:35:26 +0000729Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
730 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
731 // RHS to the same size as the LHS.
732 Value *RHS = Ops.RHS;
733 if (Ops.LHS->getType() != RHS->getType())
734 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
735
736 return Builder.CreateShl(Ops.LHS, RHS, "shl");
737}
738
739Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
740 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
741 // RHS to the same size as the LHS.
742 Value *RHS = Ops.RHS;
743 if (Ops.LHS->getType() != RHS->getType())
744 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
745
Chris Lattner660e31d2007-08-24 21:00:35 +0000746 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000747 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
748 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
749}
750
751Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
752 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000753 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000754 QualType LHSTy = E->getLHS()->getType();
755 if (!LHSTy->isComplexType()) {
756 Value *LHS = Visit(E->getLHS());
757 Value *RHS = Visit(E->getRHS());
758
759 if (LHS->getType()->isFloatingPoint()) {
760 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
761 LHS, RHS, "cmp");
762 } else if (LHSTy->isUnsignedIntegerType()) {
763 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
764 LHS, RHS, "cmp");
765 } else {
766 // Signed integers and pointers.
767 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
768 LHS, RHS, "cmp");
769 }
770 } else {
771 // Complex Comparison: can only be an equality comparison.
772 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
773 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
774
775 QualType CETy =
776 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
777
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000778 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000779 if (CETy->isRealFloatingType()) {
780 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
781 LHS.first, RHS.first, "cmp.r");
782 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
783 LHS.second, RHS.second, "cmp.i");
784 } else {
785 // Complex comparisons can only be equality comparisons. As such, signed
786 // and unsigned opcodes are the same.
787 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
788 LHS.first, RHS.first, "cmp.r");
789 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
790 LHS.second, RHS.second, "cmp.i");
791 }
792
793 if (E->getOpcode() == BinaryOperator::EQ) {
794 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
795 } else {
796 assert(E->getOpcode() == BinaryOperator::NE &&
797 "Complex comparison other than == or != ?");
798 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
799 }
800 }
801
802 // ZExt result to int.
803 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
804}
805
806Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
807 LValue LHS = EmitLValue(E->getLHS());
808 Value *RHS = Visit(E->getRHS());
809
810 // Store the value into the LHS.
811 // FIXME: Volatility!
812 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
813
814 // Return the RHS.
815 return RHS;
816}
817
818Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
819 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
820
821 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
822 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
823
824 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
825 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
826
827 CGF.EmitBlock(RHSBlock);
828 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
829
830 // Reaquire the RHS block, as there may be subblocks inserted.
831 RHSBlock = Builder.GetInsertBlock();
832 CGF.EmitBlock(ContBlock);
833
834 // Create a PHI node. If we just evaluted the LHS condition, the result is
835 // false. If we evaluated both, the result is the RHS condition.
836 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
837 PN->reserveOperandSpace(2);
838 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
839 PN->addIncoming(RHSCond, RHSBlock);
840
841 // ZExt result to int.
842 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
843}
844
845Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
846 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
847
848 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
849 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
850
851 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
852 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
853
854 CGF.EmitBlock(RHSBlock);
855 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
856
857 // Reaquire the RHS block, as there may be subblocks inserted.
858 RHSBlock = Builder.GetInsertBlock();
859 CGF.EmitBlock(ContBlock);
860
861 // Create a PHI node. If we just evaluted the LHS condition, the result is
862 // true. If we evaluated both, the result is the RHS condition.
863 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
864 PN->reserveOperandSpace(2);
865 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
866 PN->addIncoming(RHSCond, RHSBlock);
867
868 // ZExt result to int.
869 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
870}
871
872Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
873 CGF.EmitStmt(E->getLHS());
874 return Visit(E->getRHS());
875}
876
877//===----------------------------------------------------------------------===//
878// Other Operators
879//===----------------------------------------------------------------------===//
880
881Value *ScalarExprEmitter::
882VisitConditionalOperator(const ConditionalOperator *E) {
883 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
884 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
885 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
886
Chris Lattner98a425c2007-11-26 01:40:58 +0000887 // Evaluate the conditional, then convert it to bool. We do this explicitly
888 // because we need the unconverted value if this is a GNU ?: expression with
889 // missing middle value.
890 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
891 Value *CondBoolVal = CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
892 CGF.getContext().BoolTy);
893 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000894
895 CGF.EmitBlock(LHSBlock);
896
897 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +0000898 Value *LHS;
899 if (E->getLHS())
900 LHS = Visit(E->getLHS());
901 else // Perform promotions, to handle cases like "short ?: int"
902 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
903
Chris Lattner9fba49a2007-08-24 05:35:26 +0000904 Builder.CreateBr(ContBlock);
905 LHSBlock = Builder.GetInsertBlock();
906
907 CGF.EmitBlock(RHSBlock);
908
909 Value *RHS = Visit(E->getRHS());
910 Builder.CreateBr(ContBlock);
911 RHSBlock = Builder.GetInsertBlock();
912
913 CGF.EmitBlock(ContBlock);
914
Chris Lattner307da022007-11-30 17:56:23 +0000915 if (!LHS) {
916 assert(E->getType()->isVoidType() && "Non-void value should have a value");
917 return 0;
918 }
919
Chris Lattner9fba49a2007-08-24 05:35:26 +0000920 // Create a PHI node for the real part.
921 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
922 PN->reserveOperandSpace(2);
923 PN->addIncoming(LHS, LHSBlock);
924 PN->addIncoming(RHS, RHSBlock);
925 return PN;
926}
927
928Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000929 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000930 return
931 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000932}
933
Chris Lattner307da022007-11-30 17:56:23 +0000934Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +0000935 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
936
937 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
938 return V;
939}
940
Chris Lattner307da022007-11-30 17:56:23 +0000941Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +0000942 std::string str;
943
944 CGF.getContext().getObjcEncodingForType(E->getEncodedType(), str);
945
946 llvm::Constant *C = llvm::ConstantArray::get(str);
947 C = new llvm::GlobalVariable(C->getType(), true,
948 llvm::GlobalValue::InternalLinkage,
949 C, ".str", &CGF.CGM.getModule());
950 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
951 llvm::Constant *Zeros[] = { Zero, Zero };
952 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
953
954 return C;
955}
956
Chris Lattner9fba49a2007-08-24 05:35:26 +0000957//===----------------------------------------------------------------------===//
958// Entry Point into this File
959//===----------------------------------------------------------------------===//
960
961/// EmitComplexExpr - Emit the computation of the specified expression of
962/// complex type, ignoring the result.
963Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
964 assert(E && !hasAggregateLLVMType(E->getType()) &&
965 "Invalid scalar expression to emit");
966
967 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
968}
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000969
970/// EmitScalarConversion - Emit a conversion from the specified type to the
971/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000972Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
973 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000974 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
975 "Invalid scalar expression to emit");
976 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
977}
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000978
979/// EmitComplexToScalarConversion - Emit a conversion from the specified
980/// complex type to the specified destination type, where the destination
981/// type is an LLVM scalar type.
982Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
983 QualType SrcTy,
984 QualType DstTy) {
985 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
986 "Invalid complex -> scalar conversion");
987 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
988 DstTy);
989}