blob: 52b022b6611efcac1d5676ea2ce4116f4bb51fcf [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 Lattnercbfb5512008-03-01 08:45:05 +000044 CGObjCRuntime *Runtime;
45
46
Chris Lattner9fba49a2007-08-24 05:35:26 +000047public:
48
Chris Lattnercbfb5512008-03-01 08:45:05 +000049 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
50 Builder(CGF.Builder),
51 Runtime(CGF.CGM.getObjCRuntime()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000052 }
53
54
55 //===--------------------------------------------------------------------===//
56 // Utilities
57 //===--------------------------------------------------------------------===//
58
59 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
60 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
61
62 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000063 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000064 }
65
66 /// EmitLoadOfLValue - Given an expression with complex type that represents a
67 /// value l-value, this method emits the address of the l-value, then loads
68 /// and returns the result.
69 Value *EmitLoadOfLValue(const Expr *E) {
70 // FIXME: Volatile
71 return EmitLoadOfLValue(EmitLValue(E), E->getType());
72 }
73
Chris Lattnerd8d44222007-08-26 16:42:57 +000074 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000075 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000076 Value *EmitConversionToBool(Value *Src, QualType DstTy);
77
Chris Lattner4e05d1e2007-08-26 06:48:56 +000078 /// EmitScalarConversion - Emit a conversion from the specified type to the
79 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000080 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
81
82 /// EmitComplexToScalarConversion - Emit a conversion from the specified
83 /// complex type to the specified destination type, where the destination
84 /// type is an LLVM scalar type.
85 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
86 QualType SrcTy, QualType DstTy);
Chris Lattner4e05d1e2007-08-26 06:48:56 +000087
Chris Lattner9fba49a2007-08-24 05:35:26 +000088 //===--------------------------------------------------------------------===//
89 // Visitor Methods
90 //===--------------------------------------------------------------------===//
91
92 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000093 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000094 assert(0 && "Stmt can't have complex result type!");
95 return 0;
96 }
97 Value *VisitExpr(Expr *S);
98 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
99
100 // Leaves.
101 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
102 return llvm::ConstantInt::get(E->getValue());
103 }
104 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner7f298762007-09-22 18:47:25 +0000105 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000106 }
107 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
108 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
109 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000110 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
111 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
112 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000113 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
114 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000115 CGF.getContext().typesAreCompatible(
116 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000117 }
118 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
119 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
120 }
121
122 // l-values.
123 Value *VisitDeclRefExpr(DeclRefExpr *E) {
124 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
125 return llvm::ConstantInt::get(EC->getInitVal());
126 return EmitLoadOfLValue(E);
127 }
Chris Lattnercbfb5512008-03-01 08:45:05 +0000128 Value *VisitObjCMessageExpr(ObjCMessageExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000129 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
130 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
131 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
132 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
133 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000134
135 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000136 unsigned NumInitElements = E->getNumInits();
137
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000138 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000139 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
140
141 // We have a scalar in braces. Just use the first element.
142 if (!VType)
143 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000144
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000145 unsigned NumVectorElements = VType->getNumElements();
146 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000147
148 // Emit individual vector element stores.
149 llvm::Value *V = llvm::UndefValue::get(VType);
150
Anders Carlsson323d5682007-12-18 02:45:33 +0000151 // Emit initializers
152 unsigned i;
153 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000154 Value *NewV = Visit(E->getInit(i));
155 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
156 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000157 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000158
159 // Emit remaining default initializers
160 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
161 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
162 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
163 V = Builder.CreateInsertElement(V, NewV, Idx);
164 }
165
Devang Patel32c39832007-10-24 18:05:48 +0000166 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000167 }
168
169 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
170 return Visit(E->getInitializer());
171 }
172
Chris Lattner9fba49a2007-08-24 05:35:26 +0000173 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
174 Value *VisitCastExpr(const CastExpr *E) {
175 return EmitCastExpr(E->getSubExpr(), E->getType());
176 }
177 Value *EmitCastExpr(const Expr *E, QualType T);
178
179 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000180 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000181 }
182
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000183 Value *VisitStmtExpr(const StmtExpr *E);
184
Chris Lattner9fba49a2007-08-24 05:35:26 +0000185 // Unary Operators.
186 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
187 Value *VisitUnaryPostDec(const UnaryOperator *E) {
188 return VisitPrePostIncDec(E, false, false);
189 }
190 Value *VisitUnaryPostInc(const UnaryOperator *E) {
191 return VisitPrePostIncDec(E, true, false);
192 }
193 Value *VisitUnaryPreDec(const UnaryOperator *E) {
194 return VisitPrePostIncDec(E, false, true);
195 }
196 Value *VisitUnaryPreInc(const UnaryOperator *E) {
197 return VisitPrePostIncDec(E, true, true);
198 }
199 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
200 return EmitLValue(E->getSubExpr()).getAddress();
201 }
202 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
203 Value *VisitUnaryPlus(const UnaryOperator *E) {
204 return Visit(E->getSubExpr());
205 }
206 Value *VisitUnaryMinus (const UnaryOperator *E);
207 Value *VisitUnaryNot (const UnaryOperator *E);
208 Value *VisitUnaryLNot (const UnaryOperator *E);
209 Value *VisitUnarySizeOf (const UnaryOperator *E) {
210 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
211 }
212 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
213 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
214 }
215 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
216 bool isSizeOf);
Chris Lattner01211af2007-08-24 21:20:17 +0000217 Value *VisitUnaryReal (const UnaryOperator *E);
218 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000219 Value *VisitUnaryExtension(const UnaryOperator *E) {
220 return Visit(E->getSubExpr());
221 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000222 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
223
Chris Lattner9fba49a2007-08-24 05:35:26 +0000224 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000225 Value *EmitMul(const BinOpInfo &Ops) {
226 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
227 }
228 Value *EmitDiv(const BinOpInfo &Ops);
229 Value *EmitRem(const BinOpInfo &Ops);
230 Value *EmitAdd(const BinOpInfo &Ops);
231 Value *EmitSub(const BinOpInfo &Ops);
232 Value *EmitShl(const BinOpInfo &Ops);
233 Value *EmitShr(const BinOpInfo &Ops);
234 Value *EmitAnd(const BinOpInfo &Ops) {
235 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
236 }
237 Value *EmitXor(const BinOpInfo &Ops) {
238 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
239 }
240 Value *EmitOr (const BinOpInfo &Ops) {
241 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
242 }
243
Chris Lattner660e31d2007-08-24 21:00:35 +0000244 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000245 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000246 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
247
248 // Binary operators and binary compound assignment operators.
249#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000250 Value *VisitBin ## OP(const BinaryOperator *E) { \
251 return Emit ## OP(EmitBinOps(E)); \
252 } \
253 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
254 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000255 }
256 HANDLEBINOP(Mul);
257 HANDLEBINOP(Div);
258 HANDLEBINOP(Rem);
259 HANDLEBINOP(Add);
260 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
261 HANDLEBINOP(Shl);
262 HANDLEBINOP(Shr);
263 HANDLEBINOP(And);
264 HANDLEBINOP(Xor);
265 HANDLEBINOP(Or);
266#undef HANDLEBINOP
267 Value *VisitBinSub(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000268 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000269 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
270 }
271
Chris Lattner9fba49a2007-08-24 05:35:26 +0000272 // Comparisons.
273 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
274 unsigned SICmpOpc, unsigned FCmpOpc);
275#define VISITCOMP(CODE, UI, SI, FP) \
276 Value *VisitBin##CODE(const BinaryOperator *E) { \
277 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
278 llvm::FCmpInst::FP); }
279 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
280 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
281 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
282 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
283 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
284 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
285#undef VISITCOMP
286
287 Value *VisitBinAssign (const BinaryOperator *E);
288
289 Value *VisitBinLAnd (const BinaryOperator *E);
290 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000291 Value *VisitBinComma (const BinaryOperator *E);
292
293 // Other Operators.
294 Value *VisitConditionalOperator(const ConditionalOperator *CO);
295 Value *VisitChooseExpr(ChooseExpr *CE);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000296 Value *VisitOverloadExpr(OverloadExpr *OE);
Anders Carlsson36760332007-10-15 20:28:48 +0000297 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000298 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
299 return CGF.EmitObjCStringLiteral(E);
300 }
Anders Carlsson36f07d82007-10-29 05:01:08 +0000301 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000302};
303} // end anonymous namespace.
304
305//===----------------------------------------------------------------------===//
306// Utilities
307//===----------------------------------------------------------------------===//
308
Chris Lattnerd8d44222007-08-26 16:42:57 +0000309/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000310/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000311Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
312 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
313
314 if (SrcType->isRealFloatingType()) {
315 // Compare against 0.0 for fp scalars.
316 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000317 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
318 }
319
320 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
321 "Unknown scalar type to convert");
322
323 // Because of the type rules of C, we often end up computing a logical value,
324 // then zero extending it to int, then wanting it as a logical value again.
325 // Optimize this common case.
326 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
327 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
328 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000329 // If there aren't any more uses, zap the instruction to save space.
330 // Note that there can be more uses, for example if this
331 // is the result of an assignment.
332 if (ZI->use_empty())
333 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000334 return Result;
335 }
336 }
337
338 // Compare against an integer or pointer null.
339 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
340 return Builder.CreateICmpNE(Src, Zero, "tobool");
341}
342
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000343/// EmitScalarConversion - Emit a conversion from the specified type to the
344/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000345Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
346 QualType DstType) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000347 SrcType = SrcType.getCanonicalType();
348 DstType = DstType.getCanonicalType();
349 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000350
351 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000352
353 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000354 if (DstType->isBooleanType())
355 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000356
357 const llvm::Type *DstTy = ConvertType(DstType);
358
359 // Ignore conversions like int -> uint.
360 if (Src->getType() == DstTy)
361 return Src;
362
363 // Handle pointer conversions next: pointers can only be converted to/from
364 // other pointers and integers.
365 if (isa<PointerType>(DstType)) {
366 // The source value may be an integer, or a pointer.
367 if (isa<llvm::PointerType>(Src->getType()))
368 return Builder.CreateBitCast(Src, DstTy, "conv");
369 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
370 return Builder.CreateIntToPtr(Src, DstTy, "conv");
371 }
372
373 if (isa<PointerType>(SrcType)) {
374 // Must be an ptr to int cast.
375 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000376 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000377 }
378
Anders Carlssonaba8c572008-02-01 23:17:55 +0000379 // A scalar source can be splatted to an OCU vector of the same element type
Chris Lattner4f025a42008-02-02 04:51:41 +0000380 if (DstType->isOCUVectorType() && !isa<VectorType>(SrcType) &&
381 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
Nate Begemanec2d1062007-12-30 02:59:45 +0000382 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
383 true);
Nate Begemanec2d1062007-12-30 02:59:45 +0000384
Chris Lattner4f025a42008-02-02 04:51:41 +0000385 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000386 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000387 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000388 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000389
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000390 // Finally, we have the arithmetic types: real int/float.
391 if (isa<llvm::IntegerType>(Src->getType())) {
392 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000393 if (isa<llvm::IntegerType>(DstTy))
394 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
395 else if (InputSigned)
396 return Builder.CreateSIToFP(Src, DstTy, "conv");
397 else
398 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000399 }
400
401 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
402 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000403 if (DstType->isSignedIntegerType())
404 return Builder.CreateFPToSI(Src, DstTy, "conv");
405 else
406 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000407 }
408
409 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000410 if (DstTy->getTypeID() < Src->getType()->getTypeID())
411 return Builder.CreateFPTrunc(Src, DstTy, "conv");
412 else
413 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000414}
415
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000416/// EmitComplexToScalarConversion - Emit a conversion from the specified
417/// complex type to the specified destination type, where the destination
418/// type is an LLVM scalar type.
419Value *ScalarExprEmitter::
420EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
421 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000422 // Get the source element type.
423 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
424
425 // Handle conversions to bool first, they are special: comparisons against 0.
426 if (DstTy->isBooleanType()) {
427 // Complex != 0 -> (Real != 0) | (Imag != 0)
428 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
429 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
430 return Builder.CreateOr(Src.first, Src.second, "tobool");
431 }
432
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000433 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
434 // the imaginary part of the complex value is discarded and the value of the
435 // real part is converted according to the conversion rules for the
436 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000437 return EmitScalarConversion(Src.first, SrcTy, DstTy);
438}
439
440
Chris Lattner9fba49a2007-08-24 05:35:26 +0000441//===----------------------------------------------------------------------===//
442// Visitor Methods
443//===----------------------------------------------------------------------===//
444
445Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Chris Lattnere8f49632007-12-02 01:49:16 +0000446 CGF.WarnUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000447 if (E->getType()->isVoidType())
448 return 0;
449 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
450}
451
Chris Lattnercbfb5512008-03-01 08:45:05 +0000452Value *ScalarExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
453 // Only the lookup mechanism and first two arguments of the method
454 // implementation vary between runtimes. We can get the receiver and
455 // arguments in generic code.
456
457 // Find the receiver
458 llvm::Value * Receiver = CGF.EmitScalarExpr(E->getReceiver());
459
460 // Process the arguments
461 unsigned int ArgC = E->getNumArgs();
462 llvm::SmallVector<llvm::Value*, 16> Args;
463 for(unsigned i=0 ; i<ArgC ; i++) {
464 Expr *ArgExpr = E->getArg(i);
465 QualType ArgTy = ArgExpr->getType();
466 if (!CGF.hasAggregateLLVMType(ArgTy)) {
467 // Scalar argument is passed by-value.
468 Args.push_back(CGF.EmitScalarExpr(ArgExpr));
469 } else if (ArgTy->isComplexType()) {
470 // Make a temporary alloca to pass the argument.
471 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
472 CGF.EmitComplexExprIntoAddr(ArgExpr, DestMem, false);
473 Args.push_back(DestMem);
474 } else {
475 llvm::Value *DestMem = CGF.CreateTempAlloca(ConvertType(ArgTy));
476 CGF.EmitAggExpr(ArgExpr, DestMem, false);
477 Args.push_back(DestMem);
478 }
479 }
480
481 // Get the selector string
482 std::string SelStr = E->getSelector().getName();
483 llvm::Constant *Selector = CGF.CGM.GetAddrOfConstantString(SelStr);
484 ConvertType(E->getType());
485 return Runtime->generateMessageSend(Builder,
486 ConvertType(E->getType()),
487 Receiver,
488 Selector,
489 &Args[0],
490 Args.size());
491}
492
Chris Lattner9fba49a2007-08-24 05:35:26 +0000493Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
494 // Emit subscript expressions in rvalue context's. For most cases, this just
495 // loads the lvalue formed by the subscript expr. However, we have to be
496 // careful, because the base of a vector subscript is occasionally an rvalue,
497 // so we can't get it as an lvalue.
498 if (!E->getBase()->getType()->isVectorType())
499 return EmitLoadOfLValue(E);
500
501 // Handle the vector case. The base must be a vector, the index must be an
502 // integer value.
503 Value *Base = Visit(E->getBase());
504 Value *Idx = Visit(E->getIdx());
505
506 // FIXME: Convert Idx to i32 type.
507 return Builder.CreateExtractElement(Base, Idx, "vecext");
508}
509
510/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
511/// also handle things like function to pointer-to-function decay, and array to
512/// pointer decay.
513Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
514 const Expr *Op = E->getSubExpr();
515
516 // If this is due to array->pointer conversion, emit the array expression as
517 // an l-value.
518 if (Op->getType()->isArrayType()) {
519 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
520 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000521 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000522
523 assert(isa<llvm::PointerType>(V->getType()) &&
524 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
525 ->getElementType()) &&
526 "Doesn't support VLAs yet!");
527 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Ted Kremenek7f6f4a42007-09-04 17:20:08 +0000528
529 llvm::Value *Ops[] = {Idx0, Idx0};
Chris Lattnere54443b2007-12-12 04:13:20 +0000530 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
531
532 // The resultant pointer type can be implicitly casted to other pointer
533 // types as well, for example void*.
534 const llvm::Type *DestPTy = ConvertType(E->getType());
535 assert(isa<llvm::PointerType>(DestPTy) &&
536 "Only expect implicit cast to pointer");
537 if (V->getType() != DestPTy)
538 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
539 return V;
540
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000541 } else if (E->getType()->isReferenceType()) {
Anders Carlsson88842452007-10-13 05:52:34 +0000542 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
543 getReferenceeType() ==
544 Op->getType().getCanonicalType() && "Incompatible types!");
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000545
546 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000547 }
548
549 return EmitCastExpr(Op, E->getType());
550}
551
552
553// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
554// have to handle a more broad range of conversions than explicit casts, as they
555// handle things like function to ptr-to-function decay etc.
556Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000557 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000558
559 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000560 Value *Src = Visit(const_cast<Expr*>(E));
561
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000562 // Use EmitScalarConversion to perform the conversion.
563 return EmitScalarConversion(Src, E->getType(), DestTy);
564 }
Chris Lattner77288792008-02-16 23:55:16 +0000565
566 if (E->getType()->isComplexType()) {
567 // Handle cases where the source is a complex type.
568 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
569 DestTy);
570 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000571
Chris Lattner77288792008-02-16 23:55:16 +0000572 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
573 // evaluate the result and return.
574 CGF.EmitAggExpr(E, 0, false);
575 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000576}
577
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000578Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000579 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000580}
581
582
Chris Lattner9fba49a2007-08-24 05:35:26 +0000583//===----------------------------------------------------------------------===//
584// Unary Operators
585//===----------------------------------------------------------------------===//
586
587Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000588 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000589 LValue LV = EmitLValue(E->getSubExpr());
590 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000591 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000592 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000593
594 int AmountVal = isInc ? 1 : -1;
595
596 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000597 if (isa<llvm::PointerType>(InVal->getType())) {
598 // FIXME: This isn't right for VLAs.
599 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
600 NextVal = Builder.CreateGEP(InVal, NextVal);
601 } else {
602 // Add the inc/dec to the real part.
603 if (isa<llvm::IntegerType>(InVal->getType()))
604 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000605 else if (InVal->getType() == llvm::Type::FloatTy)
606 // FIXME: Handle long double.
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000607 NextVal =
608 llvm::ConstantFP::get(InVal->getType(),
609 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000610 else {
611 // FIXME: Handle long double.
612 assert(InVal->getType() == llvm::Type::DoubleTy);
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000613 NextVal =
614 llvm::ConstantFP::get(InVal->getType(),
615 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000616 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000617 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
618 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000619
620 // Store the updated result through the lvalue.
621 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
622 E->getSubExpr()->getType());
623
624 // If this is a postinc, return the value read from memory, otherwise use the
625 // updated value.
626 return isPre ? NextVal : InVal;
627}
628
629
630Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
631 Value *Op = Visit(E->getSubExpr());
632 return Builder.CreateNeg(Op, "neg");
633}
634
635Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
636 Value *Op = Visit(E->getSubExpr());
637 return Builder.CreateNot(Op, "neg");
638}
639
640Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
641 // Compare operand to zero.
642 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
643
644 // Invert value.
645 // TODO: Could dynamically modify easy computations here. For example, if
646 // the operand is an icmp ne, turn into icmp eq.
647 BoolVal = Builder.CreateNot(BoolVal, "lnot");
648
649 // ZExt result to int.
650 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
651}
652
653/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
654/// an integer (RetType).
655Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
Chris Lattner01211af2007-08-24 21:20:17 +0000656 QualType RetType,bool isSizeOf){
Chris Lattner20515462008-02-21 05:45:29 +0000657 assert(RetType->isIntegerType() && "Result type must be an integer!");
658 uint32_t ResultWidth =
659 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType,
660 SourceLocation()));
661
662 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
663 if (TypeToSize->isVoidType())
664 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1));
665
Chris Lattner9fba49a2007-08-24 05:35:26 +0000666 /// FIXME: This doesn't handle VLAs yet!
667 std::pair<uint64_t, unsigned> Info =
668 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
669
670 uint64_t Val = isSizeOf ? Info.first : Info.second;
671 Val /= 8; // Return size in bytes, not bits.
672
Chris Lattner9fba49a2007-08-24 05:35:26 +0000673 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
674}
675
Chris Lattner01211af2007-08-24 21:20:17 +0000676Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
677 Expr *Op = E->getSubExpr();
678 if (Op->getType()->isComplexType())
679 return CGF.EmitComplexExpr(Op).first;
680 return Visit(Op);
681}
682Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
683 Expr *Op = E->getSubExpr();
684 if (Op->getType()->isComplexType())
685 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000686
687 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
688 // effects are evaluated.
689 CGF.EmitScalarExpr(Op);
690 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000691}
692
Anders Carlsson52774ad2008-01-29 15:56:48 +0000693Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
694{
695 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
696
697 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
698
699 uint32_t ResultWidth = static_cast<uint32_t>(
700 CGF.getContext().getTypeSize(E->getType(), SourceLocation()));
701 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
702}
Chris Lattner01211af2007-08-24 21:20:17 +0000703
Chris Lattner9fba49a2007-08-24 05:35:26 +0000704//===----------------------------------------------------------------------===//
705// Binary Operators
706//===----------------------------------------------------------------------===//
707
708BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
709 BinOpInfo Result;
710 Result.LHS = Visit(E->getLHS());
711 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000712 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000713 Result.E = E;
714 return Result;
715}
716
Chris Lattner0d965302007-08-26 21:41:21 +0000717Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000718 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
719 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
720
721 BinOpInfo OpInfo;
722
723 // Load the LHS and RHS operands.
724 LValue LHSLV = EmitLValue(E->getLHS());
725 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000726
727 // Determine the computation type. If the RHS is complex, then this is one of
728 // the add/sub/mul/div operators. All of these operators can be computed in
729 // with just their real component even though the computation domain really is
730 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000731 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000732
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000733 // If the computation type is complex, then the RHS is complex. Emit the RHS.
734 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
735 ComputeType = CT->getElementType();
736
737 // Emit the RHS, only keeping the real component.
738 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
739 RHSTy = RHSTy->getAsComplexType()->getElementType();
740 } else {
741 // Otherwise the RHS is a simple scalar value.
742 OpInfo.RHS = Visit(E->getRHS());
743 }
744
745 // Convert the LHS/RHS values to the computation type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000746 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000747
Devang Patel04011802007-10-25 22:19:13 +0000748 // Do not merge types for -= or += where the LHS is a pointer.
749 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
Devang Patelce6c8372007-10-30 18:31:12 +0000750 E->getOpcode() == BinaryOperator::AddAssign) ||
Chris Lattner42330c32007-08-25 21:56:20 +0000751 !E->getLHS()->getType()->isPointerType()) {
Chris Lattnerb1497062007-08-26 07:08:39 +0000752 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
Chris Lattner660e31d2007-08-24 21:00:35 +0000753 }
754 OpInfo.Ty = ComputeType;
755 OpInfo.E = E;
756
757 // Expand the binary operator.
758 Value *Result = (this->*Func)(OpInfo);
759
760 // Truncate the result back to the LHS type.
Chris Lattnerb1497062007-08-26 07:08:39 +0000761 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000762
763 // Store the result value into the LHS lvalue.
764 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
765
766 return Result;
767}
768
769
Chris Lattner9fba49a2007-08-24 05:35:26 +0000770Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000771 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000772 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000773 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000774 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
775 else
776 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
777}
778
779Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
780 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000781 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000782 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
783 else
784 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
785}
786
787
788Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000789 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000790 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000791
792 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000793 Value *Ptr, *Idx;
794 Expr *IdxExp;
795 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
796 Ptr = Ops.LHS;
797 Idx = Ops.RHS;
798 IdxExp = Ops.E->getRHS();
799 } else { // int + pointer
800 Ptr = Ops.RHS;
801 Idx = Ops.LHS;
802 IdxExp = Ops.E->getLHS();
803 }
804
805 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
806 if (Width < CGF.LLVMPointerWidth) {
807 // Zero or sign extend the pointer value based on whether the index is
808 // signed or not.
809 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
810 if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
811 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
812 else
813 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
814 }
815
816 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000817}
818
819Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
820 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
821 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
822
Chris Lattner660e31d2007-08-24 21:00:35 +0000823 // pointer - int
824 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
825 "ptr-ptr shouldn't get here");
826 // FIXME: The pointer could point to a VLA.
Chris Lattnere78c1ea2008-01-31 04:12:50 +0000827 Value *Idx = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
828
829 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
830 if (Width < CGF.LLVMPointerWidth) {
831 // Zero or sign extend the pointer value based on whether the index is
832 // signed or not.
833 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
834 if (Ops.E->getRHS()->getType().getCanonicalType()->isSignedIntegerType())
835 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
836 else
837 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
838 }
839
840 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Chris Lattner660e31d2007-08-24 21:00:35 +0000841}
842
843Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
844 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
845 // the compound assignment case it is invalid, so just handle it here.
846 if (!E->getRHS()->getType()->isPointerType())
847 return EmitSub(EmitBinOps(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000848
849 // pointer - pointer
Chris Lattner660e31d2007-08-24 21:00:35 +0000850 Value *LHS = Visit(E->getLHS());
851 Value *RHS = Visit(E->getRHS());
852
Seo Sanghyeonfcd44772007-12-03 06:23:43 +0000853 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
Seo Sanghyeona570d312007-12-26 05:21:37 +0000854 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000855 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
856 SourceLocation()) / 8;
Chris Lattner660e31d2007-08-24 21:00:35 +0000857
858 const llvm::Type *ResultType = ConvertType(E->getType());
859 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
860 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
861 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000862
863 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
864 // remainder. As such, we handle common power-of-two cases here to generate
865 // better code.
866 if (llvm::isPowerOf2_64(ElementSize)) {
867 Value *ShAmt =
868 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
869 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
870 }
Chris Lattner660e31d2007-08-24 21:00:35 +0000871
Chris Lattner9fba49a2007-08-24 05:35:26 +0000872 // Otherwise, do a full sdiv.
873 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
874 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
875}
876
Chris Lattner660e31d2007-08-24 21:00:35 +0000877
Chris Lattner9fba49a2007-08-24 05:35:26 +0000878Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
879 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
880 // RHS to the same size as the LHS.
881 Value *RHS = Ops.RHS;
882 if (Ops.LHS->getType() != RHS->getType())
883 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
884
885 return Builder.CreateShl(Ops.LHS, RHS, "shl");
886}
887
888Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
889 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
890 // RHS to the same size as the LHS.
891 Value *RHS = Ops.RHS;
892 if (Ops.LHS->getType() != RHS->getType())
893 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
894
Chris Lattner660e31d2007-08-24 21:00:35 +0000895 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000896 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
897 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
898}
899
900Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
901 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000902 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000903 QualType LHSTy = E->getLHS()->getType();
904 if (!LHSTy->isComplexType()) {
905 Value *LHS = Visit(E->getLHS());
906 Value *RHS = Visit(E->getRHS());
907
908 if (LHS->getType()->isFloatingPoint()) {
909 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
910 LHS, RHS, "cmp");
911 } else if (LHSTy->isUnsignedIntegerType()) {
912 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
913 LHS, RHS, "cmp");
914 } else {
915 // Signed integers and pointers.
916 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
917 LHS, RHS, "cmp");
918 }
919 } else {
920 // Complex Comparison: can only be an equality comparison.
921 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
922 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
923
924 QualType CETy =
925 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
926
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000927 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000928 if (CETy->isRealFloatingType()) {
929 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
930 LHS.first, RHS.first, "cmp.r");
931 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
932 LHS.second, RHS.second, "cmp.i");
933 } else {
934 // Complex comparisons can only be equality comparisons. As such, signed
935 // and unsigned opcodes are the same.
936 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
937 LHS.first, RHS.first, "cmp.r");
938 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
939 LHS.second, RHS.second, "cmp.i");
940 }
941
942 if (E->getOpcode() == BinaryOperator::EQ) {
943 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
944 } else {
945 assert(E->getOpcode() == BinaryOperator::NE &&
946 "Complex comparison other than == or != ?");
947 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
948 }
949 }
950
951 // ZExt result to int.
952 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
953}
954
955Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
956 LValue LHS = EmitLValue(E->getLHS());
957 Value *RHS = Visit(E->getRHS());
958
959 // Store the value into the LHS.
960 // FIXME: Volatility!
961 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
962
963 // Return the RHS.
964 return RHS;
965}
966
967Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
968 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
969
970 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
971 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
972
973 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
974 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
975
976 CGF.EmitBlock(RHSBlock);
977 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
978
979 // Reaquire the RHS block, as there may be subblocks inserted.
980 RHSBlock = Builder.GetInsertBlock();
981 CGF.EmitBlock(ContBlock);
982
983 // Create a PHI node. If we just evaluted the LHS condition, the result is
984 // false. If we evaluated both, the result is the RHS condition.
985 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
986 PN->reserveOperandSpace(2);
987 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
988 PN->addIncoming(RHSCond, RHSBlock);
989
990 // ZExt result to int.
991 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
992}
993
994Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
995 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
996
997 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
998 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
999
1000 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1001 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1002
1003 CGF.EmitBlock(RHSBlock);
1004 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1005
1006 // Reaquire the RHS block, as there may be subblocks inserted.
1007 RHSBlock = Builder.GetInsertBlock();
1008 CGF.EmitBlock(ContBlock);
1009
1010 // Create a PHI node. If we just evaluted the LHS condition, the result is
1011 // true. If we evaluated both, the result is the RHS condition.
1012 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1013 PN->reserveOperandSpace(2);
1014 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1015 PN->addIncoming(RHSCond, RHSBlock);
1016
1017 // ZExt result to int.
1018 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1019}
1020
1021Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1022 CGF.EmitStmt(E->getLHS());
1023 return Visit(E->getRHS());
1024}
1025
1026//===----------------------------------------------------------------------===//
1027// Other Operators
1028//===----------------------------------------------------------------------===//
1029
1030Value *ScalarExprEmitter::
1031VisitConditionalOperator(const ConditionalOperator *E) {
1032 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1033 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1034 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1035
Chris Lattner98a425c2007-11-26 01:40:58 +00001036 // Evaluate the conditional, then convert it to bool. We do this explicitly
1037 // because we need the unconverted value if this is a GNU ?: expression with
1038 // missing middle value.
1039 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnerc2126682008-01-03 07:05:49 +00001040 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1041 CGF.getContext().BoolTy);
Chris Lattner98a425c2007-11-26 01:40:58 +00001042 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001043
1044 CGF.EmitBlock(LHSBlock);
1045
1046 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001047 Value *LHS;
1048 if (E->getLHS())
1049 LHS = Visit(E->getLHS());
1050 else // Perform promotions, to handle cases like "short ?: int"
1051 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1052
Chris Lattner9fba49a2007-08-24 05:35:26 +00001053 Builder.CreateBr(ContBlock);
1054 LHSBlock = Builder.GetInsertBlock();
1055
1056 CGF.EmitBlock(RHSBlock);
1057
1058 Value *RHS = Visit(E->getRHS());
1059 Builder.CreateBr(ContBlock);
1060 RHSBlock = Builder.GetInsertBlock();
1061
1062 CGF.EmitBlock(ContBlock);
1063
Chris Lattner307da022007-11-30 17:56:23 +00001064 if (!LHS) {
1065 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1066 return 0;
1067 }
1068
Chris Lattner9fba49a2007-08-24 05:35:26 +00001069 // Create a PHI node for the real part.
1070 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1071 PN->reserveOperandSpace(2);
1072 PN->addIncoming(LHS, LHSBlock);
1073 PN->addIncoming(RHS, RHSBlock);
1074 return PN;
1075}
1076
1077Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001078 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001079 return
1080 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001081}
1082
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001083Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
Nate Begemanbd881ef2008-01-30 20:50:20 +00001084 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
1085 E->getNumArgs(CGF.getContext())).getScalarVal();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001086}
1087
Chris Lattner307da022007-11-30 17:56:23 +00001088Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Anders Carlsson36760332007-10-15 20:28:48 +00001089 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1090
1091 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1092 return V;
1093}
1094
Chris Lattner307da022007-11-30 17:56:23 +00001095Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001096 std::string str;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001097 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1098 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1099 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001100
1101 llvm::Constant *C = llvm::ConstantArray::get(str);
1102 C = new llvm::GlobalVariable(C->getType(), true,
1103 llvm::GlobalValue::InternalLinkage,
1104 C, ".str", &CGF.CGM.getModule());
1105 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1106 llvm::Constant *Zeros[] = { Zero, Zero };
1107 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1108
1109 return C;
1110}
1111
Chris Lattner9fba49a2007-08-24 05:35:26 +00001112//===----------------------------------------------------------------------===//
1113// Entry Point into this File
1114//===----------------------------------------------------------------------===//
1115
1116/// EmitComplexExpr - Emit the computation of the specified expression of
1117/// complex type, ignoring the result.
1118Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1119 assert(E && !hasAggregateLLVMType(E->getType()) &&
1120 "Invalid scalar expression to emit");
1121
1122 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1123}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001124
1125/// EmitScalarConversion - Emit a conversion from the specified type to the
1126/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001127Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1128 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001129 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1130 "Invalid scalar expression to emit");
1131 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1132}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001133
1134/// EmitComplexToScalarConversion - Emit a conversion from the specified
1135/// complex type to the specified destination type, where the destination
1136/// type is an LLVM scalar type.
1137Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1138 QualType SrcTy,
1139 QualType DstTy) {
1140 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1141 "Invalid complex -> scalar conversion");
1142 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1143 DstTy);
1144}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001145
1146Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1147 assert(V1->getType() == V2->getType() &&
1148 "Vector operands must be of the same type");
1149
1150 unsigned NumElements =
1151 cast<llvm::VectorType>(V1->getType())->getNumElements();
1152
1153 va_list va;
1154 va_start(va, V2);
1155
1156 llvm::SmallVector<llvm::Constant*, 16> Args;
1157
1158 for (unsigned i = 0; i < NumElements; i++) {
1159 int n = va_arg(va, int);
1160
1161 assert(n >= 0 && n < (int)NumElements * 2 &&
1162 "Vector shuffle index out of bounds!");
1163
1164 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1165 }
1166
1167 const char *Name = va_arg(va, const char *);
1168 va_end(va);
1169
1170 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1171
1172 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1173}
1174
Anders Carlsson68b8be92007-12-15 21:23:30 +00001175llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Nate Begemanec2d1062007-12-30 02:59:45 +00001176 unsigned NumVals, bool isSplat)
Anders Carlsson68b8be92007-12-15 21:23:30 +00001177{
Anders Carlsson68b8be92007-12-15 21:23:30 +00001178 llvm::Value *Vec
1179 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1180
1181 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001182 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001183 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001184 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001185 }
1186
1187 return Vec;
1188}