blob: 5ef7496a6606f31dac3ee1804d549a34f4221a84 [file] [log] [blame]
Chris Lattner9fba49a2007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000019#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000020#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Support/Compiler.h"
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
132 std::vector<llvm::Constant*> VectorElts;
133 const llvm::VectorType *VType =
134 cast<llvm::VectorType>(ConvertType(E->getType()));
135
136 // Copy initializer elements.
137 bool AllConstElements = true;
138 unsigned i = 0;
139 for (i = 0; i < NumInitElements; ++i) {
140 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Visit(E->getInit(i))))
141 VectorElts.push_back(C);
142 else {
143 AllConstElements = false;
144 break;
145 }
146 }
147
148 unsigned NumVectorElements = VType->getNumElements();
149 const llvm::Type *ElementType = VType->getElementType();
150 if (AllConstElements) {
151 // Initialize remaining array elements.
152 for (/*Do not initialize i*/; i < NumVectorElements; ++i)
153 VectorElts.push_back(llvm::Constant::getNullValue(ElementType));
154
155 return llvm::ConstantVector::get(VectorElts);
156 }
157
158 // Emit individual vector element stores.
159 llvm::Value *V = llvm::UndefValue::get(VType);
160
161 // Emit already seen constants initializers.
162 for (i = 0; i < VectorElts.size(); i++) {
163 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
164 V = Builder.CreateInsertElement(V, VectorElts[i], Idx);
165 }
166
167 // Emit remaining initializers
168 for (/*Do not initialize i*/; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000169 Value *NewV = Visit(E->getInit(i));
170 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
171 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000172 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000173
174 // Emit remaining default initializers
175 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
176 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
177 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
178 V = Builder.CreateInsertElement(V, NewV, Idx);
179 }
180
Devang Patel32c39832007-10-24 18:05:48 +0000181 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000182 }
183
184 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
185 return Visit(E->getInitializer());
186 }
187
Chris Lattner9fba49a2007-08-24 05:35:26 +0000188 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
189 Value *VisitCastExpr(const CastExpr *E) {
190 return EmitCastExpr(E->getSubExpr(), E->getType());
191 }
192 Value *EmitCastExpr(const Expr *E, QualType T);
193
194 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000195 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000196 }
197
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000198 Value *VisitStmtExpr(const StmtExpr *E);
199
Chris Lattner9fba49a2007-08-24 05:35:26 +0000200 // Unary Operators.
201 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
202 Value *VisitUnaryPostDec(const UnaryOperator *E) {
203 return VisitPrePostIncDec(E, false, false);
204 }
205 Value *VisitUnaryPostInc(const UnaryOperator *E) {
206 return VisitPrePostIncDec(E, true, false);
207 }
208 Value *VisitUnaryPreDec(const UnaryOperator *E) {
209 return VisitPrePostIncDec(E, false, true);
210 }
211 Value *VisitUnaryPreInc(const UnaryOperator *E) {
212 return VisitPrePostIncDec(E, true, true);
213 }
214 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
215 return EmitLValue(E->getSubExpr()).getAddress();
216 }
217 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
218 Value *VisitUnaryPlus(const UnaryOperator *E) {
219 return Visit(E->getSubExpr());
220 }
221 Value *VisitUnaryMinus (const UnaryOperator *E);
222 Value *VisitUnaryNot (const UnaryOperator *E);
223 Value *VisitUnaryLNot (const UnaryOperator *E);
224 Value *VisitUnarySizeOf (const UnaryOperator *E) {
225 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
226 }
227 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
228 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
229 }
230 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
231 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000232 Value *VisitUnaryReal (const UnaryOperator *E);
233 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000234 Value *VisitUnaryExtension(const UnaryOperator *E) {
235 return Visit(E->getSubExpr());
236 }
237
238 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000239 Value *EmitMul(const BinOpInfo &Ops) {
240 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
241 }
242 Value *EmitDiv(const BinOpInfo &Ops);
243 Value *EmitRem(const BinOpInfo &Ops);
244 Value *EmitAdd(const BinOpInfo &Ops);
245 Value *EmitSub(const BinOpInfo &Ops);
246 Value *EmitShl(const BinOpInfo &Ops);
247 Value *EmitShr(const BinOpInfo &Ops);
248 Value *EmitAnd(const BinOpInfo &Ops) {
249 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
250 }
251 Value *EmitXor(const BinOpInfo &Ops) {
252 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
253 }
254 Value *EmitOr (const BinOpInfo &Ops) {
255 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
256 }
257
Chris Lattner660e31d2007-08-24 21:00:35 +0000258 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000259 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000260 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
261
262 // Binary operators and binary compound assignment operators.
263#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000264 Value *VisitBin ## OP(const BinaryOperator *E) { \
265 return Emit ## OP(EmitBinOps(E)); \
266 } \
267 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
268 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000269 }
270 HANDLEBINOP(Mul);
271 HANDLEBINOP(Div);
272 HANDLEBINOP(Rem);
273 HANDLEBINOP(Add);
274 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
275 HANDLEBINOP(Shl);
276 HANDLEBINOP(Shr);
277 HANDLEBINOP(And);
278 HANDLEBINOP(Xor);
279 HANDLEBINOP(Or);
280#undef HANDLEBINOP
281 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000282 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000283 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
284 }
285
Chris Lattner9fba49a2007-08-24 05:35:26 +0000286 // Comparisons.
287 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
288 unsigned SICmpOpc, unsigned FCmpOpc);
289#define VISITCOMP(CODE, UI, SI, FP) \
290 Value *VisitBin##CODE(const BinaryOperator *E) { \
291 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
292 llvm::FCmpInst::FP); }
293 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
294 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
295 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
296 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
297 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
298 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
299#undef VISITCOMP
300
301 Value *VisitBinAssign (const BinaryOperator *E);
302
303 Value *VisitBinLAnd (const BinaryOperator *E);
304 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000305 Value *VisitBinComma (const BinaryOperator *E);
306
307 // Other Operators.
308 Value *VisitConditionalOperator(const ConditionalOperator *CO);
309 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000310 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000311 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
312 return CGF.EmitObjCStringLiteral(E);
313 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000314 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000315};
316} // end anonymous namespace.
317
318//===----------------------------------------------------------------------===//
319// Utilities
320//===----------------------------------------------------------------------===//
321
Chris Lattnerd8d44222007-08-26 16:42:57 +0000322/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000323/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000324Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
325 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
326
327 if (SrcType->isRealFloatingType()) {
328 // Compare against 0.0 for fp scalars.
329 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000330 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
331 }
332
333 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
334 "Unknown scalar type to convert");
335
336 // Because of the type rules of C, we often end up computing a logical value,
337 // then zero extending it to int, then wanting it as a logical value again.
338 // Optimize this common case.
339 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
340 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
341 Value *Result = ZI->getOperand(0);
342 ZI->eraseFromParent();
343 return Result;
344 }
345 }
346
347 // Compare against an integer or pointer null.
348 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
349 return Builder.CreateICmpNE(Src, Zero, "tobool");
350}
351
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000352/// EmitScalarConversion - Emit a conversion from the specified type to the
353/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000354Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
355 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000356 SrcType = SrcType.getCanonicalType();
357 DstType = DstType.getCanonicalType();
358 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000359
360 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000361
362 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000363 if (DstType->isBooleanType())
364 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000365
366 const llvm::Type *DstTy = ConvertType(DstType);
367
368 // Ignore conversions like int -> uint.
369 if (Src->getType() == DstTy)
370 return Src;
371
372 // Handle pointer conversions next: pointers can only be converted to/from
373 // other pointers and integers.
374 if (isa<PointerType>(DstType)) {
375 // The source value may be an integer, or a pointer.
376 if (isa<llvm::PointerType>(Src->getType()))
377 return Builder.CreateBitCast(Src, DstTy, "conv");
378 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
379 return Builder.CreateIntToPtr(Src, DstTy, "conv");
380 }
381
382 if (isa<PointerType>(SrcType)) {
383 // Must be an ptr to int cast.
384 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000385 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000386 }
387
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000388 if (isa<llvm::VectorType>(Src->getType()) ||
389 isa<llvm::VectorType>(DstTy)) {
390 return Builder.CreateBitCast(Src, DstTy, "conv");
391 }
392
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000393 // Finally, we have the arithmetic types: real int/float.
394 if (isa<llvm::IntegerType>(Src->getType())) {
395 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000396 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Src)) {
397 if (isa<llvm::IntegerType>(DstTy))
398 return llvm::ConstantExpr::getIntegerCast(C, DstTy, InputSigned);
399 else if (InputSigned)
400 return llvm::ConstantExpr::getSIToFP(C, DstTy);
401 else
402 return llvm::ConstantExpr::getUIToFP(C, DstTy);
403 } else {
404 if (isa<llvm::IntegerType>(DstTy))
405 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
406 else if (InputSigned)
407 return Builder.CreateSIToFP(Src, DstTy, "conv");
408 else
409 return Builder.CreateUIToFP(Src, DstTy, "conv");
410 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000411 }
412
413 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
414 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000415 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Src)) {
416 if (DstType->isSignedIntegerType())
417 return llvm::ConstantExpr::getFPToSI(C, DstTy);
418 else
419 return llvm::ConstantExpr::getFPToUI(C, DstTy);
420 } else {
421 if (DstType->isSignedIntegerType())
422 return Builder.CreateFPToSI(Src, DstTy, "conv");
423 else
424 return Builder.CreateFPToUI(Src, DstTy, "conv");
425 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000426 }
427
428 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000429 if (llvm::Constant *C = dyn_cast<llvm::Constant>(Src)) {
430 if (DstTy->getTypeID() < Src->getType()->getTypeID())
431 return llvm::ConstantExpr::getFPTrunc(C, DstTy);
432 else
433 return llvm::ConstantExpr::getFPExtend(C, DstTy);
434 } else {
435 if (DstTy->getTypeID() < Src->getType()->getTypeID())
436 return Builder.CreateFPTrunc(Src, DstTy, "conv");
437 else
438 return Builder.CreateFPExt(Src, DstTy, "conv");
439 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000440}
441
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000442/// EmitComplexToScalarConversion - Emit a conversion from the specified
443/// complex type to the specified destination type, where the destination
444/// type is an LLVM scalar type.
445Value *ScalarExprEmitter::
446EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
447 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000448 // Get the source element type.
449 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
450
451 // Handle conversions to bool first, they are special: comparisons against 0.
452 if (DstTy->isBooleanType()) {
453 // Complex != 0 -> (Real != 0) | (Imag != 0)
454 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
455 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
456 return Builder.CreateOr(Src.first, Src.second, "tobool");
457 }
458
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000459 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
460 // the imaginary part of the complex value is discarded and the value of the
461 // real part is converted according to the conversion rules for the
462 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000463 return EmitScalarConversion(Src.first, SrcTy, DstTy);
464}
465
466
Chris Lattner9fba49a2007-08-24 05:35:26 +0000467//===----------------------------------------------------------------------===//
468// Visitor Methods
469//===----------------------------------------------------------------------===//
470
471Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000472 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000473 if (E->getType()->isVoidType())
474 return 0;
475 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
476}
477
478Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
479 // Emit subscript expressions in rvalue context's. For most cases, this just
480 // loads the lvalue formed by the subscript expr. However, we have to be
481 // careful, because the base of a vector subscript is occasionally an rvalue,
482 // so we can't get it as an lvalue.
483 if (!E->getBase()->getType()->isVectorType())
484 return EmitLoadOfLValue(E);
485
486 // Handle the vector case. The base must be a vector, the index must be an
487 // integer value.
488 Value *Base = Visit(E->getBase());
489 Value *Idx = Visit(E->getIdx());
490
491 // FIXME: Convert Idx to i32 type.
492 return Builder.CreateExtractElement(Base, Idx, "vecext");
493}
494
495/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
496/// also handle things like function to pointer-to-function decay, and array to
497/// pointer decay.
498Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
499 const Expr *Op = E->getSubExpr();
500
501 // If this is due to array->pointer conversion, emit the array expression as
502 // an l-value.
503 if (Op->getType()->isArrayType()) {
504 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
505 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000506 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000507
508 assert(isa<llvm::PointerType>(V->getType()) &&
509 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
510 ->getElementType()) &&
511 "Doesn't support VLAs yet!");
512 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000513
514 llvm::Value *Ops[] = {Idx0, Idx0};
Chris Lattnere54443b2007-12-12 04:13:20 +0000515 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
516
517 // The resultant pointer type can be implicitly casted to other pointer
518 // types as well, for example void*.
519 const llvm::Type *DestPTy = ConvertType(E->getType());
520 assert(isa<llvm::PointerType>(DestPTy) &&
521 "Only expect implicit cast to pointer");
522 if (V->getType() != DestPTy)
523 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
524 return V;
525
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000526 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000527 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
528 getReferenceeType() ==
529 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000530
531 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000532 }
533
534 return EmitCastExpr(Op, E->getType());
535}
536
537
538// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
539// have to handle a more broad range of conversions than explicit casts, as they
540// handle things like function to ptr-to-function decay etc.
541Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000542 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000543 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000544 Value *Src = Visit(const_cast<Expr*>(E));
545
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000546 // Use EmitScalarConversion to perform the conversion.
547 return EmitScalarConversion(Src, E->getType(), DestTy);
548 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000549
Chris Lattner82e10392007-08-26 07:26:12 +0000550 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000551 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
552 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000553}
554
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000555Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000556 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000557}
558
559
Chris Lattner9fba49a2007-08-24 05:35:26 +0000560//===----------------------------------------------------------------------===//
561// Unary Operators
562//===----------------------------------------------------------------------===//
563
564Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000565 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000566 LValue LV = EmitLValue(E->getSubExpr());
567 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000568 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000569 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000570
571 int AmountVal = isInc ? 1 : -1;
572
573 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000574 if (isa<llvm::PointerType>(InVal->getType())) {
575 // FIXME: This isn't right for VLAs.
576 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
577 NextVal = Builder.CreateGEP(InVal, NextVal);
578 } else {
579 // Add the inc/dec to the real part.
580 if (isa<llvm::IntegerType>(InVal->getType()))
581 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000582 else if (InVal->getType() == llvm::Type::FloatTy)
583 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000584 NextVal =
585 llvm::ConstantFP::get(InVal->getType(),
586 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000587 else {
588 // FIXME: Handle long double.
589 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000590 NextVal =
591 llvm::ConstantFP::get(InVal->getType(),
592 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000593 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000594 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
595 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000596
597 // Store the updated result through the lvalue.
598 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
599 E->getSubExpr()->getType());
600
601 // If this is a postinc, return the value read from memory, otherwise use the
602 // updated value.
603 return isPre ? NextVal : InVal;
604}
605
606
607Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
608 Value *Op = Visit(E->getSubExpr());
609 return Builder.CreateNeg(Op, "neg");
610}
611
612Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
613 Value *Op = Visit(E->getSubExpr());
614 return Builder.CreateNot(Op, "neg");
615}
616
617Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
618 // Compare operand to zero.
619 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
620
621 // Invert value.
622 // TODO: Could dynamically modify easy computations here. For example, if
623 // the operand is an icmp ne, turn into icmp eq.
624 BoolVal = Builder.CreateNot(BoolVal, "lnot");
625
626 // ZExt result to int.
627 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
628}
629
630/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
631/// an integer (RetType).
632Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000633 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000634 /// FIXME: This doesn't handle VLAs yet!
635 std::pair<uint64_t, unsigned> Info =
636 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
637
638 uint64_t Val = isSizeOf ? Info.first : Info.second;
639 Val /= 8; // Return size in bytes, not bits.
640
641 assert(RetType->isIntegerType() && "Result type must be an integer!");
642
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000643 uint32_t ResultWidth = static_cast<uint32_t>(
644 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000645 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
646}
647
Chris Lattner01211af2007-08-24 21:20:17 +0000648Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
649 Expr *Op = E->getSubExpr();
650 if (Op->getType()->isComplexType())
651 return CGF.EmitComplexExpr(Op).first;
652 return Visit(Op);
653}
654Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
655 Expr *Op = E->getSubExpr();
656 if (Op->getType()->isComplexType())
657 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000658
659 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
660 // effects are evaluated.
661 CGF.EmitScalarExpr(Op);
662 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000663}
664
665
Chris Lattner9fba49a2007-08-24 05:35:26 +0000666//===----------------------------------------------------------------------===//
667// Binary Operators
668//===----------------------------------------------------------------------===//
669
670BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
671 BinOpInfo Result;
672 Result.LHS = Visit(E->getLHS());
673 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000674 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000675 Result.E = E;
676 return Result;
677}
678
Chris Lattner0d965302007-08-26 21:41:21 +0000679Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000680 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
681 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
682
683 BinOpInfo OpInfo;
684
685 // Load the LHS and RHS operands.
686 LValue LHSLV = EmitLValue(E->getLHS());
687 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000688
689 // Determine the computation type. If the RHS is complex, then this is one of
690 // the add/sub/mul/div operators. All of these operators can be computed in
691 // with just their real component even though the computation domain really is
692 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000693 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000694
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000695 // If the computation type is complex, then the RHS is complex. Emit the RHS.
696 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
697 ComputeType = CT->getElementType();
698
699 // Emit the RHS, only keeping the real component.
700 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
701 RHSTy = RHSTy->getAsComplexType()->getElementType();
702 } else {
703 // Otherwise the RHS is a simple scalar value.
704 OpInfo.RHS = Visit(E->getRHS());
705 }
706
707 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000708 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000709
Devang Patel04011802007-10-25 22:19:13 +0000710 // Do not merge types for -= or += where the LHS is a pointer.
711 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000712 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000713 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000714 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000715 }
716 OpInfo.Ty = ComputeType;
717 OpInfo.E = E;
718
719 // Expand the binary operator.
720 Value *Result = (this->*Func)(OpInfo);
721
722 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000723 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000724
725 // Store the result value into the LHS lvalue.
726 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
727
728 return Result;
729}
730
731
Chris Lattner9fba49a2007-08-24 05:35:26 +0000732Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
733 if (Ops.LHS->getType()->isFloatingPoint())
734 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000735 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000736 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
737 else
738 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
739}
740
741Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
742 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000743 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000744 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
745 else
746 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
747}
748
749
750Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000751 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000752 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000753
754 // FIXME: What about a pointer to a VLA?
Chris Lattner9fba49a2007-08-24 05:35:26 +0000755 if (isa<llvm::PointerType>(Ops.LHS->getType())) // pointer + int
756 return Builder.CreateGEP(Ops.LHS, Ops.RHS, "add.ptr");
757 // int + pointer
758 return Builder.CreateGEP(Ops.RHS, Ops.LHS, "add.ptr");
759}
760
761Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
762 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
763 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
764
Chris Lattner660e31d2007-08-24 21:00:35 +0000765 // pointer - int
766 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
767 "ptr-ptr shouldn't get here");
768 // FIXME: The pointer could point to a VLA.
769 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
770 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
771}
772
773Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
774 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
775 // the compound assignment case it is invalid, so just handle it here.
776 if (!E->getRHS()->getType()->isPointerType())
777 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000778
779 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000780 Value *LHS = Visit(E->getLHS());
781 Value *RHS = Visit(E->getRHS());
782
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000783 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
784 const QualType RHSType = E->getRHS()->getType().getCanonicalType();
785 assert(LHSType == RHSType && "Can't subtract different pointer types");
Chris Lattner660e31d2007-08-24 21:00:35 +0000786
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000787 QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000788 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
789 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000790
791 const llvm::Type *ResultType = ConvertType(E->getType());
792 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
793 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
794 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000795
796 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
797 // remainder. As such, we handle common power-of-two cases here to generate
798 // better code.
799 if (llvm::isPowerOf2_64(ElementSize)) {
800 Value *ShAmt =
801 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
802 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
803 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000804
Chris Lattner9fba49a2007-08-24 05:35:26 +0000805 // Otherwise, do a full sdiv.
806 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
807 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
808}
809
Chris Lattner660e31d2007-08-24 21:00:35 +0000810
Chris Lattner9fba49a2007-08-24 05:35:26 +0000811Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
812 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
813 // RHS to the same size as the LHS.
814 Value *RHS = Ops.RHS;
815 if (Ops.LHS->getType() != RHS->getType())
816 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
817
818 return Builder.CreateShl(Ops.LHS, RHS, "shl");
819}
820
821Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
822 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
823 // RHS to the same size as the LHS.
824 Value *RHS = Ops.RHS;
825 if (Ops.LHS->getType() != RHS->getType())
826 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
827
Chris Lattner660e31d2007-08-24 21:00:35 +0000828 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000829 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
830 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
831}
832
833Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
834 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000835 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000836 QualType LHSTy = E->getLHS()->getType();
837 if (!LHSTy->isComplexType()) {
838 Value *LHS = Visit(E->getLHS());
839 Value *RHS = Visit(E->getRHS());
840
841 if (LHS->getType()->isFloatingPoint()) {
842 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
843 LHS, RHS, "cmp");
844 } else if (LHSTy->isUnsignedIntegerType()) {
845 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
846 LHS, RHS, "cmp");
847 } else {
848 // Signed integers and pointers.
849 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
850 LHS, RHS, "cmp");
851 }
852 } else {
853 // Complex Comparison: can only be an equality comparison.
854 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
855 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
856
857 QualType CETy =
858 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
859
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000860 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000861 if (CETy->isRealFloatingType()) {
862 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
863 LHS.first, RHS.first, "cmp.r");
864 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
865 LHS.second, RHS.second, "cmp.i");
866 } else {
867 // Complex comparisons can only be equality comparisons. As such, signed
868 // and unsigned opcodes are the same.
869 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
870 LHS.first, RHS.first, "cmp.r");
871 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
872 LHS.second, RHS.second, "cmp.i");
873 }
874
875 if (E->getOpcode() == BinaryOperator::EQ) {
876 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
877 } else {
878 assert(E->getOpcode() == BinaryOperator::NE &&
879 "Complex comparison other than == or != ?");
880 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
881 }
882 }
883
884 // ZExt result to int.
885 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
886}
887
888Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
889 LValue LHS = EmitLValue(E->getLHS());
890 Value *RHS = Visit(E->getRHS());
891
892 // Store the value into the LHS.
893 // FIXME: Volatility!
894 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
895
896 // Return the RHS.
897 return RHS;
898}
899
900Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
901 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
902
903 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
904 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
905
906 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
907 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
908
909 CGF.EmitBlock(RHSBlock);
910 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
911
912 // Reaquire the RHS block, as there may be subblocks inserted.
913 RHSBlock = Builder.GetInsertBlock();
914 CGF.EmitBlock(ContBlock);
915
916 // Create a PHI node. If we just evaluted the LHS condition, the result is
917 // false. If we evaluated both, the result is the RHS condition.
918 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
919 PN->reserveOperandSpace(2);
920 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
921 PN->addIncoming(RHSCond, RHSBlock);
922
923 // ZExt result to int.
924 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
925}
926
927Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
928 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
929
930 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
931 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
932
933 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
934 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
935
936 CGF.EmitBlock(RHSBlock);
937 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
938
939 // Reaquire the RHS block, as there may be subblocks inserted.
940 RHSBlock = Builder.GetInsertBlock();
941 CGF.EmitBlock(ContBlock);
942
943 // Create a PHI node. If we just evaluted the LHS condition, the result is
944 // true. If we evaluated both, the result is the RHS condition.
945 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
946 PN->reserveOperandSpace(2);
947 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
948 PN->addIncoming(RHSCond, RHSBlock);
949
950 // ZExt result to int.
951 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
952}
953
954Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
955 CGF.EmitStmt(E->getLHS());
956 return Visit(E->getRHS());
957}
958
959//===----------------------------------------------------------------------===//
960// Other Operators
961//===----------------------------------------------------------------------===//
962
963Value *ScalarExprEmitter::
964VisitConditionalOperator(const ConditionalOperator *E) {
965 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
966 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
967 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
968
Chris Lattner98a425c2007-11-26 01:40:58 +0000969 // Evaluate the conditional, then convert it to bool. We do this explicitly
970 // because we need the unconverted value if this is a GNU ?: expression with
971 // missing middle value.
972 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
973 Value *CondBoolVal = CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
974 CGF.getContext().BoolTy);
975 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000976
977 CGF.EmitBlock(LHSBlock);
978
979 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +0000980 Value *LHS;
981 if (E->getLHS())
982 LHS = Visit(E->getLHS());
983 else // Perform promotions, to handle cases like "short ?: int"
984 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
985
Chris Lattner9fba49a2007-08-24 05:35:26 +0000986 Builder.CreateBr(ContBlock);
987 LHSBlock = Builder.GetInsertBlock();
988
989 CGF.EmitBlock(RHSBlock);
990
991 Value *RHS = Visit(E->getRHS());
992 Builder.CreateBr(ContBlock);
993 RHSBlock = Builder.GetInsertBlock();
994
995 CGF.EmitBlock(ContBlock);
996
Chris Lattner307da022007-11-30 17:56:23 +0000997 if (!LHS) {
998 assert(E->getType()->isVoidType() && "Non-void value should have a value");
999 return 0;
1000 }
1001
Chris Lattner9fba49a2007-08-24 05:35:26 +00001002 // Create a PHI node for the real part.
1003 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1004 PN->reserveOperandSpace(2);
1005 PN->addIncoming(LHS, LHSBlock);
1006 PN->addIncoming(RHS, RHSBlock);
1007 return PN;
1008}
1009
1010Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001011 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001012 return
1013 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001014}
1015
Chris Lattner307da022007-11-30 17:56:23 +00001016Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001017 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1018
1019 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1020 return V;
1021}
1022
Chris Lattner307da022007-11-30 17:56:23 +00001023Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001024 std::string str;
1025
1026 CGF.getContext().getObjcEncodingForType(E->getEncodedType(), str);
1027
1028 llvm::Constant *C = llvm::ConstantArray::get(str);
1029 C = new llvm::GlobalVariable(C->getType(), true,
1030 llvm::GlobalValue::InternalLinkage,
1031 C, ".str", &CGF.CGM.getModule());
1032 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1033 llvm::Constant *Zeros[] = { Zero, Zero };
1034 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1035
1036 return C;
1037}
1038
Chris Lattner9fba49a2007-08-24 05:35:26 +00001039//===----------------------------------------------------------------------===//
1040// Entry Point into this File
1041//===----------------------------------------------------------------------===//
1042
1043/// EmitComplexExpr - Emit the computation of the specified expression of
1044/// complex type, ignoring the result.
1045Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1046 assert(E && !hasAggregateLLVMType(E->getType()) &&
1047 "Invalid scalar expression to emit");
1048
1049 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1050}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001051
1052/// EmitScalarConversion - Emit a conversion from the specified type to the
1053/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001054Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1055 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001056 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1057 "Invalid scalar expression to emit");
1058 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1059}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001060
1061/// EmitComplexToScalarConversion - Emit a conversion from the specified
1062/// complex type to the specified destination type, where the destination
1063/// type is an LLVM scalar type.
1064Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1065 QualType SrcTy,
1066 QualType DstTy) {
1067 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1068 "Invalid complex -> scalar conversion");
1069 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1070 DstTy);
1071}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001072
1073Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1074 assert(V1->getType() == V2->getType() &&
1075 "Vector operands must be of the same type");
1076
1077 unsigned NumElements =
1078 cast<llvm::VectorType>(V1->getType())->getNumElements();
1079
1080 va_list va;
1081 va_start(va, V2);
1082
1083 llvm::SmallVector<llvm::Constant*, 16> Args;
1084
1085 for (unsigned i = 0; i < NumElements; i++) {
1086 int n = va_arg(va, int);
1087
1088 assert(n >= 0 && n < (int)NumElements * 2 &&
1089 "Vector shuffle index out of bounds!");
1090
1091 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1092 }
1093
1094 const char *Name = va_arg(va, const char *);
1095 va_end(va);
1096
1097 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1098
1099 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1100}
1101