blob: 4ffe6c55759adca7ccf73d357db0f30ac82d7e31 [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
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000363 if (isa<llvm::VectorType>(Src->getType()) ||
364 isa<llvm::VectorType>(DstTy)) {
365 return Builder.CreateBitCast(Src, DstTy, "conv");
366 }
367
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000368 // Finally, we have the arithmetic types: real int/float.
369 if (isa<llvm::IntegerType>(Src->getType())) {
370 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000371 if (isa<llvm::IntegerType>(DstTy))
372 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
373 else if (InputSigned)
374 return Builder.CreateSIToFP(Src, DstTy, "conv");
375 else
376 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000377 }
378
379 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
380 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000381 if (DstType->isSignedIntegerType())
382 return Builder.CreateFPToSI(Src, DstTy, "conv");
383 else
384 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000385 }
386
387 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000388 if (DstTy->getTypeID() < Src->getType()->getTypeID())
389 return Builder.CreateFPTrunc(Src, DstTy, "conv");
390 else
391 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000392}
393
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000394/// EmitComplexToScalarConversion - Emit a conversion from the specified
395/// complex type to the specified destination type, where the destination
396/// type is an LLVM scalar type.
397Value *ScalarExprEmitter::
398EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
399 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000400 // Get the source element type.
401 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
402
403 // Handle conversions to bool first, they are special: comparisons against 0.
404 if (DstTy->isBooleanType()) {
405 // Complex != 0 -> (Real != 0) | (Imag != 0)
406 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
407 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
408 return Builder.CreateOr(Src.first, Src.second, "tobool");
409 }
410
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000411 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
412 // the imaginary part of the complex value is discarded and the value of the
413 // real part is converted according to the conversion rules for the
414 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000415 return EmitScalarConversion(Src.first, SrcTy, DstTy);
416}
417
418
Chris Lattner9fba49a2007-08-24 05:35:26 +0000419//===----------------------------------------------------------------------===//
420// Visitor Methods
421//===----------------------------------------------------------------------===//
422
423Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000424 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000425 if (E->getType()->isVoidType())
426 return 0;
427 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
428}
429
430Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
431 // Emit subscript expressions in rvalue context's. For most cases, this just
432 // loads the lvalue formed by the subscript expr. However, we have to be
433 // careful, because the base of a vector subscript is occasionally an rvalue,
434 // so we can't get it as an lvalue.
435 if (!E->getBase()->getType()->isVectorType())
436 return EmitLoadOfLValue(E);
437
438 // Handle the vector case. The base must be a vector, the index must be an
439 // integer value.
440 Value *Base = Visit(E->getBase());
441 Value *Idx = Visit(E->getIdx());
442
443 // FIXME: Convert Idx to i32 type.
444 return Builder.CreateExtractElement(Base, Idx, "vecext");
445}
446
447/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
448/// also handle things like function to pointer-to-function decay, and array to
449/// pointer decay.
450Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
451 const Expr *Op = E->getSubExpr();
452
453 // If this is due to array->pointer conversion, emit the array expression as
454 // an l-value.
455 if (Op->getType()->isArrayType()) {
456 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
457 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000458 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000459
460 assert(isa<llvm::PointerType>(V->getType()) &&
461 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
462 ->getElementType()) &&
463 "Doesn't support VLAs yet!");
464 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000465
466 llvm::Value *Ops[] = {Idx0, Idx0};
Chris Lattnere54443b2007-12-12 04:13:20 +0000467 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
468
469 // The resultant pointer type can be implicitly casted to other pointer
470 // types as well, for example void*.
471 const llvm::Type *DestPTy = ConvertType(E->getType());
472 assert(isa<llvm::PointerType>(DestPTy) &&
473 "Only expect implicit cast to pointer");
474 if (V->getType() != DestPTy)
475 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
476 return V;
477
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000478 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000479 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
480 getReferenceeType() ==
481 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000482
483 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000484 }
485
486 return EmitCastExpr(Op, E->getType());
487}
488
489
490// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
491// have to handle a more broad range of conversions than explicit casts, as they
492// handle things like function to ptr-to-function decay etc.
493Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000494 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000495 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000496 Value *Src = Visit(const_cast<Expr*>(E));
497
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000498 // Use EmitScalarConversion to perform the conversion.
499 return EmitScalarConversion(Src, E->getType(), DestTy);
500 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000501
Chris Lattner82e10392007-08-26 07:26:12 +0000502 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000503 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
504 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000505}
506
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000507Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000508 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000509}
510
511
Chris Lattner9fba49a2007-08-24 05:35:26 +0000512//===----------------------------------------------------------------------===//
513// Unary Operators
514//===----------------------------------------------------------------------===//
515
516Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000517 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000518 LValue LV = EmitLValue(E->getSubExpr());
519 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000520 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000521 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000522
523 int AmountVal = isInc ? 1 : -1;
524
525 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000526 if (isa<llvm::PointerType>(InVal->getType())) {
527 // FIXME: This isn't right for VLAs.
528 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
529 NextVal = Builder.CreateGEP(InVal, NextVal);
530 } else {
531 // Add the inc/dec to the real part.
532 if (isa<llvm::IntegerType>(InVal->getType()))
533 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000534 else if (InVal->getType() == llvm::Type::FloatTy)
535 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000536 NextVal =
537 llvm::ConstantFP::get(InVal->getType(),
538 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000539 else {
540 // FIXME: Handle long double.
541 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000542 NextVal =
543 llvm::ConstantFP::get(InVal->getType(),
544 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000545 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000546 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
547 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000548
549 // Store the updated result through the lvalue.
550 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
551 E->getSubExpr()->getType());
552
553 // If this is a postinc, return the value read from memory, otherwise use the
554 // updated value.
555 return isPre ? NextVal : InVal;
556}
557
558
559Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
560 Value *Op = Visit(E->getSubExpr());
561 return Builder.CreateNeg(Op, "neg");
562}
563
564Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
565 Value *Op = Visit(E->getSubExpr());
566 return Builder.CreateNot(Op, "neg");
567}
568
569Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
570 // Compare operand to zero.
571 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
572
573 // Invert value.
574 // TODO: Could dynamically modify easy computations here. For example, if
575 // the operand is an icmp ne, turn into icmp eq.
576 BoolVal = Builder.CreateNot(BoolVal, "lnot");
577
578 // ZExt result to int.
579 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
580}
581
582/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
583/// an integer (RetType).
584Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000585 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000586 /// FIXME: This doesn't handle VLAs yet!
587 std::pair<uint64_t, unsigned> Info =
588 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
589
590 uint64_t Val = isSizeOf ? Info.first : Info.second;
591 Val /= 8; // Return size in bytes, not bits.
592
593 assert(RetType->isIntegerType() && "Result type must be an integer!");
594
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000595 uint32_t ResultWidth = static_cast<uint32_t>(
596 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000597 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
598}
599
Chris Lattner01211af2007-08-24 21:20:17 +0000600Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
601 Expr *Op = E->getSubExpr();
602 if (Op->getType()->isComplexType())
603 return CGF.EmitComplexExpr(Op).first;
604 return Visit(Op);
605}
606Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
607 Expr *Op = E->getSubExpr();
608 if (Op->getType()->isComplexType())
609 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000610
611 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
612 // effects are evaluated.
613 CGF.EmitScalarExpr(Op);
614 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000615}
616
617
Chris Lattner9fba49a2007-08-24 05:35:26 +0000618//===----------------------------------------------------------------------===//
619// Binary Operators
620//===----------------------------------------------------------------------===//
621
622BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
623 BinOpInfo Result;
624 Result.LHS = Visit(E->getLHS());
625 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000626 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000627 Result.E = E;
628 return Result;
629}
630
Chris Lattner0d965302007-08-26 21:41:21 +0000631Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000632 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
633 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
634
635 BinOpInfo OpInfo;
636
637 // Load the LHS and RHS operands.
638 LValue LHSLV = EmitLValue(E->getLHS());
639 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000640
641 // Determine the computation type. If the RHS is complex, then this is one of
642 // the add/sub/mul/div operators. All of these operators can be computed in
643 // with just their real component even though the computation domain really is
644 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000645 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000646
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000647 // If the computation type is complex, then the RHS is complex. Emit the RHS.
648 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
649 ComputeType = CT->getElementType();
650
651 // Emit the RHS, only keeping the real component.
652 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
653 RHSTy = RHSTy->getAsComplexType()->getElementType();
654 } else {
655 // Otherwise the RHS is a simple scalar value.
656 OpInfo.RHS = Visit(E->getRHS());
657 }
658
659 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000660 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000661
Devang Patel04011802007-10-25 22:19:13 +0000662 // Do not merge types for -= or += where the LHS is a pointer.
663 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000664 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000665 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000666 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000667 }
668 OpInfo.Ty = ComputeType;
669 OpInfo.E = E;
670
671 // Expand the binary operator.
672 Value *Result = (this->*Func)(OpInfo);
673
674 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000675 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000676
677 // Store the result value into the LHS lvalue.
678 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
679
680 return Result;
681}
682
683
Chris Lattner9fba49a2007-08-24 05:35:26 +0000684Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
685 if (Ops.LHS->getType()->isFloatingPoint())
686 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000687 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000688 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
689 else
690 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
691}
692
693Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
694 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000695 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000696 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
697 else
698 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
699}
700
701
702Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000703 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000704 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000705
706 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000707 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
708 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
709 // int + pointer
710 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
711}
712
713Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
714 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
715 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
716
Chris Lattner660e31d2007-08-24 21:00:35 +0000717 // pointer - int
718 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
719 "ptr-ptr shouldn't get here");
720 // FIXME: The pointer could point to a VLA.
721 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
722 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
723}
724
725Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
726 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
727 // the compound assignment case it is invalid, so just handle it here.
728 if (!E->getRHS()->getType()->isPointerType())
729 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000730
731 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000732 Value *LHS = Visit(E->getLHS());
733 Value *RHS = Visit(E->getRHS());
734
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000735 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
Seo Sanghyeona570d312007-12-26 05:21:37 +0000736 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000737 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
738 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000739
740 const llvm::Type *ResultType = ConvertType(E->getType());
741 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
742 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
743 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000744
745 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
746 // remainder. As such, we handle common power-of-two cases here to generate
747 // better code.
748 if (llvm::isPowerOf2_64(ElementSize)) {
749 Value *ShAmt =
750 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
751 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
752 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000753
Chris Lattner9fba49a2007-08-24 05:35:26 +0000754 // Otherwise, do a full sdiv.
755 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
756 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
757}
758
Chris Lattner660e31d2007-08-24 21:00:35 +0000759
Chris Lattner9fba49a2007-08-24 05:35:26 +0000760Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
761 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
762 // RHS to the same size as the LHS.
763 Value *RHS = Ops.RHS;
764 if (Ops.LHS->getType() != RHS->getType())
765 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
766
767 return Builder.CreateShl(Ops.LHS, RHS, "shl");
768}
769
770Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
771 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
772 // RHS to the same size as the LHS.
773 Value *RHS = Ops.RHS;
774 if (Ops.LHS->getType() != RHS->getType())
775 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
776
Chris Lattner660e31d2007-08-24 21:00:35 +0000777 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000778 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
779 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
780}
781
782Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
783 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000784 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000785 QualType LHSTy = E->getLHS()->getType();
786 if (!LHSTy->isComplexType()) {
787 Value *LHS = Visit(E->getLHS());
788 Value *RHS = Visit(E->getRHS());
789
790 if (LHS->getType()->isFloatingPoint()) {
791 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
792 LHS, RHS, "cmp");
793 } else if (LHSTy->isUnsignedIntegerType()) {
794 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
795 LHS, RHS, "cmp");
796 } else {
797 // Signed integers and pointers.
798 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
799 LHS, RHS, "cmp");
800 }
801 } else {
802 // Complex Comparison: can only be an equality comparison.
803 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
804 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
805
806 QualType CETy =
807 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
808
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000809 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000810 if (CETy->isRealFloatingType()) {
811 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
812 LHS.first, RHS.first, "cmp.r");
813 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
814 LHS.second, RHS.second, "cmp.i");
815 } else {
816 // Complex comparisons can only be equality comparisons. As such, signed
817 // and unsigned opcodes are the same.
818 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
819 LHS.first, RHS.first, "cmp.r");
820 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
821 LHS.second, RHS.second, "cmp.i");
822 }
823
824 if (E->getOpcode() == BinaryOperator::EQ) {
825 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
826 } else {
827 assert(E->getOpcode() == BinaryOperator::NE &&
828 "Complex comparison other than == or != ?");
829 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
830 }
831 }
832
833 // ZExt result to int.
834 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
835}
836
837Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
838 LValue LHS = EmitLValue(E->getLHS());
839 Value *RHS = Visit(E->getRHS());
840
841 // Store the value into the LHS.
842 // FIXME: Volatility!
843 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
844
845 // Return the RHS.
846 return RHS;
847}
848
849Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
850 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
851
852 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
853 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
854
855 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
856 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
857
858 CGF.EmitBlock(RHSBlock);
859 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
860
861 // Reaquire the RHS block, as there may be subblocks inserted.
862 RHSBlock = Builder.GetInsertBlock();
863 CGF.EmitBlock(ContBlock);
864
865 // Create a PHI node. If we just evaluted the LHS condition, the result is
866 // false. If we evaluated both, the result is the RHS condition.
867 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
868 PN->reserveOperandSpace(2);
869 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
870 PN->addIncoming(RHSCond, RHSBlock);
871
872 // ZExt result to int.
873 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
874}
875
876Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
877 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
878
879 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
880 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
881
882 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
883 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
884
885 CGF.EmitBlock(RHSBlock);
886 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
887
888 // Reaquire the RHS block, as there may be subblocks inserted.
889 RHSBlock = Builder.GetInsertBlock();
890 CGF.EmitBlock(ContBlock);
891
892 // Create a PHI node. If we just evaluted the LHS condition, the result is
893 // true. If we evaluated both, the result is the RHS condition.
894 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
895 PN->reserveOperandSpace(2);
896 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
897 PN->addIncoming(RHSCond, RHSBlock);
898
899 // ZExt result to int.
900 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
901}
902
903Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
904 CGF.EmitStmt(E->getLHS());
905 return Visit(E->getRHS());
906}
907
908//===----------------------------------------------------------------------===//
909// Other Operators
910//===----------------------------------------------------------------------===//
911
912Value *ScalarExprEmitter::
913VisitConditionalOperator(const ConditionalOperator *E) {
914 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
915 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
916 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
917
Chris Lattner98a425c2007-11-26 01:40:58 +0000918 // Evaluate the conditional, then convert it to bool. We do this explicitly
919 // because we need the unconverted value if this is a GNU ?: expression with
920 // missing middle value.
921 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
922 Value *CondBoolVal = CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
923 CGF.getContext().BoolTy);
924 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000925
926 CGF.EmitBlock(LHSBlock);
927
928 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +0000929 Value *LHS;
930 if (E->getLHS())
931 LHS = Visit(E->getLHS());
932 else // Perform promotions, to handle cases like "short ?: int"
933 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
934
Chris Lattner9fba49a2007-08-24 05:35:26 +0000935 Builder.CreateBr(ContBlock);
936 LHSBlock = Builder.GetInsertBlock();
937
938 CGF.EmitBlock(RHSBlock);
939
940 Value *RHS = Visit(E->getRHS());
941 Builder.CreateBr(ContBlock);
942 RHSBlock = Builder.GetInsertBlock();
943
944 CGF.EmitBlock(ContBlock);
945
Chris Lattner307da022007-11-30 17:56:23 +0000946 if (!LHS) {
947 assert(E->getType()->isVoidType() && "Non-void value should have a value");
948 return 0;
949 }
950
Chris Lattner9fba49a2007-08-24 05:35:26 +0000951 // Create a PHI node for the real part.
952 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
953 PN->reserveOperandSpace(2);
954 PN->addIncoming(LHS, LHSBlock);
955 PN->addIncoming(RHS, RHSBlock);
956 return PN;
957}
958
959Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000960 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000961 return
962 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000963}
964
Chris Lattner307da022007-11-30 17:56:23 +0000965Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +0000966 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
967
968 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
969 return V;
970}
971
Chris Lattner307da022007-11-30 17:56:23 +0000972Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +0000973 std::string str;
974
975 CGF.getContext().getObjcEncodingForType(E->getEncodedType(), str);
976
977 llvm::Constant *C = llvm::ConstantArray::get(str);
978 C = new llvm::GlobalVariable(C->getType(), true,
979 llvm::GlobalValue::InternalLinkage,
980 C, ".str", &CGF.CGM.getModule());
981 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
982 llvm::Constant *Zeros[] = { Zero, Zero };
983 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
984
985 return C;
986}
987
Chris Lattner9fba49a2007-08-24 05:35:26 +0000988//===----------------------------------------------------------------------===//
989// Entry Point into this File
990//===----------------------------------------------------------------------===//
991
992/// EmitComplexExpr - Emit the computation of the specified expression of
993/// complex type, ignoring the result.
994Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
995 assert(E && !hasAggregateLLVMType(E->getType()) &&
996 "Invalid scalar expression to emit");
997
998 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
999}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001000
1001/// EmitScalarConversion - Emit a conversion from the specified type to the
1002/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001003Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1004 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001005 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1006 "Invalid scalar expression to emit");
1007 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1008}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001009
1010/// EmitComplexToScalarConversion - Emit a conversion from the specified
1011/// complex type to the specified destination type, where the destination
1012/// type is an LLVM scalar type.
1013Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1014 QualType SrcTy,
1015 QualType DstTy) {
1016 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1017 "Invalid complex -> scalar conversion");
1018 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1019 DstTy);
1020}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001021
1022Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1023 assert(V1->getType() == V2->getType() &&
1024 "Vector operands must be of the same type");
1025
1026 unsigned NumElements =
1027 cast<llvm::VectorType>(V1->getType())->getNumElements();
1028
1029 va_list va;
1030 va_start(va, V2);
1031
1032 llvm::SmallVector<llvm::Constant*, 16> Args;
1033
1034 for (unsigned i = 0; i < NumElements; i++) {
1035 int n = va_arg(va, int);
1036
1037 assert(n >= 0 && n < (int)NumElements * 2 &&
1038 "Vector shuffle index out of bounds!");
1039
1040 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1041 }
1042
1043 const char *Name = va_arg(va, const char *);
1044 va_end(va);
1045
1046 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1047
1048 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1049}
1050
Anders Carlsson68b8be92007-12-15 21:23:30 +00001051llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1052 unsigned NumVals)
1053{
Anders Carlsson68b8be92007-12-15 21:23:30 +00001054 llvm::Value *Vec
1055 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1056
1057 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
1058 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
1059 Vec = Builder.CreateInsertElement(Vec, Vals[i], Idx, "tmp");
1060 }
1061
1062 return Vec;
1063}