blob: 652729ac27b1e1f1a3516efd2970ddccdf18a436 [file] [log] [blame]
Chris Lattner9fba49a2007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner9fba49a2007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000019#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000020#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Support/Compiler.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000022#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000023
Chris Lattner9fba49a2007-08-24 05:35:26 +000024using namespace clang;
25using namespace CodeGen;
26using llvm::Value;
27
28//===----------------------------------------------------------------------===//
29// Scalar Expression Emitter
30//===----------------------------------------------------------------------===//
31
32struct BinOpInfo {
33 Value *LHS;
34 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000035 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000036 const BinaryOperator *E;
37};
38
39namespace {
40class VISIBILITY_HIDDEN ScalarExprEmitter
41 : public StmtVisitor<ScalarExprEmitter, Value*> {
42 CodeGenFunction &CGF;
Devang Patel638b64c2007-10-09 19:49:58 +000043 llvm::LLVMFoldingBuilder &Builder;
Chris Lattner9fba49a2007-08-24 05:35:26 +000044public:
45
46 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
47 }
48
49
50 //===--------------------------------------------------------------------===//
51 // Utilities
52 //===--------------------------------------------------------------------===//
53
54 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
55 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
56
57 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000058 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000059 }
60
61 /// EmitLoadOfLValue - Given an expression with complex type that represents a
62 /// value l-value, this method emits the address of the l-value, then loads
63 /// and returns the result.
64 Value *EmitLoadOfLValue(const Expr *E) {
65 // FIXME: Volatile
66 return EmitLoadOfLValue(EmitLValue(E), E->getType());
67 }
68
Chris Lattnerd8d44222007-08-26 16:42:57 +000069 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000070 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000071 Value *EmitConversionToBool(Value *Src, QualType DstTy);
72
Chris Lattner4e05d1e2007-08-26 06:48:56 +000073 /// EmitScalarConversion - Emit a conversion from the specified type to the
74 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000075 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
76
77 /// EmitComplexToScalarConversion - Emit a conversion from the specified
78 /// complex type to the specified destination type, where the destination
79 /// type is an LLVM scalar type.
80 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
81 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000082
Chris Lattner9fba49a2007-08-24 05:35:26 +000083 //===--------------------------------------------------------------------===//
84 // Visitor Methods
85 //===--------------------------------------------------------------------===//
86
87 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000088 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000089 assert(0 && "Stmt can't have complex result type!");
90 return 0;
91 }
92 Value *VisitExpr(Expr *S);
93 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
94
95 // Leaves.
96 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
97 return llvm::ConstantInt::get(E->getValue());
98 }
99 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner7f298762007-09-22 18:47:25 +0000100 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000101 }
102 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
103 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
104 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000105 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
106 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
107 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000108 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
109 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000110 CGF.getContext().typesAreCompatible(
111 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000112 }
113 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
114 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
115 }
116
117 // l-values.
118 Value *VisitDeclRefExpr(DeclRefExpr *E) {
119 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
120 return llvm::ConstantInt::get(EC->getInitVal());
121 return EmitLoadOfLValue(E);
122 }
123 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
124 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
125 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
126 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
127 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000128
129 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000130 unsigned NumInitElements = E->getNumInits();
131
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000132 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000133 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
134
135 // We have a scalar in braces. Just use the first element.
136 if (!VType)
137 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000138
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000139 unsigned NumVectorElements = VType->getNumElements();
140 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000141
142 // Emit individual vector element stores.
143 llvm::Value *V = llvm::UndefValue::get(VType);
144
Anders Carlsson323d5682007-12-18 02:45:33 +0000145 // Emit initializers
146 unsigned i;
147 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000148 Value *NewV = Visit(E->getInit(i));
149 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
150 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000151 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000152
153 // Emit remaining default initializers
154 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
155 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
156 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
157 V = Builder.CreateInsertElement(V, NewV, Idx);
158 }
159
Devang Patel32c39832007-10-24 18:05:48 +0000160 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000161 }
162
163 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
164 return Visit(E->getInitializer());
165 }
166
Chris Lattner9fba49a2007-08-24 05:35:26 +0000167 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
168 Value *VisitCastExpr(const CastExpr *E) {
169 return EmitCastExpr(E->getSubExpr(), E->getType());
170 }
171 Value *EmitCastExpr(const Expr *E, QualType T);
172
173 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000174 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000175 }
176
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000177 Value *VisitStmtExpr(const StmtExpr *E);
178
Chris Lattner9fba49a2007-08-24 05:35:26 +0000179 // Unary Operators.
180 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
181 Value *VisitUnaryPostDec(const UnaryOperator *E) {
182 return VisitPrePostIncDec(E, false, false);
183 }
184 Value *VisitUnaryPostInc(const UnaryOperator *E) {
185 return VisitPrePostIncDec(E, true, false);
186 }
187 Value *VisitUnaryPreDec(const UnaryOperator *E) {
188 return VisitPrePostIncDec(E, false, true);
189 }
190 Value *VisitUnaryPreInc(const UnaryOperator *E) {
191 return VisitPrePostIncDec(E, true, true);
192 }
193 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
194 return EmitLValue(E->getSubExpr()).getAddress();
195 }
196 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
197 Value *VisitUnaryPlus(const UnaryOperator *E) {
198 return Visit(E->getSubExpr());
199 }
200 Value *VisitUnaryMinus (const UnaryOperator *E);
201 Value *VisitUnaryNot (const UnaryOperator *E);
202 Value *VisitUnaryLNot (const UnaryOperator *E);
203 Value *VisitUnarySizeOf (const UnaryOperator *E) {
204 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
205 }
206 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
207 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
208 }
209 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
210 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000211 Value *VisitUnaryReal (const UnaryOperator *E);
212 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000213 Value *VisitUnaryExtension(const UnaryOperator *E) {
214 return Visit(E->getSubExpr());
215 }
216
217 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000218 Value *EmitMul(const BinOpInfo &Ops) {
219 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
220 }
221 Value *EmitDiv(const BinOpInfo &Ops);
222 Value *EmitRem(const BinOpInfo &Ops);
223 Value *EmitAdd(const BinOpInfo &Ops);
224 Value *EmitSub(const BinOpInfo &Ops);
225 Value *EmitShl(const BinOpInfo &Ops);
226 Value *EmitShr(const BinOpInfo &Ops);
227 Value *EmitAnd(const BinOpInfo &Ops) {
228 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
229 }
230 Value *EmitXor(const BinOpInfo &Ops) {
231 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
232 }
233 Value *EmitOr (const BinOpInfo &Ops) {
234 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
235 }
236
Chris Lattner660e31d2007-08-24 21:00:35 +0000237 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000238 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000239 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
240
241 // Binary operators and binary compound assignment operators.
242#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000243 Value *VisitBin ## OP(const BinaryOperator *E) { \
244 return Emit ## OP(EmitBinOps(E)); \
245 } \
246 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
247 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000248 }
249 HANDLEBINOP(Mul);
250 HANDLEBINOP(Div);
251 HANDLEBINOP(Rem);
252 HANDLEBINOP(Add);
253 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
254 HANDLEBINOP(Shl);
255 HANDLEBINOP(Shr);
256 HANDLEBINOP(And);
257 HANDLEBINOP(Xor);
258 HANDLEBINOP(Or);
259#undef HANDLEBINOP
260 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000261 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000262 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
263 }
264
Chris Lattner9fba49a2007-08-24 05:35:26 +0000265 // Comparisons.
266 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
267 unsigned SICmpOpc, unsigned FCmpOpc);
268#define VISITCOMP(CODE, UI, SI, FP) \
269 Value *VisitBin##CODE(const BinaryOperator *E) { \
270 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
271 llvm::FCmpInst::FP); }
272 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
273 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
274 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
275 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
276 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
277 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
278#undef VISITCOMP
279
280 Value *VisitBinAssign (const BinaryOperator *E);
281
282 Value *VisitBinLAnd (const BinaryOperator *E);
283 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000284 Value *VisitBinComma (const BinaryOperator *E);
285
286 // Other Operators.
287 Value *VisitConditionalOperator(const ConditionalOperator *CO);
288 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000289 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000290 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000291 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
292 return CGF.EmitObjCStringLiteral(E);
293 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000294 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000295};
296} // end anonymous namespace.
297
298//===----------------------------------------------------------------------===//
299// Utilities
300//===----------------------------------------------------------------------===//
301
Chris Lattnerd8d44222007-08-26 16:42:57 +0000302/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000303/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000304Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
305 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
306
307 if (SrcType->isRealFloatingType()) {
308 // Compare against 0.0 for fp scalars.
309 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000310 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
311 }
312
313 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
314 "Unknown scalar type to convert");
315
316 // Because of the type rules of C, we often end up computing a logical value,
317 // then zero extending it to int, then wanting it as a logical value again.
318 // Optimize this common case.
319 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
320 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
321 Value *Result = ZI->getOperand(0);
322 ZI->eraseFromParent();
323 return Result;
324 }
325 }
326
327 // Compare against an integer or pointer null.
328 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
329 return Builder.CreateICmpNE(Src, Zero, "tobool");
330}
331
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000332/// EmitScalarConversion - Emit a conversion from the specified type to the
333/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000334Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
335 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000336 SrcType = SrcType.getCanonicalType();
337 DstType = DstType.getCanonicalType();
338 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000339
340 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000341
342 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000343 if (DstType->isBooleanType())
344 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000345
346 const llvm::Type *DstTy = ConvertType(DstType);
347
348 // Ignore conversions like int -> uint.
349 if (Src->getType() == DstTy)
350 return Src;
351
352 // Handle pointer conversions next: pointers can only be converted to/from
353 // other pointers and integers.
354 if (isa<PointerType>(DstType)) {
355 // The source value may be an integer, or a pointer.
356 if (isa<llvm::PointerType>(Src->getType()))
357 return Builder.CreateBitCast(Src, DstTy, "conv");
358 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
359 return Builder.CreateIntToPtr(Src, DstTy, "conv");
360 }
361
362 if (isa<PointerType>(SrcType)) {
363 // Must be an ptr to int cast.
364 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000365 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000366 }
367
Nate Begemanec2d1062007-12-30 02:59:45 +0000368 // A scalar source can be splatted to a vector of the same element type
369 if (isa<llvm::VectorType>(DstTy) && !isa<VectorType>(SrcType)) {
370 const llvm::VectorType *VT = cast<llvm::VectorType>(DstTy);
371 assert((VT->getElementType() == Src->getType()) &&
372 "Vector element type must match scalar type to splat.");
373 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
374 true);
375 }
376
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000377 if (isa<llvm::VectorType>(Src->getType()) ||
378 isa<llvm::VectorType>(DstTy)) {
379 return Builder.CreateBitCast(Src, DstTy, "conv");
380 }
381
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000382 // Finally, we have the arithmetic types: real int/float.
383 if (isa<llvm::IntegerType>(Src->getType())) {
384 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000385 if (isa<llvm::IntegerType>(DstTy))
386 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
387 else if (InputSigned)
388 return Builder.CreateSIToFP(Src, DstTy, "conv");
389 else
390 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000391 }
392
393 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
394 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000395 if (DstType->isSignedIntegerType())
396 return Builder.CreateFPToSI(Src, DstTy, "conv");
397 else
398 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000399 }
400
401 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000402 if (DstTy->getTypeID() < Src->getType()->getTypeID())
403 return Builder.CreateFPTrunc(Src, DstTy, "conv");
404 else
405 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000406}
407
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000408/// EmitComplexToScalarConversion - Emit a conversion from the specified
409/// complex type to the specified destination type, where the destination
410/// type is an LLVM scalar type.
411Value *ScalarExprEmitter::
412EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
413 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000414 // Get the source element type.
415 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
416
417 // Handle conversions to bool first, they are special: comparisons against 0.
418 if (DstTy->isBooleanType()) {
419 // Complex != 0 -> (Real != 0) | (Imag != 0)
420 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
421 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
422 return Builder.CreateOr(Src.first, Src.second, "tobool");
423 }
424
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000425 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
426 // the imaginary part of the complex value is discarded and the value of the
427 // real part is converted according to the conversion rules for the
428 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000429 return EmitScalarConversion(Src.first, SrcTy, DstTy);
430}
431
432
Chris Lattner9fba49a2007-08-24 05:35:26 +0000433//===----------------------------------------------------------------------===//
434// Visitor Methods
435//===----------------------------------------------------------------------===//
436
437Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000438 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000439 if (E->getType()->isVoidType())
440 return 0;
441 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
442}
443
444Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
445 // Emit subscript expressions in rvalue context's. For most cases, this just
446 // loads the lvalue formed by the subscript expr. However, we have to be
447 // careful, because the base of a vector subscript is occasionally an rvalue,
448 // so we can't get it as an lvalue.
449 if (!E->getBase()->getType()->isVectorType())
450 return EmitLoadOfLValue(E);
451
452 // Handle the vector case. The base must be a vector, the index must be an
453 // integer value.
454 Value *Base = Visit(E->getBase());
455 Value *Idx = Visit(E->getIdx());
456
457 // FIXME: Convert Idx to i32 type.
458 return Builder.CreateExtractElement(Base, Idx, "vecext");
459}
460
461/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
462/// also handle things like function to pointer-to-function decay, and array to
463/// pointer decay.
464Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
465 const Expr *Op = E->getSubExpr();
466
467 // If this is due to array->pointer conversion, emit the array expression as
468 // an l-value.
469 if (Op->getType()->isArrayType()) {
470 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
471 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000472 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000473
474 assert(isa<llvm::PointerType>(V->getType()) &&
475 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
476 ->getElementType()) &&
477 "Doesn't support VLAs yet!");
478 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000479
480 llvm::Value *Ops[] = {Idx0, Idx0};
Chris Lattnere54443b2007-12-12 04:13:20 +0000481 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
482
483 // The resultant pointer type can be implicitly casted to other pointer
484 // types as well, for example void*.
485 const llvm::Type *DestPTy = ConvertType(E->getType());
486 assert(isa<llvm::PointerType>(DestPTy) &&
487 "Only expect implicit cast to pointer");
488 if (V->getType() != DestPTy)
489 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
490 return V;
491
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000492 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000493 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
494 getReferenceeType() ==
495 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000496
497 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000498 }
499
500 return EmitCastExpr(Op, E->getType());
501}
502
503
504// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
505// have to handle a more broad range of conversions than explicit casts, as they
506// handle things like function to ptr-to-function decay etc.
507Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000508 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000509 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000510 Value *Src = Visit(const_cast<Expr*>(E));
511
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000512 // Use EmitScalarConversion to perform the conversion.
513 return EmitScalarConversion(Src, E->getType(), DestTy);
514 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000515
Chris Lattner82e10392007-08-26 07:26:12 +0000516 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000517 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
518 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000519}
520
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000521Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000522 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000523}
524
525
Chris Lattner9fba49a2007-08-24 05:35:26 +0000526//===----------------------------------------------------------------------===//
527// Unary Operators
528//===----------------------------------------------------------------------===//
529
530Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000531 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000532 LValue LV = EmitLValue(E->getSubExpr());
533 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000534 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000535 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000536
537 int AmountVal = isInc ? 1 : -1;
538
539 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000540 if (isa<llvm::PointerType>(InVal->getType())) {
541 // FIXME: This isn't right for VLAs.
542 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
543 NextVal = Builder.CreateGEP(InVal, NextVal);
544 } else {
545 // Add the inc/dec to the real part.
546 if (isa<llvm::IntegerType>(InVal->getType()))
547 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000548 else if (InVal->getType() == llvm::Type::FloatTy)
549 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000550 NextVal =
551 llvm::ConstantFP::get(InVal->getType(),
552 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000553 else {
554 // FIXME: Handle long double.
555 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000556 NextVal =
557 llvm::ConstantFP::get(InVal->getType(),
558 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000559 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000560 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
561 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000562
563 // Store the updated result through the lvalue.
564 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
565 E->getSubExpr()->getType());
566
567 // If this is a postinc, return the value read from memory, otherwise use the
568 // updated value.
569 return isPre ? NextVal : InVal;
570}
571
572
573Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
574 Value *Op = Visit(E->getSubExpr());
575 return Builder.CreateNeg(Op, "neg");
576}
577
578Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
579 Value *Op = Visit(E->getSubExpr());
580 return Builder.CreateNot(Op, "neg");
581}
582
583Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
584 // Compare operand to zero.
585 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
586
587 // Invert value.
588 // TODO: Could dynamically modify easy computations here. For example, if
589 // the operand is an icmp ne, turn into icmp eq.
590 BoolVal = Builder.CreateNot(BoolVal, "lnot");
591
592 // ZExt result to int.
593 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
594}
595
596/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
597/// an integer (RetType).
598Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000599 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000600 /// FIXME: This doesn't handle VLAs yet!
601 std::pair<uint64_t, unsigned> Info =
602 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
603
604 uint64_t Val = isSizeOf ? Info.first : Info.second;
605 Val /= 8; // Return size in bytes, not bits.
606
607 assert(RetType->isIntegerType() && "Result type must be an integer!");
608
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000609 uint32_t ResultWidth = static_cast<uint32_t>(
610 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000611 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
612}
613
Chris Lattner01211af2007-08-24 21:20:17 +0000614Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
615 Expr *Op = E->getSubExpr();
616 if (Op->getType()->isComplexType())
617 return CGF.EmitComplexExpr(Op).first;
618 return Visit(Op);
619}
620Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
621 Expr *Op = E->getSubExpr();
622 if (Op->getType()->isComplexType())
623 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000624
625 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
626 // effects are evaluated.
627 CGF.EmitScalarExpr(Op);
628 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000629}
630
631
Chris Lattner9fba49a2007-08-24 05:35:26 +0000632//===----------------------------------------------------------------------===//
633// Binary Operators
634//===----------------------------------------------------------------------===//
635
636BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
637 BinOpInfo Result;
638 Result.LHS = Visit(E->getLHS());
639 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000640 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000641 Result.E = E;
642 return Result;
643}
644
Chris Lattner0d965302007-08-26 21:41:21 +0000645Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000646 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
647 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
648
649 BinOpInfo OpInfo;
650
651 // Load the LHS and RHS operands.
652 LValue LHSLV = EmitLValue(E->getLHS());
653 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000654
655 // Determine the computation type. If the RHS is complex, then this is one of
656 // the add/sub/mul/div operators. All of these operators can be computed in
657 // with just their real component even though the computation domain really is
658 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000659 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000660
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000661 // If the computation type is complex, then the RHS is complex. Emit the RHS.
662 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
663 ComputeType = CT->getElementType();
664
665 // Emit the RHS, only keeping the real component.
666 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
667 RHSTy = RHSTy->getAsComplexType()->getElementType();
668 } else {
669 // Otherwise the RHS is a simple scalar value.
670 OpInfo.RHS = Visit(E->getRHS());
671 }
672
673 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000674 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000675
Devang Patel04011802007-10-25 22:19:13 +0000676 // Do not merge types for -= or += where the LHS is a pointer.
677 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000678 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000679 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000680 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000681 }
682 OpInfo.Ty = ComputeType;
683 OpInfo.E = E;
684
685 // Expand the binary operator.
686 Value *Result = (this->*Func)(OpInfo);
687
688 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000689 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000690
691 // Store the result value into the LHS lvalue.
692 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
693
694 return Result;
695}
696
697
Chris Lattner9fba49a2007-08-24 05:35:26 +0000698Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000699 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000700 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000701 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000702 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
703 else
704 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
705}
706
707Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
708 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000709 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000710 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
711 else
712 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
713}
714
715
716Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000717 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000718 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000719
720 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000721 Value *Ptr, *Idx;
722 Expr *IdxExp;
723 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
724 Ptr = Ops.LHS;
725 Idx = Ops.RHS;
726 IdxExp = Ops.E->getRHS();
727 } else { // int + pointer
728 Ptr = Ops.RHS;
729 Idx = Ops.LHS;
730 IdxExp = Ops.E->getLHS();
731 }
732
733 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
734 if (Width < CGF.LLVMPointerWidth) {
735 // Zero or sign extend the pointer value based on whether the index is
736 // signed or not.
737 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
738 if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
739 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
740 else
741 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
742 }
743
744 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000745}
746
747Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
748 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
749 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
750
Chris Lattner660e31d2007-08-24 21:00:35 +0000751 // pointer - int
752 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
753 "ptr-ptr shouldn't get here");
754 // FIXME: The pointer could point to a VLA.
755 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
756 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
757}
758
759Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
760 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
761 // the compound assignment case it is invalid, so just handle it here.
762 if (!E->getRHS()->getType()->isPointerType())
763 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000764
765 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000766 Value *LHS = Visit(E->getLHS());
767 Value *RHS = Visit(E->getRHS());
768
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000769 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
Seo Sanghyeona570d312007-12-26 05:21:37 +0000770 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000771 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
772 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000773
774 const llvm::Type *ResultType = ConvertType(E->getType());
775 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
776 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
777 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000778
779 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
780 // remainder. As such, we handle common power-of-two cases here to generate
781 // better code.
782 if (llvm::isPowerOf2_64(ElementSize)) {
783 Value *ShAmt =
784 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
785 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
786 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000787
Chris Lattner9fba49a2007-08-24 05:35:26 +0000788 // Otherwise, do a full sdiv.
789 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
790 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
791}
792
Chris Lattner660e31d2007-08-24 21:00:35 +0000793
Chris Lattner9fba49a2007-08-24 05:35:26 +0000794Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
795 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
796 // RHS to the same size as the LHS.
797 Value *RHS = Ops.RHS;
798 if (Ops.LHS->getType() != RHS->getType())
799 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
800
801 return Builder.CreateShl(Ops.LHS, RHS, "shl");
802}
803
804Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
805 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
806 // RHS to the same size as the LHS.
807 Value *RHS = Ops.RHS;
808 if (Ops.LHS->getType() != RHS->getType())
809 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
810
Chris Lattner660e31d2007-08-24 21:00:35 +0000811 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000812 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
813 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
814}
815
816Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
817 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000818 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000819 QualType LHSTy = E->getLHS()->getType();
820 if (!LHSTy->isComplexType()) {
821 Value *LHS = Visit(E->getLHS());
822 Value *RHS = Visit(E->getRHS());
823
824 if (LHS->getType()->isFloatingPoint()) {
825 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
826 LHS, RHS, "cmp");
827 } else if (LHSTy->isUnsignedIntegerType()) {
828 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
829 LHS, RHS, "cmp");
830 } else {
831 // Signed integers and pointers.
832 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
833 LHS, RHS, "cmp");
834 }
835 } else {
836 // Complex Comparison: can only be an equality comparison.
837 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
838 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
839
840 QualType CETy =
841 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
842
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000843 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000844 if (CETy->isRealFloatingType()) {
845 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
846 LHS.first, RHS.first, "cmp.r");
847 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
848 LHS.second, RHS.second, "cmp.i");
849 } else {
850 // Complex comparisons can only be equality comparisons. As such, signed
851 // and unsigned opcodes are the same.
852 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
853 LHS.first, RHS.first, "cmp.r");
854 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
855 LHS.second, RHS.second, "cmp.i");
856 }
857
858 if (E->getOpcode() == BinaryOperator::EQ) {
859 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
860 } else {
861 assert(E->getOpcode() == BinaryOperator::NE &&
862 "Complex comparison other than == or != ?");
863 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
864 }
865 }
866
867 // ZExt result to int.
868 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
869}
870
871Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
872 LValue LHS = EmitLValue(E->getLHS());
873 Value *RHS = Visit(E->getRHS());
874
875 // Store the value into the LHS.
876 // FIXME: Volatility!
877 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
878
879 // Return the RHS.
880 return RHS;
881}
882
883Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
884 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
885
886 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
887 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
888
889 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
890 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
891
892 CGF.EmitBlock(RHSBlock);
893 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
894
895 // Reaquire the RHS block, as there may be subblocks inserted.
896 RHSBlock = Builder.GetInsertBlock();
897 CGF.EmitBlock(ContBlock);
898
899 // Create a PHI node. If we just evaluted the LHS condition, the result is
900 // false. If we evaluated both, the result is the RHS condition.
901 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
902 PN->reserveOperandSpace(2);
903 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
904 PN->addIncoming(RHSCond, RHSBlock);
905
906 // ZExt result to int.
907 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
908}
909
910Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
911 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
912
913 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
914 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
915
916 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
917 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
918
919 CGF.EmitBlock(RHSBlock);
920 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
921
922 // Reaquire the RHS block, as there may be subblocks inserted.
923 RHSBlock = Builder.GetInsertBlock();
924 CGF.EmitBlock(ContBlock);
925
926 // Create a PHI node. If we just evaluted the LHS condition, the result is
927 // true. If we evaluated both, the result is the RHS condition.
928 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
929 PN->reserveOperandSpace(2);
930 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
931 PN->addIncoming(RHSCond, RHSBlock);
932
933 // ZExt result to int.
934 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
935}
936
937Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
938 CGF.EmitStmt(E->getLHS());
939 return Visit(E->getRHS());
940}
941
942//===----------------------------------------------------------------------===//
943// Other Operators
944//===----------------------------------------------------------------------===//
945
946Value *ScalarExprEmitter::
947VisitConditionalOperator(const ConditionalOperator *E) {
948 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
949 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
950 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
951
Chris Lattner98a425c2007-11-26 01:40:58 +0000952 // Evaluate the conditional, then convert it to bool. We do this explicitly
953 // because we need the unconverted value if this is a GNU ?: expression with
954 // missing middle value.
955 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +0000956 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
957 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +0000958 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000959
960 CGF.EmitBlock(LHSBlock);
961
962 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +0000963 Value *LHS;
964 if (E->getLHS())
965 LHS = Visit(E->getLHS());
966 else // Perform promotions, to handle cases like "short ?: int"
967 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
968
Chris Lattner9fba49a2007-08-24 05:35:26 +0000969 Builder.CreateBr(ContBlock);
970 LHSBlock = Builder.GetInsertBlock();
971
972 CGF.EmitBlock(RHSBlock);
973
974 Value *RHS = Visit(E->getRHS());
975 Builder.CreateBr(ContBlock);
976 RHSBlock = Builder.GetInsertBlock();
977
978 CGF.EmitBlock(ContBlock);
979
Chris Lattner307da022007-11-30 17:56:23 +0000980 if (!LHS) {
981 assert(E->getType()->isVoidType() && "Non-void value should have a value");
982 return 0;
983 }
984
Chris Lattner9fba49a2007-08-24 05:35:26 +0000985 // Create a PHI node for the real part.
986 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
987 PN->reserveOperandSpace(2);
988 PN->addIncoming(LHS, LHSBlock);
989 PN->addIncoming(RHS, RHSBlock);
990 return PN;
991}
992
993Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000994 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000995 return
996 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000997}
998
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000999Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
1000 return CGF.EmitCallExpr(E->getFn(), E->arg_begin()).getScalarVal();
1001}
1002
Chris Lattner307da022007-11-30 17:56:23 +00001003Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001004 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1005
1006 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1007 return V;
1008}
1009
Chris Lattner307da022007-11-30 17:56:23 +00001010Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001011 std::string str;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001012 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1013 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1014 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001015
1016 llvm::Constant *C = llvm::ConstantArray::get(str);
1017 C = new llvm::GlobalVariable(C->getType(), true,
1018 llvm::GlobalValue::InternalLinkage,
1019 C, ".str", &CGF.CGM.getModule());
1020 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1021 llvm::Constant *Zeros[] = { Zero, Zero };
1022 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1023
1024 return C;
1025}
1026
Chris Lattner9fba49a2007-08-24 05:35:26 +00001027//===----------------------------------------------------------------------===//
1028// Entry Point into this File
1029//===----------------------------------------------------------------------===//
1030
1031/// EmitComplexExpr - Emit the computation of the specified expression of
1032/// complex type, ignoring the result.
1033Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1034 assert(E && !hasAggregateLLVMType(E->getType()) &&
1035 "Invalid scalar expression to emit");
1036
1037 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1038}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001039
1040/// EmitScalarConversion - Emit a conversion from the specified type to the
1041/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001042Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1043 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001044 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1045 "Invalid scalar expression to emit");
1046 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1047}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001048
1049/// EmitComplexToScalarConversion - Emit a conversion from the specified
1050/// complex type to the specified destination type, where the destination
1051/// type is an LLVM scalar type.
1052Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1053 QualType SrcTy,
1054 QualType DstTy) {
1055 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1056 "Invalid complex -> scalar conversion");
1057 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1058 DstTy);
1059}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001060
1061Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1062 assert(V1->getType() == V2->getType() &&
1063 "Vector operands must be of the same type");
1064
1065 unsigned NumElements =
1066 cast<llvm::VectorType>(V1->getType())->getNumElements();
1067
1068 va_list va;
1069 va_start(va, V2);
1070
1071 llvm::SmallVector<llvm::Constant*, 16> Args;
1072
1073 for (unsigned i = 0; i < NumElements; i++) {
1074 int n = va_arg(va, int);
1075
1076 assert(n >= 0 && n < (int)NumElements * 2 &&
1077 "Vector shuffle index out of bounds!");
1078
1079 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1080 }
1081
1082 const char *Name = va_arg(va, const char *);
1083 va_end(va);
1084
1085 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1086
1087 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1088}
1089
Anders Carlsson68b8be92007-12-15 21:23:30 +00001090llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Nate Begemanec2d1062007-12-30 02:59:45 +00001091 unsigned NumVals, bool isSplat)
Anders Carlsson68b8be92007-12-15 21:23:30 +00001092{
Anders Carlsson68b8be92007-12-15 21:23:30 +00001093 llvm::Value *Vec
1094 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1095
1096 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001097 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001098 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001099 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001100 }
1101
1102 return Vec;
1103}