blob: 410284a7b8e7d412290f16686729271fe19de2ea [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"
Chris Lattnerc2126682008-01-03 07:05:49 +000022#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000023
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);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000285 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000286 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000287 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
288 return CGF.EmitObjCStringLiteral(E);
289 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000290 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000291};
292} // end anonymous namespace.
293
294//===----------------------------------------------------------------------===//
295// Utilities
296//===----------------------------------------------------------------------===//
297
Chris Lattnerd8d44222007-08-26 16:42:57 +0000298/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000299/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000300Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
301 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
302
303 if (SrcType->isRealFloatingType()) {
304 // Compare against 0.0 for fp scalars.
305 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000306 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
307 }
308
309 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
310 "Unknown scalar type to convert");
311
312 // Because of the type rules of C, we often end up computing a logical value,
313 // then zero extending it to int, then wanting it as a logical value again.
314 // Optimize this common case.
315 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
316 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
317 Value *Result = ZI->getOperand(0);
318 ZI->eraseFromParent();
319 return Result;
320 }
321 }
322
323 // Compare against an integer or pointer null.
324 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
325 return Builder.CreateICmpNE(Src, Zero, "tobool");
326}
327
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000328/// EmitScalarConversion - Emit a conversion from the specified type to the
329/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000330Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
331 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000332 SrcType = SrcType.getCanonicalType();
333 DstType = DstType.getCanonicalType();
334 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000335
336 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000337
338 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000339 if (DstType->isBooleanType())
340 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000341
342 const llvm::Type *DstTy = ConvertType(DstType);
343
344 // Ignore conversions like int -> uint.
345 if (Src->getType() == DstTy)
346 return Src;
347
348 // Handle pointer conversions next: pointers can only be converted to/from
349 // other pointers and integers.
350 if (isa<PointerType>(DstType)) {
351 // The source value may be an integer, or a pointer.
352 if (isa<llvm::PointerType>(Src->getType()))
353 return Builder.CreateBitCast(Src, DstTy, "conv");
354 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
355 return Builder.CreateIntToPtr(Src, DstTy, "conv");
356 }
357
358 if (isa<PointerType>(SrcType)) {
359 // Must be an ptr to int cast.
360 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000361 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000362 }
363
Nate Begemanec2d1062007-12-30 02:59:45 +0000364 // A scalar source can be splatted to a vector of the same element type
365 if (isa<llvm::VectorType>(DstTy) && !isa<VectorType>(SrcType)) {
366 const llvm::VectorType *VT = cast<llvm::VectorType>(DstTy);
367 assert((VT->getElementType() == Src->getType()) &&
368 "Vector element type must match scalar type to splat.");
369 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
370 true);
371 }
372
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000373 if (isa<llvm::VectorType>(Src->getType()) ||
374 isa<llvm::VectorType>(DstTy)) {
375 return Builder.CreateBitCast(Src, DstTy, "conv");
376 }
377
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000378 // Finally, we have the arithmetic types: real int/float.
379 if (isa<llvm::IntegerType>(Src->getType())) {
380 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000381 if (isa<llvm::IntegerType>(DstTy))
382 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
383 else if (InputSigned)
384 return Builder.CreateSIToFP(Src, DstTy, "conv");
385 else
386 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000387 }
388
389 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
390 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000391 if (DstType->isSignedIntegerType())
392 return Builder.CreateFPToSI(Src, DstTy, "conv");
393 else
394 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000395 }
396
397 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000398 if (DstTy->getTypeID() < Src->getType()->getTypeID())
399 return Builder.CreateFPTrunc(Src, DstTy, "conv");
400 else
401 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000402}
403
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000404/// EmitComplexToScalarConversion - Emit a conversion from the specified
405/// complex type to the specified destination type, where the destination
406/// type is an LLVM scalar type.
407Value *ScalarExprEmitter::
408EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
409 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000410 // Get the source element type.
411 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
412
413 // Handle conversions to bool first, they are special: comparisons against 0.
414 if (DstTy->isBooleanType()) {
415 // Complex != 0 -> (Real != 0) | (Imag != 0)
416 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
417 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
418 return Builder.CreateOr(Src.first, Src.second, "tobool");
419 }
420
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000421 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
422 // the imaginary part of the complex value is discarded and the value of the
423 // real part is converted according to the conversion rules for the
424 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000425 return EmitScalarConversion(Src.first, SrcTy, DstTy);
426}
427
428
Chris Lattner9fba49a2007-08-24 05:35:26 +0000429//===----------------------------------------------------------------------===//
430// Visitor Methods
431//===----------------------------------------------------------------------===//
432
433Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000434 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000435 if (E->getType()->isVoidType())
436 return 0;
437 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
438}
439
440Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
441 // Emit subscript expressions in rvalue context's. For most cases, this just
442 // loads the lvalue formed by the subscript expr. However, we have to be
443 // careful, because the base of a vector subscript is occasionally an rvalue,
444 // so we can't get it as an lvalue.
445 if (!E->getBase()->getType()->isVectorType())
446 return EmitLoadOfLValue(E);
447
448 // Handle the vector case. The base must be a vector, the index must be an
449 // integer value.
450 Value *Base = Visit(E->getBase());
451 Value *Idx = Visit(E->getIdx());
452
453 // FIXME: Convert Idx to i32 type.
454 return Builder.CreateExtractElement(Base, Idx, "vecext");
455}
456
457/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
458/// also handle things like function to pointer-to-function decay, and array to
459/// pointer decay.
460Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
461 const Expr *Op = E->getSubExpr();
462
463 // If this is due to array->pointer conversion, emit the array expression as
464 // an l-value.
465 if (Op->getType()->isArrayType()) {
466 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
467 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000468 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000469
470 assert(isa<llvm::PointerType>(V->getType()) &&
471 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
472 ->getElementType()) &&
473 "Doesn't support VLAs yet!");
474 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000475
476 llvm::Value *Ops[] = {Idx0, Idx0};
Chris Lattnere54443b2007-12-12 04:13:20 +0000477 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
478
479 // The resultant pointer type can be implicitly casted to other pointer
480 // types as well, for example void*.
481 const llvm::Type *DestPTy = ConvertType(E->getType());
482 assert(isa<llvm::PointerType>(DestPTy) &&
483 "Only expect implicit cast to pointer");
484 if (V->getType() != DestPTy)
485 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
486 return V;
487
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000488 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000489 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
490 getReferenceeType() ==
491 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000492
493 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000494 }
495
496 return EmitCastExpr(Op, E->getType());
497}
498
499
500// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
501// have to handle a more broad range of conversions than explicit casts, as they
502// handle things like function to ptr-to-function decay etc.
503Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000504 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000505 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000506 Value *Src = Visit(const_cast<Expr*>(E));
507
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000508 // Use EmitScalarConversion to perform the conversion.
509 return EmitScalarConversion(Src, E->getType(), DestTy);
510 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000511
Chris Lattner82e10392007-08-26 07:26:12 +0000512 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000513 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
514 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000515}
516
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000517Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000518 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000519}
520
521
Chris Lattner9fba49a2007-08-24 05:35:26 +0000522//===----------------------------------------------------------------------===//
523// Unary Operators
524//===----------------------------------------------------------------------===//
525
526Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000527 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000528 LValue LV = EmitLValue(E->getSubExpr());
529 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000530 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000531 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000532
533 int AmountVal = isInc ? 1 : -1;
534
535 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000536 if (isa<llvm::PointerType>(InVal->getType())) {
537 // FIXME: This isn't right for VLAs.
538 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
539 NextVal = Builder.CreateGEP(InVal, NextVal);
540 } else {
541 // Add the inc/dec to the real part.
542 if (isa<llvm::IntegerType>(InVal->getType()))
543 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000544 else if (InVal->getType() == llvm::Type::FloatTy)
545 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000546 NextVal =
547 llvm::ConstantFP::get(InVal->getType(),
548 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000549 else {
550 // FIXME: Handle long double.
551 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000552 NextVal =
553 llvm::ConstantFP::get(InVal->getType(),
554 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000555 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000556 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
557 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000558
559 // Store the updated result through the lvalue.
560 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
561 E->getSubExpr()->getType());
562
563 // If this is a postinc, return the value read from memory, otherwise use the
564 // updated value.
565 return isPre ? NextVal : InVal;
566}
567
568
569Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
570 Value *Op = Visit(E->getSubExpr());
571 return Builder.CreateNeg(Op, "neg");
572}
573
574Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
575 Value *Op = Visit(E->getSubExpr());
576 return Builder.CreateNot(Op, "neg");
577}
578
579Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
580 // Compare operand to zero.
581 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
582
583 // Invert value.
584 // TODO: Could dynamically modify easy computations here. For example, if
585 // the operand is an icmp ne, turn into icmp eq.
586 BoolVal = Builder.CreateNot(BoolVal, "lnot");
587
588 // ZExt result to int.
589 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
590}
591
592/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
593/// an integer (RetType).
594Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000595 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000596 /// FIXME: This doesn't handle VLAs yet!
597 std::pair<uint64_t, unsigned> Info =
598 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
599
600 uint64_t Val = isSizeOf ? Info.first : Info.second;
601 Val /= 8; // Return size in bytes, not bits.
602
603 assert(RetType->isIntegerType() && "Result type must be an integer!");
604
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000605 uint32_t ResultWidth = static_cast<uint32_t>(
606 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000607 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
608}
609
Chris Lattner01211af2007-08-24 21:20:17 +0000610Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
611 Expr *Op = E->getSubExpr();
612 if (Op->getType()->isComplexType())
613 return CGF.EmitComplexExpr(Op).first;
614 return Visit(Op);
615}
616Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
617 Expr *Op = E->getSubExpr();
618 if (Op->getType()->isComplexType())
619 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000620
621 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
622 // effects are evaluated.
623 CGF.EmitScalarExpr(Op);
624 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000625}
626
627
Chris Lattner9fba49a2007-08-24 05:35:26 +0000628//===----------------------------------------------------------------------===//
629// Binary Operators
630//===----------------------------------------------------------------------===//
631
632BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
633 BinOpInfo Result;
634 Result.LHS = Visit(E->getLHS());
635 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000636 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000637 Result.E = E;
638 return Result;
639}
640
Chris Lattner0d965302007-08-26 21:41:21 +0000641Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000642 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
643 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
644
645 BinOpInfo OpInfo;
646
647 // Load the LHS and RHS operands.
648 LValue LHSLV = EmitLValue(E->getLHS());
649 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000650
651 // Determine the computation type. If the RHS is complex, then this is one of
652 // the add/sub/mul/div operators. All of these operators can be computed in
653 // with just their real component even though the computation domain really is
654 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000655 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000656
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000657 // If the computation type is complex, then the RHS is complex. Emit the RHS.
658 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
659 ComputeType = CT->getElementType();
660
661 // Emit the RHS, only keeping the real component.
662 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
663 RHSTy = RHSTy->getAsComplexType()->getElementType();
664 } else {
665 // Otherwise the RHS is a simple scalar value.
666 OpInfo.RHS = Visit(E->getRHS());
667 }
668
669 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000670 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000671
Devang Patel04011802007-10-25 22:19:13 +0000672 // Do not merge types for -= or += where the LHS is a pointer.
673 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000674 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000675 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000676 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000677 }
678 OpInfo.Ty = ComputeType;
679 OpInfo.E = E;
680
681 // Expand the binary operator.
682 Value *Result = (this->*Func)(OpInfo);
683
684 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000685 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000686
687 // Store the result value into the LHS lvalue.
688 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
689
690 return Result;
691}
692
693
Chris Lattner9fba49a2007-08-24 05:35:26 +0000694Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000695 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000696 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000697 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000698 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
699 else
700 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
701}
702
703Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
704 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000705 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000706 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
707 else
708 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
709}
710
711
712Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000713 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000714 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000715
716 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000717 Value *Ptr, *Idx;
718 Expr *IdxExp;
719 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
720 Ptr = Ops.LHS;
721 Idx = Ops.RHS;
722 IdxExp = Ops.E->getRHS();
723 } else { // int + pointer
724 Ptr = Ops.RHS;
725 Idx = Ops.LHS;
726 IdxExp = Ops.E->getLHS();
727 }
728
729 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
730 if (Width < CGF.LLVMPointerWidth) {
731 // Zero or sign extend the pointer value based on whether the index is
732 // signed or not.
733 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
734 if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
735 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
736 else
737 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
738 }
739
740 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000741}
742
743Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
744 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
745 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
746
Chris Lattner660e31d2007-08-24 21:00:35 +0000747 // pointer - int
748 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
749 "ptr-ptr shouldn't get here");
750 // FIXME: The pointer could point to a VLA.
751 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
752 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
753}
754
755Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
756 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
757 // the compound assignment case it is invalid, so just handle it here.
758 if (!E->getRHS()->getType()->isPointerType())
759 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000760
761 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000762 Value *LHS = Visit(E->getLHS());
763 Value *RHS = Visit(E->getRHS());
764
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000765 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
Seo Sanghyeona570d312007-12-26 05:21:37 +0000766 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000767 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
768 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000769
770 const llvm::Type *ResultType = ConvertType(E->getType());
771 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
772 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
773 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000774
775 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
776 // remainder. As such, we handle common power-of-two cases here to generate
777 // better code.
778 if (llvm::isPowerOf2_64(ElementSize)) {
779 Value *ShAmt =
780 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
781 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
782 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000783
Chris Lattner9fba49a2007-08-24 05:35:26 +0000784 // Otherwise, do a full sdiv.
785 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
786 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
787}
788
Chris Lattner660e31d2007-08-24 21:00:35 +0000789
Chris Lattner9fba49a2007-08-24 05:35:26 +0000790Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
791 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
792 // RHS to the same size as the LHS.
793 Value *RHS = Ops.RHS;
794 if (Ops.LHS->getType() != RHS->getType())
795 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
796
797 return Builder.CreateShl(Ops.LHS, RHS, "shl");
798}
799
800Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
801 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
802 // RHS to the same size as the LHS.
803 Value *RHS = Ops.RHS;
804 if (Ops.LHS->getType() != RHS->getType())
805 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
806
Chris Lattner660e31d2007-08-24 21:00:35 +0000807 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000808 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
809 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
810}
811
812Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
813 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000814 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000815 QualType LHSTy = E->getLHS()->getType();
816 if (!LHSTy->isComplexType()) {
817 Value *LHS = Visit(E->getLHS());
818 Value *RHS = Visit(E->getRHS());
819
820 if (LHS->getType()->isFloatingPoint()) {
821 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
822 LHS, RHS, "cmp");
823 } else if (LHSTy->isUnsignedIntegerType()) {
824 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
825 LHS, RHS, "cmp");
826 } else {
827 // Signed integers and pointers.
828 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
829 LHS, RHS, "cmp");
830 }
831 } else {
832 // Complex Comparison: can only be an equality comparison.
833 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
834 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
835
836 QualType CETy =
837 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
838
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000839 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000840 if (CETy->isRealFloatingType()) {
841 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
842 LHS.first, RHS.first, "cmp.r");
843 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
844 LHS.second, RHS.second, "cmp.i");
845 } else {
846 // Complex comparisons can only be equality comparisons. As such, signed
847 // and unsigned opcodes are the same.
848 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
849 LHS.first, RHS.first, "cmp.r");
850 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
851 LHS.second, RHS.second, "cmp.i");
852 }
853
854 if (E->getOpcode() == BinaryOperator::EQ) {
855 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
856 } else {
857 assert(E->getOpcode() == BinaryOperator::NE &&
858 "Complex comparison other than == or != ?");
859 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
860 }
861 }
862
863 // ZExt result to int.
864 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
865}
866
867Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
868 LValue LHS = EmitLValue(E->getLHS());
869 Value *RHS = Visit(E->getRHS());
870
871 // Store the value into the LHS.
872 // FIXME: Volatility!
873 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
874
875 // Return the RHS.
876 return RHS;
877}
878
879Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
880 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
881
882 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
883 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
884
885 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
886 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
887
888 CGF.EmitBlock(RHSBlock);
889 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
890
891 // Reaquire the RHS block, as there may be subblocks inserted.
892 RHSBlock = Builder.GetInsertBlock();
893 CGF.EmitBlock(ContBlock);
894
895 // Create a PHI node. If we just evaluted the LHS condition, the result is
896 // false. If we evaluated both, the result is the RHS condition.
897 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
898 PN->reserveOperandSpace(2);
899 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
900 PN->addIncoming(RHSCond, RHSBlock);
901
902 // ZExt result to int.
903 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
904}
905
906Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
907 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
908
909 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
910 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
911
912 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
913 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
914
915 CGF.EmitBlock(RHSBlock);
916 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
917
918 // Reaquire the RHS block, as there may be subblocks inserted.
919 RHSBlock = Builder.GetInsertBlock();
920 CGF.EmitBlock(ContBlock);
921
922 // Create a PHI node. If we just evaluted the LHS condition, the result is
923 // true. If we evaluated both, the result is the RHS condition.
924 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
925 PN->reserveOperandSpace(2);
926 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
927 PN->addIncoming(RHSCond, RHSBlock);
928
929 // ZExt result to int.
930 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
931}
932
933Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
934 CGF.EmitStmt(E->getLHS());
935 return Visit(E->getRHS());
936}
937
938//===----------------------------------------------------------------------===//
939// Other Operators
940//===----------------------------------------------------------------------===//
941
942Value *ScalarExprEmitter::
943VisitConditionalOperator(const ConditionalOperator *E) {
944 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
945 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
946 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
947
Chris Lattner98a425c2007-11-26 01:40:58 +0000948 // Evaluate the conditional, then convert it to bool. We do this explicitly
949 // because we need the unconverted value if this is a GNU ?: expression with
950 // missing middle value.
951 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +0000952 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
953 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +0000954 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000955
956 CGF.EmitBlock(LHSBlock);
957
958 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +0000959 Value *LHS;
960 if (E->getLHS())
961 LHS = Visit(E->getLHS());
962 else // Perform promotions, to handle cases like "short ?: int"
963 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
964
Chris Lattner9fba49a2007-08-24 05:35:26 +0000965 Builder.CreateBr(ContBlock);
966 LHSBlock = Builder.GetInsertBlock();
967
968 CGF.EmitBlock(RHSBlock);
969
970 Value *RHS = Visit(E->getRHS());
971 Builder.CreateBr(ContBlock);
972 RHSBlock = Builder.GetInsertBlock();
973
974 CGF.EmitBlock(ContBlock);
975
Chris Lattner307da022007-11-30 17:56:23 +0000976 if (!LHS) {
977 assert(E->getType()->isVoidType() && "Non-void value should have a value");
978 return 0;
979 }
980
Chris Lattner9fba49a2007-08-24 05:35:26 +0000981 // Create a PHI node for the real part.
982 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
983 PN->reserveOperandSpace(2);
984 PN->addIncoming(LHS, LHSBlock);
985 PN->addIncoming(RHS, RHSBlock);
986 return PN;
987}
988
989Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000990 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000991 return
992 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000993}
994
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000995Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
996 return CGF.EmitCallExpr(E->getFn(), E->arg_begin()).getScalarVal();
997}
998
Chris Lattner307da022007-11-30 17:56:23 +0000999Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001000 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1001
1002 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1003 return V;
1004}
1005
Chris Lattner307da022007-11-30 17:56:23 +00001006Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001007 std::string str;
1008
Ted Kremenek42730c52008-01-07 19:49:32 +00001009 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001010
1011 llvm::Constant *C = llvm::ConstantArray::get(str);
1012 C = new llvm::GlobalVariable(C->getType(), true,
1013 llvm::GlobalValue::InternalLinkage,
1014 C, ".str", &CGF.CGM.getModule());
1015 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1016 llvm::Constant *Zeros[] = { Zero, Zero };
1017 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1018
1019 return C;
1020}
1021
Chris Lattner9fba49a2007-08-24 05:35:26 +00001022//===----------------------------------------------------------------------===//
1023// Entry Point into this File
1024//===----------------------------------------------------------------------===//
1025
1026/// EmitComplexExpr - Emit the computation of the specified expression of
1027/// complex type, ignoring the result.
1028Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1029 assert(E && !hasAggregateLLVMType(E->getType()) &&
1030 "Invalid scalar expression to emit");
1031
1032 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1033}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001034
1035/// EmitScalarConversion - Emit a conversion from the specified type to the
1036/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001037Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1038 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001039 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1040 "Invalid scalar expression to emit");
1041 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1042}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001043
1044/// EmitComplexToScalarConversion - Emit a conversion from the specified
1045/// complex type to the specified destination type, where the destination
1046/// type is an LLVM scalar type.
1047Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1048 QualType SrcTy,
1049 QualType DstTy) {
1050 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1051 "Invalid complex -> scalar conversion");
1052 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1053 DstTy);
1054}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001055
1056Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1057 assert(V1->getType() == V2->getType() &&
1058 "Vector operands must be of the same type");
1059
1060 unsigned NumElements =
1061 cast<llvm::VectorType>(V1->getType())->getNumElements();
1062
1063 va_list va;
1064 va_start(va, V2);
1065
1066 llvm::SmallVector<llvm::Constant*, 16> Args;
1067
1068 for (unsigned i = 0; i < NumElements; i++) {
1069 int n = va_arg(va, int);
1070
1071 assert(n >= 0 && n < (int)NumElements * 2 &&
1072 "Vector shuffle index out of bounds!");
1073
1074 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1075 }
1076
1077 const char *Name = va_arg(va, const char *);
1078 va_end(va);
1079
1080 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1081
1082 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1083}
1084
Anders Carlsson68b8be92007-12-15 21:23:30 +00001085llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Nate Begemanec2d1062007-12-30 02:59:45 +00001086 unsigned NumVals, bool isSplat)
Anders Carlsson68b8be92007-12-15 21:23:30 +00001087{
Anders Carlsson68b8be92007-12-15 21:23:30 +00001088 llvm::Value *Vec
1089 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1090
1091 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001092 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001093 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001094 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001095 }
1096
1097 return Vec;
1098}