blob: 639b907e027183a78d17a174baa9fbd57be255d6 [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//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner9fba49a2007-08-24 05:35:26 +00007//
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"
Ted Kremenek03cf4df2007-12-10 23:44:32 +000022#include <stdarg.h>
23
Chris Lattner9fba49a2007-08-24 05:35:26 +000024using namespace clang;
25using namespace CodeGen;
26using llvm::Value;
27
28//===----------------------------------------------------------------------===//
29// Scalar Expression Emitter
30//===----------------------------------------------------------------------===//
31
32struct BinOpInfo {
33 Value *LHS;
34 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000035 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000036 const BinaryOperator *E;
37};
38
39namespace {
40class VISIBILITY_HIDDEN ScalarExprEmitter
41 : public StmtVisitor<ScalarExprEmitter, Value*> {
42 CodeGenFunction &CGF;
Devang Patel638b64c2007-10-09 19:49:58 +000043 llvm::LLVMFoldingBuilder &Builder;
Chris Lattner9fba49a2007-08-24 05:35:26 +000044public:
45
46 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
47 }
48
49
50 //===--------------------------------------------------------------------===//
51 // Utilities
52 //===--------------------------------------------------------------------===//
53
54 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
55 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
56
57 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000058 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000059 }
60
61 /// EmitLoadOfLValue - Given an expression with complex type that represents a
62 /// value l-value, this method emits the address of the l-value, then loads
63 /// and returns the result.
64 Value *EmitLoadOfLValue(const Expr *E) {
65 // FIXME: Volatile
66 return EmitLoadOfLValue(EmitLValue(E), E->getType());
67 }
68
Chris Lattnerd8d44222007-08-26 16:42:57 +000069 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000070 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000071 Value *EmitConversionToBool(Value *Src, QualType DstTy);
72
Chris Lattner4e05d1e2007-08-26 06:48:56 +000073 /// EmitScalarConversion - Emit a conversion from the specified type to the
74 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000075 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
76
77 /// EmitComplexToScalarConversion - Emit a conversion from the specified
78 /// complex type to the specified destination type, where the destination
79 /// type is an LLVM scalar type.
80 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
81 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000082
Chris Lattner9fba49a2007-08-24 05:35:26 +000083 //===--------------------------------------------------------------------===//
84 // Visitor Methods
85 //===--------------------------------------------------------------------===//
86
87 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000088 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000089 assert(0 && "Stmt can't have complex result type!");
90 return 0;
91 }
92 Value *VisitExpr(Expr *S);
93 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
94
95 // Leaves.
96 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
97 return llvm::ConstantInt::get(E->getValue());
98 }
99 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner7f298762007-09-22 18:47:25 +0000100 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000101 }
102 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
103 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
104 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000105 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
106 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
107 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000108 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
109 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000110 CGF.getContext().typesAreCompatible(
111 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000112 }
113 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
114 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
115 }
116
117 // l-values.
118 Value *VisitDeclRefExpr(DeclRefExpr *E) {
119 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
120 return llvm::ConstantInt::get(EC->getInitVal());
121 return EmitLoadOfLValue(E);
122 }
123 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
124 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
125 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
126 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
127 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000128
129 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000130 unsigned NumInitElements = E->getNumInits();
131
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000132 const llvm::VectorType *VType =
133 cast<llvm::VectorType>(ConvertType(E->getType()));
134
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000135 unsigned NumVectorElements = VType->getNumElements();
136 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000137
138 // Emit individual vector element stores.
139 llvm::Value *V = llvm::UndefValue::get(VType);
140
Anders Carlsson323d5682007-12-18 02:45:33 +0000141 // Emit initializers
142 unsigned i;
143 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000144 Value *NewV = Visit(E->getInit(i));
145 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
146 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000147 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000148
149 // Emit remaining default initializers
150 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
151 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
152 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
153 V = Builder.CreateInsertElement(V, NewV, Idx);
154 }
155
Devang Patel32c39832007-10-24 18:05:48 +0000156 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000157 }
158
159 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
160 return Visit(E->getInitializer());
161 }
162
Chris Lattner9fba49a2007-08-24 05:35:26 +0000163 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
164 Value *VisitCastExpr(const CastExpr *E) {
165 return EmitCastExpr(E->getSubExpr(), E->getType());
166 }
167 Value *EmitCastExpr(const Expr *E, QualType T);
168
169 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000170 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000171 }
172
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000173 Value *VisitStmtExpr(const StmtExpr *E);
174
Chris Lattner9fba49a2007-08-24 05:35:26 +0000175 // Unary Operators.
176 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
177 Value *VisitUnaryPostDec(const UnaryOperator *E) {
178 return VisitPrePostIncDec(E, false, false);
179 }
180 Value *VisitUnaryPostInc(const UnaryOperator *E) {
181 return VisitPrePostIncDec(E, true, false);
182 }
183 Value *VisitUnaryPreDec(const UnaryOperator *E) {
184 return VisitPrePostIncDec(E, false, true);
185 }
186 Value *VisitUnaryPreInc(const UnaryOperator *E) {
187 return VisitPrePostIncDec(E, true, true);
188 }
189 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
190 return EmitLValue(E->getSubExpr()).getAddress();
191 }
192 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
193 Value *VisitUnaryPlus(const UnaryOperator *E) {
194 return Visit(E->getSubExpr());
195 }
196 Value *VisitUnaryMinus (const UnaryOperator *E);
197 Value *VisitUnaryNot (const UnaryOperator *E);
198 Value *VisitUnaryLNot (const UnaryOperator *E);
199 Value *VisitUnarySizeOf (const UnaryOperator *E) {
200 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
201 }
202 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
203 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
204 }
205 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
206 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000207 Value *VisitUnaryReal (const UnaryOperator *E);
208 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000209 Value *VisitUnaryExtension(const UnaryOperator *E) {
210 return Visit(E->getSubExpr());
211 }
212
213 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000214 Value *EmitMul(const BinOpInfo &Ops) {
215 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
216 }
217 Value *EmitDiv(const BinOpInfo &Ops);
218 Value *EmitRem(const BinOpInfo &Ops);
219 Value *EmitAdd(const BinOpInfo &Ops);
220 Value *EmitSub(const BinOpInfo &Ops);
221 Value *EmitShl(const BinOpInfo &Ops);
222 Value *EmitShr(const BinOpInfo &Ops);
223 Value *EmitAnd(const BinOpInfo &Ops) {
224 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
225 }
226 Value *EmitXor(const BinOpInfo &Ops) {
227 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
228 }
229 Value *EmitOr (const BinOpInfo &Ops) {
230 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
231 }
232
Chris Lattner660e31d2007-08-24 21:00:35 +0000233 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000234 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000235 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
236
237 // Binary operators and binary compound assignment operators.
238#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000239 Value *VisitBin ## OP(const BinaryOperator *E) { \
240 return Emit ## OP(EmitBinOps(E)); \
241 } \
242 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
243 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000244 }
245 HANDLEBINOP(Mul);
246 HANDLEBINOP(Div);
247 HANDLEBINOP(Rem);
248 HANDLEBINOP(Add);
249 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
250 HANDLEBINOP(Shl);
251 HANDLEBINOP(Shr);
252 HANDLEBINOP(And);
253 HANDLEBINOP(Xor);
254 HANDLEBINOP(Or);
255#undef HANDLEBINOP
256 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000257 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000258 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
259 }
260
Chris Lattner9fba49a2007-08-24 05:35:26 +0000261 // Comparisons.
262 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
263 unsigned SICmpOpc, unsigned FCmpOpc);
264#define VISITCOMP(CODE, UI, SI, FP) \
265 Value *VisitBin##CODE(const BinaryOperator *E) { \
266 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
267 llvm::FCmpInst::FP); }
268 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
269 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
270 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
271 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
272 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
273 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
274#undef VISITCOMP
275
276 Value *VisitBinAssign (const BinaryOperator *E);
277
278 Value *VisitBinLAnd (const BinaryOperator *E);
279 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000280 Value *VisitBinComma (const BinaryOperator *E);
281
282 // Other Operators.
283 Value *VisitConditionalOperator(const ConditionalOperator *CO);
284 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000285 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000286 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
287 return CGF.EmitObjCStringLiteral(E);
288 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000289 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000290};
291} // end anonymous namespace.
292
293//===----------------------------------------------------------------------===//
294// Utilities
295//===----------------------------------------------------------------------===//
296
Chris Lattnerd8d44222007-08-26 16:42:57 +0000297/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000298/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000299Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
300 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
301
302 if (SrcType->isRealFloatingType()) {
303 // Compare against 0.0 for fp scalars.
304 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000305 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
306 }
307
308 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
309 "Unknown scalar type to convert");
310
311 // Because of the type rules of C, we often end up computing a logical value,
312 // then zero extending it to int, then wanting it as a logical value again.
313 // Optimize this common case.
314 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
315 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
316 Value *Result = ZI->getOperand(0);
317 ZI->eraseFromParent();
318 return Result;
319 }
320 }
321
322 // Compare against an integer or pointer null.
323 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
324 return Builder.CreateICmpNE(Src, Zero, "tobool");
325}
326
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000327/// EmitScalarConversion - Emit a conversion from the specified type to the
328/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000329Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
330 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000331 SrcType = SrcType.getCanonicalType();
332 DstType = DstType.getCanonicalType();
333 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000334
335 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000336
337 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000338 if (DstType->isBooleanType())
339 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000340
341 const llvm::Type *DstTy = ConvertType(DstType);
342
343 // Ignore conversions like int -> uint.
344 if (Src->getType() == DstTy)
345 return Src;
346
347 // Handle pointer conversions next: pointers can only be converted to/from
348 // other pointers and integers.
349 if (isa<PointerType>(DstType)) {
350 // The source value may be an integer, or a pointer.
351 if (isa<llvm::PointerType>(Src->getType()))
352 return Builder.CreateBitCast(Src, DstTy, "conv");
353 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
354 return Builder.CreateIntToPtr(Src, DstTy, "conv");
355 }
356
357 if (isa<PointerType>(SrcType)) {
358 // Must be an ptr to int cast.
359 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000360 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000361 }
362
Nate Begemanec2d1062007-12-30 02:59:45 +0000363 // A scalar source can be splatted to a vector of the same element type
364 if (isa<llvm::VectorType>(DstTy) && !isa<VectorType>(SrcType)) {
365 const llvm::VectorType *VT = cast<llvm::VectorType>(DstTy);
366 assert((VT->getElementType() == Src->getType()) &&
367 "Vector element type must match scalar type to splat.");
368 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
369 true);
370 }
371
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000372 if (isa<llvm::VectorType>(Src->getType()) ||
373 isa<llvm::VectorType>(DstTy)) {
374 return Builder.CreateBitCast(Src, DstTy, "conv");
375 }
376
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000377 // Finally, we have the arithmetic types: real int/float.
378 if (isa<llvm::IntegerType>(Src->getType())) {
379 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000380 if (isa<llvm::IntegerType>(DstTy))
381 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
382 else if (InputSigned)
383 return Builder.CreateSIToFP(Src, DstTy, "conv");
384 else
385 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000386 }
387
388 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
389 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000390 if (DstType->isSignedIntegerType())
391 return Builder.CreateFPToSI(Src, DstTy, "conv");
392 else
393 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000394 }
395
396 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000397 if (DstTy->getTypeID() < Src->getType()->getTypeID())
398 return Builder.CreateFPTrunc(Src, DstTy, "conv");
399 else
400 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000401}
402
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000403/// EmitComplexToScalarConversion - Emit a conversion from the specified
404/// complex type to the specified destination type, where the destination
405/// type is an LLVM scalar type.
406Value *ScalarExprEmitter::
407EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
408 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000409 // Get the source element type.
410 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
411
412 // Handle conversions to bool first, they are special: comparisons against 0.
413 if (DstTy->isBooleanType()) {
414 // Complex != 0 -> (Real != 0) | (Imag != 0)
415 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
416 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
417 return Builder.CreateOr(Src.first, Src.second, "tobool");
418 }
419
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000420 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
421 // the imaginary part of the complex value is discarded and the value of the
422 // real part is converted according to the conversion rules for the
423 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000424 return EmitScalarConversion(Src.first, SrcTy, DstTy);
425}
426
427
Chris Lattner9fba49a2007-08-24 05:35:26 +0000428//===----------------------------------------------------------------------===//
429// Visitor Methods
430//===----------------------------------------------------------------------===//
431
432Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000433 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000434 if (E->getType()->isVoidType())
435 return 0;
436 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
437}
438
439Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
440 // Emit subscript expressions in rvalue context's. For most cases, this just
441 // loads the lvalue formed by the subscript expr. However, we have to be
442 // careful, because the base of a vector subscript is occasionally an rvalue,
443 // so we can't get it as an lvalue.
444 if (!E->getBase()->getType()->isVectorType())
445 return EmitLoadOfLValue(E);
446
447 // Handle the vector case. The base must be a vector, the index must be an
448 // integer value.
449 Value *Base = Visit(E->getBase());
450 Value *Idx = Visit(E->getIdx());
451
452 // FIXME: Convert Idx to i32 type.
453 return Builder.CreateExtractElement(Base, Idx, "vecext");
454}
455
456/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
457/// also handle things like function to pointer-to-function decay, and array to
458/// pointer decay.
459Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
460 const Expr *Op = E->getSubExpr();
461
462 // If this is due to array->pointer conversion, emit the array expression as
463 // an l-value.
464 if (Op->getType()->isArrayType()) {
465 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
466 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000467 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000468
469 assert(isa<llvm::PointerType>(V->getType()) &&
470 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
471 ->getElementType()) &&
472 "Doesn't support VLAs yet!");
473 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000474
475 llvm::Value *Ops[] = {Idx0, Idx0};
Chris Lattnere54443b2007-12-12 04:13:20 +0000476 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
477
478 // The resultant pointer type can be implicitly casted to other pointer
479 // types as well, for example void*.
480 const llvm::Type *DestPTy = ConvertType(E->getType());
481 assert(isa<llvm::PointerType>(DestPTy) &&
482 "Only expect implicit cast to pointer");
483 if (V->getType() != DestPTy)
484 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
485 return V;
486
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000487 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000488 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
489 getReferenceeType() ==
490 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000491
492 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000493 }
494
495 return EmitCastExpr(Op, E->getType());
496}
497
498
499// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
500// have to handle a more broad range of conversions than explicit casts, as they
501// handle things like function to ptr-to-function decay etc.
502Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000503 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000504 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000505 Value *Src = Visit(const_cast<Expr*>(E));
506
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000507 // Use EmitScalarConversion to perform the conversion.
508 return EmitScalarConversion(Src, E->getType(), DestTy);
509 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000510
Chris Lattner82e10392007-08-26 07:26:12 +0000511 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000512 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
513 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000514}
515
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000516Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000517 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000518}
519
520
Chris Lattner9fba49a2007-08-24 05:35:26 +0000521//===----------------------------------------------------------------------===//
522// Unary Operators
523//===----------------------------------------------------------------------===//
524
525Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000526 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000527 LValue LV = EmitLValue(E->getSubExpr());
528 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000529 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000530 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000531
532 int AmountVal = isInc ? 1 : -1;
533
534 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000535 if (isa<llvm::PointerType>(InVal->getType())) {
536 // FIXME: This isn't right for VLAs.
537 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
538 NextVal = Builder.CreateGEP(InVal, NextVal);
539 } else {
540 // Add the inc/dec to the real part.
541 if (isa<llvm::IntegerType>(InVal->getType()))
542 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000543 else if (InVal->getType() == llvm::Type::FloatTy)
544 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000545 NextVal =
546 llvm::ConstantFP::get(InVal->getType(),
547 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000548 else {
549 // FIXME: Handle long double.
550 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000551 NextVal =
552 llvm::ConstantFP::get(InVal->getType(),
553 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000554 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000555 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
556 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000557
558 // Store the updated result through the lvalue.
559 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
560 E->getSubExpr()->getType());
561
562 // If this is a postinc, return the value read from memory, otherwise use the
563 // updated value.
564 return isPre ? NextVal : InVal;
565}
566
567
568Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
569 Value *Op = Visit(E->getSubExpr());
570 return Builder.CreateNeg(Op, "neg");
571}
572
573Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
574 Value *Op = Visit(E->getSubExpr());
575 return Builder.CreateNot(Op, "neg");
576}
577
578Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
579 // Compare operand to zero.
580 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
581
582 // Invert value.
583 // TODO: Could dynamically modify easy computations here. For example, if
584 // the operand is an icmp ne, turn into icmp eq.
585 BoolVal = Builder.CreateNot(BoolVal, "lnot");
586
587 // ZExt result to int.
588 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
589}
590
591/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
592/// an integer (RetType).
593Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000594 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000595 /// FIXME: This doesn't handle VLAs yet!
596 std::pair<uint64_t, unsigned> Info =
597 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
598
599 uint64_t Val = isSizeOf ? Info.first : Info.second;
600 Val /= 8; // Return size in bytes, not bits.
601
602 assert(RetType->isIntegerType() && "Result type must be an integer!");
603
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000604 uint32_t ResultWidth = static_cast<uint32_t>(
605 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000606 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
607}
608
Chris Lattner01211af2007-08-24 21:20:17 +0000609Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
610 Expr *Op = E->getSubExpr();
611 if (Op->getType()->isComplexType())
612 return CGF.EmitComplexExpr(Op).first;
613 return Visit(Op);
614}
615Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
616 Expr *Op = E->getSubExpr();
617 if (Op->getType()->isComplexType())
618 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000619
620 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
621 // effects are evaluated.
622 CGF.EmitScalarExpr(Op);
623 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000624}
625
626
Chris Lattner9fba49a2007-08-24 05:35:26 +0000627//===----------------------------------------------------------------------===//
628// Binary Operators
629//===----------------------------------------------------------------------===//
630
631BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
632 BinOpInfo Result;
633 Result.LHS = Visit(E->getLHS());
634 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000635 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000636 Result.E = E;
637 return Result;
638}
639
Chris Lattner0d965302007-08-26 21:41:21 +0000640Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000641 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
642 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
643
644 BinOpInfo OpInfo;
645
646 // Load the LHS and RHS operands.
647 LValue LHSLV = EmitLValue(E->getLHS());
648 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000649
650 // Determine the computation type. If the RHS is complex, then this is one of
651 // the add/sub/mul/div operators. All of these operators can be computed in
652 // with just their real component even though the computation domain really is
653 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000654 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000655
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000656 // If the computation type is complex, then the RHS is complex. Emit the RHS.
657 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
658 ComputeType = CT->getElementType();
659
660 // Emit the RHS, only keeping the real component.
661 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
662 RHSTy = RHSTy->getAsComplexType()->getElementType();
663 } else {
664 // Otherwise the RHS is a simple scalar value.
665 OpInfo.RHS = Visit(E->getRHS());
666 }
667
668 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000669 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000670
Devang Patel04011802007-10-25 22:19:13 +0000671 // Do not merge types for -= or += where the LHS is a pointer.
672 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000673 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000674 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000675 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000676 }
677 OpInfo.Ty = ComputeType;
678 OpInfo.E = E;
679
680 // Expand the binary operator.
681 Value *Result = (this->*Func)(OpInfo);
682
683 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000684 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000685
686 // Store the result value into the LHS lvalue.
687 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
688
689 return Result;
690}
691
692
Chris Lattner9fba49a2007-08-24 05:35:26 +0000693Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000694 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000695 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000696 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000697 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
698 else
699 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
700}
701
702Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
703 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000704 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000705 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
706 else
707 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
708}
709
710
711Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000712 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000713 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000714
715 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000716 Value *Ptr, *Idx;
717 Expr *IdxExp;
718 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
719 Ptr = Ops.LHS;
720 Idx = Ops.RHS;
721 IdxExp = Ops.E->getRHS();
722 } else { // int + pointer
723 Ptr = Ops.RHS;
724 Idx = Ops.LHS;
725 IdxExp = Ops.E->getLHS();
726 }
727
728 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
729 if (Width < CGF.LLVMPointerWidth) {
730 // Zero or sign extend the pointer value based on whether the index is
731 // signed or not.
732 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
733 if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
734 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
735 else
736 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
737 }
738
739 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000740}
741
742Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
743 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
744 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
745
Chris Lattner660e31d2007-08-24 21:00:35 +0000746 // pointer - int
747 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
748 "ptr-ptr shouldn't get here");
749 // FIXME: The pointer could point to a VLA.
750 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
751 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
752}
753
754Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
755 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
756 // the compound assignment case it is invalid, so just handle it here.
757 if (!E->getRHS()->getType()->isPointerType())
758 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000759
760 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000761 Value *LHS = Visit(E->getLHS());
762 Value *RHS = Visit(E->getRHS());
763
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000764 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
Seo Sanghyeona570d312007-12-26 05:21:37 +0000765 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000766 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
767 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000768
769 const llvm::Type *ResultType = ConvertType(E->getType());
770 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
771 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
772 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000773
774 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
775 // remainder. As such, we handle common power-of-two cases here to generate
776 // better code.
777 if (llvm::isPowerOf2_64(ElementSize)) {
778 Value *ShAmt =
779 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
780 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
781 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000782
Chris Lattner9fba49a2007-08-24 05:35:26 +0000783 // Otherwise, do a full sdiv.
784 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
785 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
786}
787
Chris Lattner660e31d2007-08-24 21:00:35 +0000788
Chris Lattner9fba49a2007-08-24 05:35:26 +0000789Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
790 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
791 // RHS to the same size as the LHS.
792 Value *RHS = Ops.RHS;
793 if (Ops.LHS->getType() != RHS->getType())
794 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
795
796 return Builder.CreateShl(Ops.LHS, RHS, "shl");
797}
798
799Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
800 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
801 // RHS to the same size as the LHS.
802 Value *RHS = Ops.RHS;
803 if (Ops.LHS->getType() != RHS->getType())
804 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
805
Chris Lattner660e31d2007-08-24 21:00:35 +0000806 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000807 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
808 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
809}
810
811Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
812 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000813 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000814 QualType LHSTy = E->getLHS()->getType();
815 if (!LHSTy->isComplexType()) {
816 Value *LHS = Visit(E->getLHS());
817 Value *RHS = Visit(E->getRHS());
818
819 if (LHS->getType()->isFloatingPoint()) {
820 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
821 LHS, RHS, "cmp");
822 } else if (LHSTy->isUnsignedIntegerType()) {
823 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
824 LHS, RHS, "cmp");
825 } else {
826 // Signed integers and pointers.
827 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
828 LHS, RHS, "cmp");
829 }
830 } else {
831 // Complex Comparison: can only be an equality comparison.
832 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
833 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
834
835 QualType CETy =
836 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
837
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000838 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000839 if (CETy->isRealFloatingType()) {
840 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
841 LHS.first, RHS.first, "cmp.r");
842 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
843 LHS.second, RHS.second, "cmp.i");
844 } else {
845 // Complex comparisons can only be equality comparisons. As such, signed
846 // and unsigned opcodes are the same.
847 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
848 LHS.first, RHS.first, "cmp.r");
849 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
850 LHS.second, RHS.second, "cmp.i");
851 }
852
853 if (E->getOpcode() == BinaryOperator::EQ) {
854 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
855 } else {
856 assert(E->getOpcode() == BinaryOperator::NE &&
857 "Complex comparison other than == or != ?");
858 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
859 }
860 }
861
862 // ZExt result to int.
863 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
864}
865
866Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
867 LValue LHS = EmitLValue(E->getLHS());
868 Value *RHS = Visit(E->getRHS());
869
870 // Store the value into the LHS.
871 // FIXME: Volatility!
872 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
873
874 // Return the RHS.
875 return RHS;
876}
877
878Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
879 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
880
881 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
882 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
883
884 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
885 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
886
887 CGF.EmitBlock(RHSBlock);
888 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
889
890 // Reaquire the RHS block, as there may be subblocks inserted.
891 RHSBlock = Builder.GetInsertBlock();
892 CGF.EmitBlock(ContBlock);
893
894 // Create a PHI node. If we just evaluted the LHS condition, the result is
895 // false. If we evaluated both, the result is the RHS condition.
896 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
897 PN->reserveOperandSpace(2);
898 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
899 PN->addIncoming(RHSCond, RHSBlock);
900
901 // ZExt result to int.
902 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
903}
904
905Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
906 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
907
908 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
909 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
910
911 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
912 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
913
914 CGF.EmitBlock(RHSBlock);
915 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
916
917 // Reaquire the RHS block, as there may be subblocks inserted.
918 RHSBlock = Builder.GetInsertBlock();
919 CGF.EmitBlock(ContBlock);
920
921 // Create a PHI node. If we just evaluted the LHS condition, the result is
922 // true. If we evaluated both, the result is the RHS condition.
923 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
924 PN->reserveOperandSpace(2);
925 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
926 PN->addIncoming(RHSCond, RHSBlock);
927
928 // ZExt result to int.
929 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
930}
931
932Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
933 CGF.EmitStmt(E->getLHS());
934 return Visit(E->getRHS());
935}
936
937//===----------------------------------------------------------------------===//
938// Other Operators
939//===----------------------------------------------------------------------===//
940
941Value *ScalarExprEmitter::
942VisitConditionalOperator(const ConditionalOperator *E) {
943 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
944 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
945 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
946
Chris Lattner98a425c2007-11-26 01:40:58 +0000947 // Evaluate the conditional, then convert it to bool. We do this explicitly
948 // because we need the unconverted value if this is a GNU ?: expression with
949 // missing middle value.
950 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
951 Value *CondBoolVal = CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
952 CGF.getContext().BoolTy);
953 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000954
955 CGF.EmitBlock(LHSBlock);
956
957 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +0000958 Value *LHS;
959 if (E->getLHS())
960 LHS = Visit(E->getLHS());
961 else // Perform promotions, to handle cases like "short ?: int"
962 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
963
Chris Lattner9fba49a2007-08-24 05:35:26 +0000964 Builder.CreateBr(ContBlock);
965 LHSBlock = Builder.GetInsertBlock();
966
967 CGF.EmitBlock(RHSBlock);
968
969 Value *RHS = Visit(E->getRHS());
970 Builder.CreateBr(ContBlock);
971 RHSBlock = Builder.GetInsertBlock();
972
973 CGF.EmitBlock(ContBlock);
974
Chris Lattner307da022007-11-30 17:56:23 +0000975 if (!LHS) {
976 assert(E->getType()->isVoidType() && "Non-void value should have a value");
977 return 0;
978 }
979
Chris Lattner9fba49a2007-08-24 05:35:26 +0000980 // Create a PHI node for the real part.
981 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
982 PN->reserveOperandSpace(2);
983 PN->addIncoming(LHS, LHSBlock);
984 PN->addIncoming(RHS, RHSBlock);
985 return PN;
986}
987
988Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000989 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000990 return
991 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000992}
993
Chris Lattner307da022007-11-30 17:56:23 +0000994Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +0000995 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
996
997 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
998 return V;
999}
1000
Chris Lattner307da022007-11-30 17:56:23 +00001001Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001002 std::string str;
1003
1004 CGF.getContext().getObjcEncodingForType(E->getEncodedType(), str);
1005
1006 llvm::Constant *C = llvm::ConstantArray::get(str);
1007 C = new llvm::GlobalVariable(C->getType(), true,
1008 llvm::GlobalValue::InternalLinkage,
1009 C, ".str", &CGF.CGM.getModule());
1010 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1011 llvm::Constant *Zeros[] = { Zero, Zero };
1012 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1013
1014 return C;
1015}
1016
Chris Lattner9fba49a2007-08-24 05:35:26 +00001017//===----------------------------------------------------------------------===//
1018// Entry Point into this File
1019//===----------------------------------------------------------------------===//
1020
1021/// EmitComplexExpr - Emit the computation of the specified expression of
1022/// complex type, ignoring the result.
1023Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1024 assert(E && !hasAggregateLLVMType(E->getType()) &&
1025 "Invalid scalar expression to emit");
1026
1027 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1028}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001029
1030/// EmitScalarConversion - Emit a conversion from the specified type to the
1031/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001032Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1033 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001034 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1035 "Invalid scalar expression to emit");
1036 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1037}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001038
1039/// EmitComplexToScalarConversion - Emit a conversion from the specified
1040/// complex type to the specified destination type, where the destination
1041/// type is an LLVM scalar type.
1042Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1043 QualType SrcTy,
1044 QualType DstTy) {
1045 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1046 "Invalid complex -> scalar conversion");
1047 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1048 DstTy);
1049}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001050
1051Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1052 assert(V1->getType() == V2->getType() &&
1053 "Vector operands must be of the same type");
1054
1055 unsigned NumElements =
1056 cast<llvm::VectorType>(V1->getType())->getNumElements();
1057
1058 va_list va;
1059 va_start(va, V2);
1060
1061 llvm::SmallVector<llvm::Constant*, 16> Args;
1062
1063 for (unsigned i = 0; i < NumElements; i++) {
1064 int n = va_arg(va, int);
1065
1066 assert(n >= 0 && n < (int)NumElements * 2 &&
1067 "Vector shuffle index out of bounds!");
1068
1069 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1070 }
1071
1072 const char *Name = va_arg(va, const char *);
1073 va_end(va);
1074
1075 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1076
1077 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1078}
1079
Anders Carlsson68b8be92007-12-15 21:23:30 +00001080llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Nate Begemanec2d1062007-12-30 02:59:45 +00001081 unsigned NumVals, bool isSplat)
Anders Carlsson68b8be92007-12-15 21:23:30 +00001082{
Anders Carlsson68b8be92007-12-15 21:23:30 +00001083 llvm::Value *Vec
1084 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1085
1086 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001087 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001088 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001089 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001090 }
1091
1092 return Vec;
1093}