blob: e1771e80f855e9471674615499add2c527fb7258 [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 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000216 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
217
Chris Lattner9fba49a2007-08-24 05:35:26 +0000218 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000219 Value *EmitMul(const BinOpInfo &Ops) {
220 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
221 }
222 Value *EmitDiv(const BinOpInfo &Ops);
223 Value *EmitRem(const BinOpInfo &Ops);
224 Value *EmitAdd(const BinOpInfo &Ops);
225 Value *EmitSub(const BinOpInfo &Ops);
226 Value *EmitShl(const BinOpInfo &Ops);
227 Value *EmitShr(const BinOpInfo &Ops);
228 Value *EmitAnd(const BinOpInfo &Ops) {
229 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
230 }
231 Value *EmitXor(const BinOpInfo &Ops) {
232 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
233 }
234 Value *EmitOr (const BinOpInfo &Ops) {
235 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
236 }
237
Chris Lattner660e31d2007-08-24 21:00:35 +0000238 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000239 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000240 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
241
242 // Binary operators and binary compound assignment operators.
243#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000244 Value *VisitBin ## OP(const BinaryOperator *E) { \
245 return Emit ## OP(EmitBinOps(E)); \
246 } \
247 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
248 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000249 }
250 HANDLEBINOP(Mul);
251 HANDLEBINOP(Div);
252 HANDLEBINOP(Rem);
253 HANDLEBINOP(Add);
254 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
255 HANDLEBINOP(Shl);
256 HANDLEBINOP(Shr);
257 HANDLEBINOP(And);
258 HANDLEBINOP(Xor);
259 HANDLEBINOP(Or);
260#undef HANDLEBINOP
261 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000262 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000263 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
264 }
265
Chris Lattner9fba49a2007-08-24 05:35:26 +0000266 // Comparisons.
267 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
268 unsigned SICmpOpc, unsigned FCmpOpc);
269#define VISITCOMP(CODE, UI, SI, FP) \
270 Value *VisitBin##CODE(const BinaryOperator *E) { \
271 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
272 llvm::FCmpInst::FP); }
273 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
274 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
275 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
276 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
277 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
278 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
279#undef VISITCOMP
280
281 Value *VisitBinAssign (const BinaryOperator *E);
282
283 Value *VisitBinLAnd (const BinaryOperator *E);
284 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000285 Value *VisitBinComma (const BinaryOperator *E);
286
287 // Other Operators.
288 Value *VisitConditionalOperator(const ConditionalOperator *CO);
289 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000290 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000291 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000292 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
293 return CGF.EmitObjCStringLiteral(E);
294 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000295 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000296};
297} // end anonymous namespace.
298
299//===----------------------------------------------------------------------===//
300// Utilities
301//===----------------------------------------------------------------------===//
302
Chris Lattnerd8d44222007-08-26 16:42:57 +0000303/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000304/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000305Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
306 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
307
308 if (SrcType->isRealFloatingType()) {
309 // Compare against 0.0 for fp scalars.
310 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000311 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
312 }
313
314 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
315 "Unknown scalar type to convert");
316
317 // Because of the type rules of C, we often end up computing a logical value,
318 // then zero extending it to int, then wanting it as a logical value again.
319 // Optimize this common case.
320 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
321 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
322 Value *Result = ZI->getOperand(0);
323 ZI->eraseFromParent();
324 return Result;
325 }
326 }
327
328 // Compare against an integer or pointer null.
329 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
330 return Builder.CreateICmpNE(Src, Zero, "tobool");
331}
332
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000333/// EmitScalarConversion - Emit a conversion from the specified type to the
334/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000335Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
336 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000337 SrcType = SrcType.getCanonicalType();
338 DstType = DstType.getCanonicalType();
339 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000340
341 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000342
343 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000344 if (DstType->isBooleanType())
345 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000346
347 const llvm::Type *DstTy = ConvertType(DstType);
348
349 // Ignore conversions like int -> uint.
350 if (Src->getType() == DstTy)
351 return Src;
352
353 // Handle pointer conversions next: pointers can only be converted to/from
354 // other pointers and integers.
355 if (isa<PointerType>(DstType)) {
356 // The source value may be an integer, or a pointer.
357 if (isa<llvm::PointerType>(Src->getType()))
358 return Builder.CreateBitCast(Src, DstTy, "conv");
359 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
360 return Builder.CreateIntToPtr(Src, DstTy, "conv");
361 }
362
363 if (isa<PointerType>(SrcType)) {
364 // Must be an ptr to int cast.
365 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000366 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000367 }
368
Nate Begemanec2d1062007-12-30 02:59:45 +0000369 // A scalar source can be splatted to a vector of the same element type
370 if (isa<llvm::VectorType>(DstTy) && !isa<VectorType>(SrcType)) {
371 const llvm::VectorType *VT = cast<llvm::VectorType>(DstTy);
372 assert((VT->getElementType() == Src->getType()) &&
373 "Vector element type must match scalar type to splat.");
374 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
375 true);
376 }
377
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000378 if (isa<llvm::VectorType>(Src->getType()) ||
379 isa<llvm::VectorType>(DstTy)) {
380 return Builder.CreateBitCast(Src, DstTy, "conv");
381 }
382
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000383 // Finally, we have the arithmetic types: real int/float.
384 if (isa<llvm::IntegerType>(Src->getType())) {
385 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000386 if (isa<llvm::IntegerType>(DstTy))
387 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
388 else if (InputSigned)
389 return Builder.CreateSIToFP(Src, DstTy, "conv");
390 else
391 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000392 }
393
394 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
395 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000396 if (DstType->isSignedIntegerType())
397 return Builder.CreateFPToSI(Src, DstTy, "conv");
398 else
399 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000400 }
401
402 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000403 if (DstTy->getTypeID() < Src->getType()->getTypeID())
404 return Builder.CreateFPTrunc(Src, DstTy, "conv");
405 else
406 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000407}
408
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000409/// EmitComplexToScalarConversion - Emit a conversion from the specified
410/// complex type to the specified destination type, where the destination
411/// type is an LLVM scalar type.
412Value *ScalarExprEmitter::
413EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
414 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000415 // Get the source element type.
416 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
417
418 // Handle conversions to bool first, they are special: comparisons against 0.
419 if (DstTy->isBooleanType()) {
420 // Complex != 0 -> (Real != 0) | (Imag != 0)
421 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
422 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
423 return Builder.CreateOr(Src.first, Src.second, "tobool");
424 }
425
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000426 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
427 // the imaginary part of the complex value is discarded and the value of the
428 // real part is converted according to the conversion rules for the
429 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000430 return EmitScalarConversion(Src.first, SrcTy, DstTy);
431}
432
433
Chris Lattner9fba49a2007-08-24 05:35:26 +0000434//===----------------------------------------------------------------------===//
435// Visitor Methods
436//===----------------------------------------------------------------------===//
437
438Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000439 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000440 if (E->getType()->isVoidType())
441 return 0;
442 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
443}
444
445Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
446 // Emit subscript expressions in rvalue context's. For most cases, this just
447 // loads the lvalue formed by the subscript expr. However, we have to be
448 // careful, because the base of a vector subscript is occasionally an rvalue,
449 // so we can't get it as an lvalue.
450 if (!E->getBase()->getType()->isVectorType())
451 return EmitLoadOfLValue(E);
452
453 // Handle the vector case. The base must be a vector, the index must be an
454 // integer value.
455 Value *Base = Visit(E->getBase());
456 Value *Idx = Visit(E->getIdx());
457
458 // FIXME: Convert Idx to i32 type.
459 return Builder.CreateExtractElement(Base, Idx, "vecext");
460}
461
462/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
463/// also handle things like function to pointer-to-function decay, and array to
464/// pointer decay.
465Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
466 const Expr *Op = E->getSubExpr();
467
468 // If this is due to array->pointer conversion, emit the array expression as
469 // an l-value.
470 if (Op->getType()->isArrayType()) {
471 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
472 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000473 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000474
475 assert(isa<llvm::PointerType>(V->getType()) &&
476 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
477 ->getElementType()) &&
478 "Doesn't support VLAs yet!");
479 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000480
481 llvm::Value *Ops[] = {Idx0, Idx0};
Chris Lattnere54443b2007-12-12 04:13:20 +0000482 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
483
484 // The resultant pointer type can be implicitly casted to other pointer
485 // types as well, for example void*.
486 const llvm::Type *DestPTy = ConvertType(E->getType());
487 assert(isa<llvm::PointerType>(DestPTy) &&
488 "Only expect implicit cast to pointer");
489 if (V->getType() != DestPTy)
490 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
491 return V;
492
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000493 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000494 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
495 getReferenceeType() ==
496 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000497
498 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000499 }
500
501 return EmitCastExpr(Op, E->getType());
502}
503
504
505// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
506// have to handle a more broad range of conversions than explicit casts, as they
507// handle things like function to ptr-to-function decay etc.
508Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000509 // Handle cases where the source is an non-complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000510 if (!E->getType()->isComplexType()) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000511 Value *Src = Visit(const_cast<Expr*>(E));
512
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000513 // Use EmitScalarConversion to perform the conversion.
514 return EmitScalarConversion(Src, E->getType(), DestTy);
515 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000516
Chris Lattner82e10392007-08-26 07:26:12 +0000517 // Handle cases where the source is a complex type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000518 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
519 DestTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000520}
521
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000522Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000523 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000524}
525
526
Chris Lattner9fba49a2007-08-24 05:35:26 +0000527//===----------------------------------------------------------------------===//
528// Unary Operators
529//===----------------------------------------------------------------------===//
530
531Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000532 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000533 LValue LV = EmitLValue(E->getSubExpr());
534 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000535 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000536 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000537
538 int AmountVal = isInc ? 1 : -1;
539
540 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000541 if (isa<llvm::PointerType>(InVal->getType())) {
542 // FIXME: This isn't right for VLAs.
543 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
544 NextVal = Builder.CreateGEP(InVal, NextVal);
545 } else {
546 // Add the inc/dec to the real part.
547 if (isa<llvm::IntegerType>(InVal->getType()))
548 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000549 else if (InVal->getType() == llvm::Type::FloatTy)
550 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000551 NextVal =
552 llvm::ConstantFP::get(InVal->getType(),
553 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000554 else {
555 // FIXME: Handle long double.
556 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000557 NextVal =
558 llvm::ConstantFP::get(InVal->getType(),
559 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000560 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000561 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
562 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000563
564 // Store the updated result through the lvalue.
565 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
566 E->getSubExpr()->getType());
567
568 // If this is a postinc, return the value read from memory, otherwise use the
569 // updated value.
570 return isPre ? NextVal : InVal;
571}
572
573
574Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
575 Value *Op = Visit(E->getSubExpr());
576 return Builder.CreateNeg(Op, "neg");
577}
578
579Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
580 Value *Op = Visit(E->getSubExpr());
581 return Builder.CreateNot(Op, "neg");
582}
583
584Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
585 // Compare operand to zero.
586 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
587
588 // Invert value.
589 // TODO: Could dynamically modify easy computations here. For example, if
590 // the operand is an icmp ne, turn into icmp eq.
591 BoolVal = Builder.CreateNot(BoolVal, "lnot");
592
593 // ZExt result to int.
594 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
595}
596
597/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
598/// an integer (RetType).
599Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000600 QualType RetType,bool isSizeOf){
Chris Lattner9fba49a2007-08-24 05:35:26 +0000601 /// FIXME: This doesn't handle VLAs yet!
602 std::pair<uint64_t, unsigned> Info =
603 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
604
605 uint64_t Val = isSizeOf ? Info.first : Info.second;
606 Val /= 8; // Return size in bytes, not bits.
607
608 assert(RetType->isIntegerType() && "Result type must be an integer!");
609
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000610 uint32_t ResultWidth = static_cast<uint32_t>(
611 CGF.getContext().getTypeSize(RetType, SourceLocation()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000612 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
613}
614
Chris Lattner01211af2007-08-24 21:20:17 +0000615Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
616 Expr *Op = E->getSubExpr();
617 if (Op->getType()->isComplexType())
618 return CGF.EmitComplexExpr(Op).first;
619 return Visit(Op);
620}
621Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
622 Expr *Op = E->getSubExpr();
623 if (Op->getType()->isComplexType())
624 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000625
626 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
627 // effects are evaluated.
628 CGF.EmitScalarExpr(Op);
629 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000630}
631
Anders Carlsson52774ad2008-01-29 15:56:48 +0000632Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
633{
634 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
635
636 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
637
638 uint32_t ResultWidth = static_cast<uint32_t>(
639 CGF.getContext().getTypeSize(E->getType(), SourceLocation()));
640 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
641}
Chris Lattner01211af2007-08-24 21:20:17 +0000642
Chris Lattner9fba49a2007-08-24 05:35:26 +0000643//===----------------------------------------------------------------------===//
644// Binary Operators
645//===----------------------------------------------------------------------===//
646
647BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
648 BinOpInfo Result;
649 Result.LHS = Visit(E->getLHS());
650 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000651 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000652 Result.E = E;
653 return Result;
654}
655
Chris Lattner0d965302007-08-26 21:41:21 +0000656Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000657 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
658 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
659
660 BinOpInfo OpInfo;
661
662 // Load the LHS and RHS operands.
663 LValue LHSLV = EmitLValue(E->getLHS());
664 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000665
666 // Determine the computation type. If the RHS is complex, then this is one of
667 // the add/sub/mul/div operators. All of these operators can be computed in
668 // with just their real component even though the computation domain really is
669 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000670 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000671
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000672 // If the computation type is complex, then the RHS is complex. Emit the RHS.
673 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
674 ComputeType = CT->getElementType();
675
676 // Emit the RHS, only keeping the real component.
677 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
678 RHSTy = RHSTy->getAsComplexType()->getElementType();
679 } else {
680 // Otherwise the RHS is a simple scalar value.
681 OpInfo.RHS = Visit(E->getRHS());
682 }
683
684 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000685 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000686
Devang Patel04011802007-10-25 22:19:13 +0000687 // Do not merge types for -= or += where the LHS is a pointer.
688 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000689 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000690 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000691 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000692 }
693 OpInfo.Ty = ComputeType;
694 OpInfo.E = E;
695
696 // Expand the binary operator.
697 Value *Result = (this->*Func)(OpInfo);
698
699 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000700 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000701
702 // Store the result value into the LHS lvalue.
703 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
704
705 return Result;
706}
707
708
Chris Lattner9fba49a2007-08-24 05:35:26 +0000709Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000710 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000711 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000712 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000713 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
714 else
715 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
716}
717
718Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
719 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000720 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000721 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
722 else
723 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
724}
725
726
727Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000728 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000729 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000730
731 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000732 Value *Ptr, *Idx;
733 Expr *IdxExp;
734 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
735 Ptr = Ops.LHS;
736 Idx = Ops.RHS;
737 IdxExp = Ops.E->getRHS();
738 } else { // int + pointer
739 Ptr = Ops.RHS;
740 Idx = Ops.LHS;
741 IdxExp = Ops.E->getLHS();
742 }
743
744 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
745 if (Width < CGF.LLVMPointerWidth) {
746 // Zero or sign extend the pointer value based on whether the index is
747 // signed or not.
748 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
749 if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
750 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
751 else
752 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
753 }
754
755 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000756}
757
758Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
759 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
760 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
761
Chris Lattner660e31d2007-08-24 21:00:35 +0000762 // pointer - int
763 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
764 "ptr-ptr shouldn't get here");
765 // FIXME: The pointer could point to a VLA.
766 Value *NegatedRHS = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
767 return Builder.CreateGEP(Ops.LHS, NegatedRHS, "sub.ptr");
768}
769
770Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
771 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
772 // the compound assignment case it is invalid, so just handle it here.
773 if (!E->getRHS()->getType()->isPointerType())
774 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000775
776 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000777 Value *LHS = Visit(E->getLHS());
778 Value *RHS = Visit(E->getRHS());
779
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000780 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
Seo Sanghyeona570d312007-12-26 05:21:37 +0000781 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000782 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
783 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000784
785 const llvm::Type *ResultType = ConvertType(E->getType());
786 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
787 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
788 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000789
790 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
791 // remainder. As such, we handle common power-of-two cases here to generate
792 // better code.
793 if (llvm::isPowerOf2_64(ElementSize)) {
794 Value *ShAmt =
795 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
796 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
797 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000798
Chris Lattner9fba49a2007-08-24 05:35:26 +0000799 // Otherwise, do a full sdiv.
800 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
801 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
802}
803
Chris Lattner660e31d2007-08-24 21:00:35 +0000804
Chris Lattner9fba49a2007-08-24 05:35:26 +0000805Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
806 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
807 // RHS to the same size as the LHS.
808 Value *RHS = Ops.RHS;
809 if (Ops.LHS->getType() != RHS->getType())
810 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
811
812 return Builder.CreateShl(Ops.LHS, RHS, "shl");
813}
814
815Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
816 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
817 // RHS to the same size as the LHS.
818 Value *RHS = Ops.RHS;
819 if (Ops.LHS->getType() != RHS->getType())
820 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
821
Chris Lattner660e31d2007-08-24 21:00:35 +0000822 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000823 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
824 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
825}
826
827Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
828 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000829 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000830 QualType LHSTy = E->getLHS()->getType();
831 if (!LHSTy->isComplexType()) {
832 Value *LHS = Visit(E->getLHS());
833 Value *RHS = Visit(E->getRHS());
834
835 if (LHS->getType()->isFloatingPoint()) {
836 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
837 LHS, RHS, "cmp");
838 } else if (LHSTy->isUnsignedIntegerType()) {
839 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
840 LHS, RHS, "cmp");
841 } else {
842 // Signed integers and pointers.
843 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
844 LHS, RHS, "cmp");
845 }
846 } else {
847 // Complex Comparison: can only be an equality comparison.
848 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
849 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
850
851 QualType CETy =
852 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
853
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000854 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000855 if (CETy->isRealFloatingType()) {
856 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
857 LHS.first, RHS.first, "cmp.r");
858 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
859 LHS.second, RHS.second, "cmp.i");
860 } else {
861 // Complex comparisons can only be equality comparisons. As such, signed
862 // and unsigned opcodes are the same.
863 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
864 LHS.first, RHS.first, "cmp.r");
865 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
866 LHS.second, RHS.second, "cmp.i");
867 }
868
869 if (E->getOpcode() == BinaryOperator::EQ) {
870 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
871 } else {
872 assert(E->getOpcode() == BinaryOperator::NE &&
873 "Complex comparison other than == or != ?");
874 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
875 }
876 }
877
878 // ZExt result to int.
879 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
880}
881
882Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
883 LValue LHS = EmitLValue(E->getLHS());
884 Value *RHS = Visit(E->getRHS());
885
886 // Store the value into the LHS.
887 // FIXME: Volatility!
888 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
889
890 // Return the RHS.
891 return RHS;
892}
893
894Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
895 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
896
897 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
898 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
899
900 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
901 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
902
903 CGF.EmitBlock(RHSBlock);
904 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
905
906 // Reaquire the RHS block, as there may be subblocks inserted.
907 RHSBlock = Builder.GetInsertBlock();
908 CGF.EmitBlock(ContBlock);
909
910 // Create a PHI node. If we just evaluted the LHS condition, the result is
911 // false. If we evaluated both, the result is the RHS condition.
912 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
913 PN->reserveOperandSpace(2);
914 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
915 PN->addIncoming(RHSCond, RHSBlock);
916
917 // ZExt result to int.
918 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
919}
920
921Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
922 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
923
924 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
925 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
926
927 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
928 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
929
930 CGF.EmitBlock(RHSBlock);
931 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
932
933 // Reaquire the RHS block, as there may be subblocks inserted.
934 RHSBlock = Builder.GetInsertBlock();
935 CGF.EmitBlock(ContBlock);
936
937 // Create a PHI node. If we just evaluted the LHS condition, the result is
938 // true. If we evaluated both, the result is the RHS condition.
939 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
940 PN->reserveOperandSpace(2);
941 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
942 PN->addIncoming(RHSCond, RHSBlock);
943
944 // ZExt result to int.
945 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
946}
947
948Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
949 CGF.EmitStmt(E->getLHS());
950 return Visit(E->getRHS());
951}
952
953//===----------------------------------------------------------------------===//
954// Other Operators
955//===----------------------------------------------------------------------===//
956
957Value *ScalarExprEmitter::
958VisitConditionalOperator(const ConditionalOperator *E) {
959 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
960 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
961 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
962
Chris Lattner98a425c2007-11-26 01:40:58 +0000963 // Evaluate the conditional, then convert it to bool. We do this explicitly
964 // because we need the unconverted value if this is a GNU ?: expression with
965 // missing middle value.
966 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +0000967 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
968 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +0000969 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000970
971 CGF.EmitBlock(LHSBlock);
972
973 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +0000974 Value *LHS;
975 if (E->getLHS())
976 LHS = Visit(E->getLHS());
977 else // Perform promotions, to handle cases like "short ?: int"
978 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
979
Chris Lattner9fba49a2007-08-24 05:35:26 +0000980 Builder.CreateBr(ContBlock);
981 LHSBlock = Builder.GetInsertBlock();
982
983 CGF.EmitBlock(RHSBlock);
984
985 Value *RHS = Visit(E->getRHS());
986 Builder.CreateBr(ContBlock);
987 RHSBlock = Builder.GetInsertBlock();
988
989 CGF.EmitBlock(ContBlock);
990
Chris Lattner307da022007-11-30 17:56:23 +0000991 if (!LHS) {
992 assert(E->getType()->isVoidType() && "Non-void value should have a value");
993 return 0;
994 }
995
Chris Lattner9fba49a2007-08-24 05:35:26 +0000996 // Create a PHI node for the real part.
997 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
998 PN->reserveOperandSpace(2);
999 PN->addIncoming(LHS, LHSBlock);
1000 PN->addIncoming(RHS, RHSBlock);
1001 return PN;
1002}
1003
1004Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001005 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001006 return
1007 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001008}
1009
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001010Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
1011 return CGF.EmitCallExpr(E->getFn(), E->arg_begin()).getScalarVal();
1012}
1013
Chris Lattner307da022007-11-30 17:56:23 +00001014Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001015 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1016
1017 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1018 return V;
1019}
1020
Chris Lattner307da022007-11-30 17:56:23 +00001021Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001022 std::string str;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001023 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1024 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1025 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001026
1027 llvm::Constant *C = llvm::ConstantArray::get(str);
1028 C = new llvm::GlobalVariable(C->getType(), true,
1029 llvm::GlobalValue::InternalLinkage,
1030 C, ".str", &CGF.CGM.getModule());
1031 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1032 llvm::Constant *Zeros[] = { Zero, Zero };
1033 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1034
1035 return C;
1036}
1037
Chris Lattner9fba49a2007-08-24 05:35:26 +00001038//===----------------------------------------------------------------------===//
1039// Entry Point into this File
1040//===----------------------------------------------------------------------===//
1041
1042/// EmitComplexExpr - Emit the computation of the specified expression of
1043/// complex type, ignoring the result.
1044Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1045 assert(E && !hasAggregateLLVMType(E->getType()) &&
1046 "Invalid scalar expression to emit");
1047
1048 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1049}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001050
1051/// EmitScalarConversion - Emit a conversion from the specified type to the
1052/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001053Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1054 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001055 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1056 "Invalid scalar expression to emit");
1057 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1058}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001059
1060/// EmitComplexToScalarConversion - Emit a conversion from the specified
1061/// complex type to the specified destination type, where the destination
1062/// type is an LLVM scalar type.
1063Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1064 QualType SrcTy,
1065 QualType DstTy) {
1066 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1067 "Invalid complex -> scalar conversion");
1068 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1069 DstTy);
1070}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001071
1072Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1073 assert(V1->getType() == V2->getType() &&
1074 "Vector operands must be of the same type");
1075
1076 unsigned NumElements =
1077 cast<llvm::VectorType>(V1->getType())->getNumElements();
1078
1079 va_list va;
1080 va_start(va, V2);
1081
1082 llvm::SmallVector<llvm::Constant*, 16> Args;
1083
1084 for (unsigned i = 0; i < NumElements; i++) {
1085 int n = va_arg(va, int);
1086
1087 assert(n >= 0 && n < (int)NumElements * 2 &&
1088 "Vector shuffle index out of bounds!");
1089
1090 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1091 }
1092
1093 const char *Name = va_arg(va, const char *);
1094 va_end(va);
1095
1096 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1097
1098 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1099}
1100
Anders Carlsson68b8be92007-12-15 21:23:30 +00001101llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Nate Begemanec2d1062007-12-30 02:59:45 +00001102 unsigned NumVals, bool isSplat)
Anders Carlsson68b8be92007-12-15 21:23:30 +00001103{
Anders Carlsson68b8be92007-12-15 21:23:30 +00001104 llvm::Value *Vec
1105 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1106
1107 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001108 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001109 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001110 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001111 }
1112
1113 return Vec;
1114}