blob: c65c0816e2bd4e466b1b7fa3e58d82c55a9036ee [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"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbarfa456242008-08-12 05:08:18 +000017#include "clang/AST/DeclObjC.h"
Eli Friedmanccffea92009-01-24 22:38:55 +000018#include "clang/AST/RecordLayout.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000023#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000024#include "llvm/Intrinsics.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000025#include "llvm/Support/Compiler.h"
Chris Lattner7f80bb32008-11-12 08:38:24 +000026#include "llvm/Support/CFG.h"
Mike Stumpfca5da02009-02-21 20:00:35 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000028#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000029
Chris Lattner9fba49a2007-08-24 05:35:26 +000030using namespace clang;
31using namespace CodeGen;
32using llvm::Value;
33
34//===----------------------------------------------------------------------===//
35// Scalar Expression Emitter
36//===----------------------------------------------------------------------===//
37
38struct BinOpInfo {
39 Value *LHS;
40 Value *RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +000041 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-08-24 05:35:26 +000042 const BinaryOperator *E;
43};
44
45namespace {
46class VISIBILITY_HIDDEN ScalarExprEmitter
47 : public StmtVisitor<ScalarExprEmitter, Value*> {
48 CodeGenFunction &CGF;
Daniel Dunbard916e6e2008-11-01 01:53:16 +000049 CGBuilderTy &Builder;
Chris Lattnercbfb5512008-03-01 08:45:05 +000050
Chris Lattner9fba49a2007-08-24 05:35:26 +000051public:
52
Chris Lattnercbfb5512008-03-01 08:45:05 +000053 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf),
Daniel Dunbarf1f7f192008-08-20 00:28:19 +000054 Builder(CGF.Builder) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000055 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000056
57 //===--------------------------------------------------------------------===//
58 // Utilities
59 //===--------------------------------------------------------------------===//
60
61 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
62 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
63
64 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +000065 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +000066 }
67
68 /// EmitLoadOfLValue - Given an expression with complex type that represents a
69 /// value l-value, this method emits the address of the l-value, then loads
70 /// and returns the result.
71 Value *EmitLoadOfLValue(const Expr *E) {
72 // FIXME: Volatile
73 return EmitLoadOfLValue(EmitLValue(E), E->getType());
74 }
75
Chris Lattnerd8d44222007-08-26 16:42:57 +000076 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000077 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000078 Value *EmitConversionToBool(Value *Src, QualType DstTy);
79
Chris Lattner4e05d1e2007-08-26 06:48:56 +000080 /// EmitScalarConversion - Emit a conversion from the specified type to the
81 /// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +000082 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
83
84 /// EmitComplexToScalarConversion - Emit a conversion from the specified
85 /// complex type to the specified destination type, where the destination
86 /// type is an LLVM scalar type.
87 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
88 QualType SrcTy, QualType DstTy);
Mike Stump4eb81dc2009-02-12 18:29:15 +000089
Chris Lattner9fba49a2007-08-24 05:35:26 +000090 //===--------------------------------------------------------------------===//
91 // Visitor Methods
92 //===--------------------------------------------------------------------===//
93
94 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +000095 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-08-24 05:35:26 +000096 assert(0 && "Stmt can't have complex result type!");
97 return 0;
98 }
99 Value *VisitExpr(Expr *S);
100 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
101
102 // Leaves.
103 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
104 return llvm::ConstantInt::get(E->getValue());
105 }
106 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Chris Lattner70c38672008-04-20 00:45:53 +0000107 return llvm::ConstantFP::get(E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000108 }
109 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
110 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
111 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000112 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
113 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
114 }
Argiris Kirtzidis750eb972008-08-23 19:35:47 +0000115 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
116 return llvm::Constant::getNullValue(ConvertType(E->getType()));
117 }
Anders Carlsson774f9c72008-12-21 22:39:40 +0000118 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
119 return llvm::Constant::getNullValue(ConvertType(E->getType()));
120 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000121 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
122 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000123 CGF.getContext().typesAreCompatible(
124 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000125 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000126 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000127 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbarb5fda0c2008-08-16 01:41:47 +0000128 llvm::Value *V =
129 llvm::ConstantInt::get(llvm::Type::Int32Ty,
130 CGF.GetIDForAddrOfLabel(E->getLabel()));
131
132 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar879788d2008-08-04 16:51:22 +0000133 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000134
135 // l-values.
136 Value *VisitDeclRefExpr(DeclRefExpr *E) {
137 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
138 return llvm::ConstantInt::get(EC->getInitVal());
139 return EmitLoadOfLValue(E);
140 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000141 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
142 return CGF.EmitObjCSelectorExpr(E);
143 }
144 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
145 return CGF.EmitObjCProtocolExpr(E);
146 }
147 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
148 return EmitLoadOfLValue(E);
149 }
Daniel Dunbar5e105892008-08-23 10:51:21 +0000150 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbare6c31752008-08-29 08:11:39 +0000151 return EmitLoadOfLValue(E);
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000152 }
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000153 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
154 return EmitLoadOfLValue(E);
155 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000156 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
157 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar5e105892008-08-23 10:51:21 +0000158 }
159
Chris Lattner9fba49a2007-08-24 05:35:26 +0000160 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000161 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000162 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000163 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnera9177982008-10-26 23:53:12 +0000164 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
165 return EmitLoadOfLValue(E);
166 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000167 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnerc5d32632009-02-24 22:18:39 +0000168 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
169 return EmitLValue(E).getAddress();
170 }
171
Chris Lattner69909292008-08-10 01:53:14 +0000172 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000173
174 Value *VisitInitListExpr(InitListExpr *E) {
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000175 unsigned NumInitElements = E->getNumInits();
176
Douglas Gregor9fddded2009-01-29 19:42:23 +0000177 if (E->hadArrayRangeDesignator()) {
178 CGF.ErrorUnsupported(E, "GNU array range designator extension");
179 }
180
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000181 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-01-29 01:15:48 +0000182 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
183
184 // We have a scalar in braces. Just use the first element.
185 if (!VType)
186 return Visit(E->getInit(0));
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000187
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000188 unsigned NumVectorElements = VType->getNumElements();
189 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000190
191 // Emit individual vector element stores.
192 llvm::Value *V = llvm::UndefValue::get(VType);
193
Anders Carlsson323d5682007-12-18 02:45:33 +0000194 // Emit initializers
195 unsigned i;
196 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000197 Value *NewV = Visit(E->getInit(i));
198 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
199 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000200 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000201
202 // Emit remaining default initializers
203 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
204 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
205 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
206 V = Builder.CreateInsertElement(V, NewV, Idx);
207 }
208
Devang Patel32c39832007-10-24 18:05:48 +0000209 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000210 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000211
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000212 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
213 return llvm::Constant::getNullValue(ConvertType(E->getType()));
214 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000215 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
216 Value *VisitCastExpr(const CastExpr *E) {
217 return EmitCastExpr(E->getSubExpr(), E->getType());
218 }
219 Value *EmitCastExpr(const Expr *E, QualType T);
220
221 Value *VisitCallExpr(const CallExpr *E) {
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000222 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000223 }
Daniel Dunbara04840b2008-08-23 03:46:30 +0000224
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000225 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpfca5da02009-02-21 20:00:35 +0000226
227 Value *VisitBlockDeclRefExpr(BlockDeclRefExpr *E);
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000228
Chris Lattner9fba49a2007-08-24 05:35:26 +0000229 // Unary Operators.
230 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
231 Value *VisitUnaryPostDec(const UnaryOperator *E) {
232 return VisitPrePostIncDec(E, false, false);
233 }
234 Value *VisitUnaryPostInc(const UnaryOperator *E) {
235 return VisitPrePostIncDec(E, true, false);
236 }
237 Value *VisitUnaryPreDec(const UnaryOperator *E) {
238 return VisitPrePostIncDec(E, false, true);
239 }
240 Value *VisitUnaryPreInc(const UnaryOperator *E) {
241 return VisitPrePostIncDec(E, true, true);
242 }
243 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
244 return EmitLValue(E->getSubExpr()).getAddress();
245 }
246 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
247 Value *VisitUnaryPlus(const UnaryOperator *E) {
248 return Visit(E->getSubExpr());
249 }
250 Value *VisitUnaryMinus (const UnaryOperator *E);
251 Value *VisitUnaryNot (const UnaryOperator *E);
252 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner01211af2007-08-24 21:20:17 +0000253 Value *VisitUnaryReal (const UnaryOperator *E);
254 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000255 Value *VisitUnaryExtension(const UnaryOperator *E) {
256 return Visit(E->getSubExpr());
257 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000258 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000259 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
260 return Visit(DAE->getExpr());
261 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000262
Chris Lattner9fba49a2007-08-24 05:35:26 +0000263 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000264 Value *EmitMul(const BinOpInfo &Ops) {
265 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
266 }
267 Value *EmitDiv(const BinOpInfo &Ops);
268 Value *EmitRem(const BinOpInfo &Ops);
269 Value *EmitAdd(const BinOpInfo &Ops);
270 Value *EmitSub(const BinOpInfo &Ops);
271 Value *EmitShl(const BinOpInfo &Ops);
272 Value *EmitShr(const BinOpInfo &Ops);
273 Value *EmitAnd(const BinOpInfo &Ops) {
274 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
275 }
276 Value *EmitXor(const BinOpInfo &Ops) {
277 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
278 }
279 Value *EmitOr (const BinOpInfo &Ops) {
280 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
281 }
282
Chris Lattner660e31d2007-08-24 21:00:35 +0000283 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000284 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000285 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
286
287 // Binary operators and binary compound assignment operators.
288#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000289 Value *VisitBin ## OP(const BinaryOperator *E) { \
290 return Emit ## OP(EmitBinOps(E)); \
291 } \
292 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
293 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000294 }
295 HANDLEBINOP(Mul);
296 HANDLEBINOP(Div);
297 HANDLEBINOP(Rem);
298 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000299 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000300 HANDLEBINOP(Shl);
301 HANDLEBINOP(Shr);
302 HANDLEBINOP(And);
303 HANDLEBINOP(Xor);
304 HANDLEBINOP(Or);
305#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000306
Chris Lattner9fba49a2007-08-24 05:35:26 +0000307 // Comparisons.
308 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
309 unsigned SICmpOpc, unsigned FCmpOpc);
310#define VISITCOMP(CODE, UI, SI, FP) \
311 Value *VisitBin##CODE(const BinaryOperator *E) { \
312 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
313 llvm::FCmpInst::FP); }
314 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
315 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
316 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
317 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
318 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
319 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
320#undef VISITCOMP
321
322 Value *VisitBinAssign (const BinaryOperator *E);
323
324 Value *VisitBinLAnd (const BinaryOperator *E);
325 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000326 Value *VisitBinComma (const BinaryOperator *E);
327
328 // Other Operators.
Mike Stump4eb81dc2009-02-12 18:29:15 +0000329 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000330 Value *VisitConditionalOperator(const ConditionalOperator *CO);
331 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000332 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000333 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
334 return CGF.EmitObjCStringLiteral(E);
335 }
336};
337} // end anonymous namespace.
338
339//===----------------------------------------------------------------------===//
340// Utilities
341//===----------------------------------------------------------------------===//
342
Chris Lattnerd8d44222007-08-26 16:42:57 +0000343/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000344/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000345Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
346 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
347
348 if (SrcType->isRealFloatingType()) {
349 // Compare against 0.0 for fp scalars.
350 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000351 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
352 }
353
Daniel Dunbar5d54eed2008-08-25 10:38:11 +0000354 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnerd8d44222007-08-26 16:42:57 +0000355 "Unknown scalar type to convert");
356
357 // Because of the type rules of C, we often end up computing a logical value,
358 // then zero extending it to int, then wanting it as a logical value again.
359 // Optimize this common case.
360 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
361 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
362 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000363 // If there aren't any more uses, zap the instruction to save space.
364 // Note that there can be more uses, for example if this
365 // is the result of an assignment.
366 if (ZI->use_empty())
367 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000368 return Result;
369 }
370 }
371
372 // Compare against an integer or pointer null.
373 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
374 return Builder.CreateICmpNE(Src, Zero, "tobool");
375}
376
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000377/// EmitScalarConversion - Emit a conversion from the specified type to the
378/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000379Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
380 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000381 SrcType = CGF.getContext().getCanonicalType(SrcType);
382 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000383 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000384
385 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000386
387 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000388 if (DstType->isBooleanType())
389 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000390
391 const llvm::Type *DstTy = ConvertType(DstType);
392
393 // Ignore conversions like int -> uint.
394 if (Src->getType() == DstTy)
395 return Src;
396
Daniel Dunbar238335f2008-08-25 09:51:32 +0000397 // Handle pointer conversions next: pointers can only be converted
398 // to/from other pointers and integers. Check for pointer types in
399 // terms of LLVM, as some native types (like Obj-C id) may map to a
400 // pointer type.
401 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000402 // The source value may be an integer, or a pointer.
403 if (isa<llvm::PointerType>(Src->getType()))
404 return Builder.CreateBitCast(Src, DstTy, "conv");
405 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
406 return Builder.CreateIntToPtr(Src, DstTy, "conv");
407 }
408
Daniel Dunbar238335f2008-08-25 09:51:32 +0000409 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000410 // Must be an ptr to int cast.
411 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000412 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000413 }
414
Nate Begemanaf6ed502008-04-18 23:10:10 +0000415 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman7903d052009-01-18 06:42:49 +0000416 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
417 // Cast the scalar to element type
418 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
419 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
420
421 // Insert the element in element zero of an undef vector
422 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
423 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
424 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
425
426 // Splat the element across to all elements
427 llvm::SmallVector<llvm::Constant*, 16> Args;
428 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
429 for (unsigned i = 0; i < NumElements; i++)
430 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
431
432 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
433 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
434 return Yay;
435 }
Nate Begemanec2d1062007-12-30 02:59:45 +0000436
Chris Lattner4f025a42008-02-02 04:51:41 +0000437 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000438 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000439 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000440 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000441
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000442 // Finally, we have the arithmetic types: real int/float.
443 if (isa<llvm::IntegerType>(Src->getType())) {
444 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000445 if (isa<llvm::IntegerType>(DstTy))
446 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
447 else if (InputSigned)
448 return Builder.CreateSIToFP(Src, DstTy, "conv");
449 else
450 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000451 }
452
453 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
454 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000455 if (DstType->isSignedIntegerType())
456 return Builder.CreateFPToSI(Src, DstTy, "conv");
457 else
458 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000459 }
460
461 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000462 if (DstTy->getTypeID() < Src->getType()->getTypeID())
463 return Builder.CreateFPTrunc(Src, DstTy, "conv");
464 else
465 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000466}
467
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000468/// EmitComplexToScalarConversion - Emit a conversion from the specified
469/// complex type to the specified destination type, where the destination
470/// type is an LLVM scalar type.
471Value *ScalarExprEmitter::
472EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
473 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000474 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000475 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000476
477 // Handle conversions to bool first, they are special: comparisons against 0.
478 if (DstTy->isBooleanType()) {
479 // Complex != 0 -> (Real != 0) | (Imag != 0)
480 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
481 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
482 return Builder.CreateOr(Src.first, Src.second, "tobool");
483 }
484
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000485 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
486 // the imaginary part of the complex value is discarded and the value of the
487 // real part is converted according to the conversion rules for the
488 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000489 return EmitScalarConversion(Src.first, SrcTy, DstTy);
490}
491
492
Chris Lattner9fba49a2007-08-24 05:35:26 +0000493//===----------------------------------------------------------------------===//
494// Visitor Methods
495//===----------------------------------------------------------------------===//
496
497Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000498 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000499 if (E->getType()->isVoidType())
500 return 0;
501 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
502}
503
Eli Friedmand0e9d092008-05-14 19:38:39 +0000504Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
505 llvm::SmallVector<llvm::Constant*, 32> indices;
506 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
507 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
508 }
509 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
510 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
511 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
512 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
513}
514
Chris Lattner9fba49a2007-08-24 05:35:26 +0000515Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
516 // Emit subscript expressions in rvalue context's. For most cases, this just
517 // loads the lvalue formed by the subscript expr. However, we have to be
518 // careful, because the base of a vector subscript is occasionally an rvalue,
519 // so we can't get it as an lvalue.
520 if (!E->getBase()->getType()->isVectorType())
521 return EmitLoadOfLValue(E);
522
523 // Handle the vector case. The base must be a vector, the index must be an
524 // integer value.
525 Value *Base = Visit(E->getBase());
526 Value *Idx = Visit(E->getIdx());
527
528 // FIXME: Convert Idx to i32 type.
529 return Builder.CreateExtractElement(Base, Idx, "vecext");
530}
531
532/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
533/// also handle things like function to pointer-to-function decay, and array to
534/// pointer decay.
535Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
536 const Expr *Op = E->getSubExpr();
537
538 // If this is due to array->pointer conversion, emit the array expression as
539 // an l-value.
540 if (Op->getType()->isArrayType()) {
541 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
542 // will not true when we add support for VLAs.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000543 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000544
545 if (!Op->getType()->isVariableArrayType()) {
546 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
547 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
548 ->getElementType()) &&
549 "Expected pointer to array");
550 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar952f4732008-08-29 17:28:43 +0000551 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000552
553 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000554 // types as well (e.g. void*) and can be implicitly converted to integer.
555 const llvm::Type *DestTy = ConvertType(E->getType());
556 if (V->getType() != DestTy) {
557 if (isa<llvm::PointerType>(DestTy))
558 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
559 else {
560 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
561 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
562 }
563 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000564 return V;
565
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000566 } else if (E->getType()->isReferenceType()) {
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000567 return EmitLValue(Op).getAddress();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000568 }
569
570 return EmitCastExpr(Op, E->getType());
571}
572
573
574// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
575// have to handle a more broad range of conversions than explicit casts, as they
576// handle things like function to ptr-to-function decay etc.
577Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Chris Lattner82e10392007-08-26 07:26:12 +0000578 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000579
580 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000581 Value *Src = Visit(const_cast<Expr*>(E));
582
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000583 // Use EmitScalarConversion to perform the conversion.
584 return EmitScalarConversion(Src, E->getType(), DestTy);
585 }
Chris Lattner77288792008-02-16 23:55:16 +0000586
Chris Lattnerde0908b2008-04-04 16:54:41 +0000587 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000588 // Handle cases where the source is a complex type.
589 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
590 DestTy);
591 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000592
Chris Lattner77288792008-02-16 23:55:16 +0000593 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
594 // evaluate the result and return.
595 CGF.EmitAggExpr(E, 0, false);
596 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000597}
598
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000599Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000600 return CGF.EmitCompoundStmt(*E->getSubStmt(),
601 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000602}
603
Mike Stumpfca5da02009-02-21 20:00:35 +0000604Value *ScalarExprEmitter::VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
605 if (E->isByRef()) {
606 // FIXME: Add codegen for __block variables.
607 return VisitExpr(E);
608 }
609
Mike Stumpf1711822009-02-25 23:33:13 +0000610 // FIXME: ensure we don't need copy/dispose.
Mike Stumpfca5da02009-02-21 20:00:35 +0000611 uint64_t &offset = CGF.BlockDecls[E->getDecl()];
612
613 const llvm::Type *Ty;
614 Ty = CGF.CGM.getTypes().ConvertType(E->getDecl()->getType());
615
616 // See if we have already allocated an offset for this variable.
617 if (offset == 0) {
Mike Stumpfca5da02009-02-21 20:00:35 +0000618 // if not, allocate one now.
Mike Stump39bcc612009-02-22 13:27:11 +0000619 offset = CGF.getBlockOffset(E->getDecl());
Mike Stumpfca5da02009-02-21 20:00:35 +0000620 }
621
622 llvm::Value *BlockLiteral = CGF.LoadBlockStruct();
623 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
624 llvm::ConstantInt::get(llvm::Type::Int64Ty,
625 offset),
626 "tmp");
627 Ty = llvm::PointerType::get(Ty, 0);
628 if (E->isByRef())
629 Ty = llvm::PointerType::get(Ty, 0);
630 V = Builder.CreateBitCast(V, Ty);
631 V = Builder.CreateLoad(V, false, "tmp");
632 if (E->isByRef())
633 V = Builder.CreateLoad(V, false, "tmp");
634 return V;
635}
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000636
Chris Lattner9fba49a2007-08-24 05:35:26 +0000637//===----------------------------------------------------------------------===//
638// Unary Operators
639//===----------------------------------------------------------------------===//
640
641Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000642 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000643 LValue LV = EmitLValue(E->getSubExpr());
644 // FIXME: Handle volatile!
Chris Lattner0dc11f62007-08-26 05:10:16 +0000645 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000646 E->getSubExpr()->getType()).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000647
648 int AmountVal = isInc ? 1 : -1;
649
650 Value *NextVal;
Chris Lattner0dc11f62007-08-26 05:10:16 +0000651 if (isa<llvm::PointerType>(InVal->getType())) {
652 // FIXME: This isn't right for VLAs.
653 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner07307562008-03-19 05:19:41 +0000654 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec");
Chris Lattner49083172009-02-11 07:40:06 +0000655 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
656 // Bool++ is an interesting case, due to promotion rules, we get:
657 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
658 // Bool = ((int)Bool+1) != 0
659 // An interesting aspect of this is that increment is always true.
660 // Decrement does not have this property.
661 NextVal = llvm::ConstantInt::getTrue();
Chris Lattner0dc11f62007-08-26 05:10:16 +0000662 } else {
663 // Add the inc/dec to the real part.
664 if (isa<llvm::IntegerType>(InVal->getType()))
665 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000666 else if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000667 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000668 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000669 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000670 NextVal =
Chris Lattner70c38672008-04-20 00:45:53 +0000671 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000672 else {
673 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesen2461f612008-10-09 23:02:32 +0000674 bool ignored;
675 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
676 &ignored);
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000677 NextVal = llvm::ConstantFP::get(F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000678 }
Chris Lattner0dc11f62007-08-26 05:10:16 +0000679 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
680 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000681
682 // Store the updated result through the lvalue.
683 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
684 E->getSubExpr()->getType());
685
686 // If this is a postinc, return the value read from memory, otherwise use the
687 // updated value.
688 return isPre ? NextVal : InVal;
689}
690
691
692Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
693 Value *Op = Visit(E->getSubExpr());
694 return Builder.CreateNeg(Op, "neg");
695}
696
697Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
698 Value *Op = Visit(E->getSubExpr());
699 return Builder.CreateNot(Op, "neg");
700}
701
702Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
703 // Compare operand to zero.
704 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
705
706 // Invert value.
707 // TODO: Could dynamically modify easy computations here. For example, if
708 // the operand is an icmp ne, turn into icmp eq.
709 BoolVal = Builder.CreateNot(BoolVal, "lnot");
710
711 // ZExt result to int.
712 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
713}
714
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000715/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
716/// argument of the sizeof expression as an integer.
717Value *
718ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000719 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000720 if (E->isSizeOf()) {
721 if (const VariableArrayType *VAT =
722 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
723 if (E->isArgumentType()) {
724 // sizeof(type) - make sure to emit the VLA size.
725 CGF.EmitVLASize(TypeToSize);
726 }
Anders Carlssond309f572009-01-30 16:41:04 +0000727
Anders Carlsson8f30de92009-02-05 19:43:10 +0000728 return CGF.GetVLASize(VAT);
Anders Carlsson6cb99b72008-12-21 03:33:21 +0000729 }
Anders Carlsson9be6aaf2008-12-12 07:38:43 +0000730 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000731
732 // If this isn't sizeof(vla), the result must be constant; use the
733 // constant folding logic so we don't have to duplicate it here.
734 Expr::EvalResult Result;
735 E->Evaluate(Result, CGF.getContext());
736 return llvm::ConstantInt::get(Result.Val.getInt());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000737}
738
Chris Lattner01211af2007-08-24 21:20:17 +0000739Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
740 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000741 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000742 return CGF.EmitComplexExpr(Op).first;
743 return Visit(Op);
744}
745Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
746 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000747 if (Op->getType()->isAnyComplexType())
Chris Lattner01211af2007-08-24 21:20:17 +0000748 return CGF.EmitComplexExpr(Op).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000749
750 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
751 // effects are evaluated.
752 CGF.EmitScalarExpr(Op);
753 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000754}
755
Anders Carlsson52774ad2008-01-29 15:56:48 +0000756Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
757{
Eli Friedman342d9432009-02-27 06:44:11 +0000758 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedmanccffea92009-01-24 22:38:55 +0000759 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman342d9432009-02-27 06:44:11 +0000760 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson52774ad2008-01-29 15:56:48 +0000761}
Chris Lattner01211af2007-08-24 21:20:17 +0000762
Chris Lattner9fba49a2007-08-24 05:35:26 +0000763//===----------------------------------------------------------------------===//
764// Binary Operators
765//===----------------------------------------------------------------------===//
766
767BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
768 BinOpInfo Result;
769 Result.LHS = Visit(E->getLHS());
770 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000771 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000772 Result.E = E;
773 return Result;
774}
775
Chris Lattner0d965302007-08-26 21:41:21 +0000776Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000777 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
778 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
779
780 BinOpInfo OpInfo;
781
782 // Load the LHS and RHS operands.
783 LValue LHSLV = EmitLValue(E->getLHS());
784 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000785
786 // Determine the computation type. If the RHS is complex, then this is one of
787 // the add/sub/mul/div operators. All of these operators can be computed in
788 // with just their real component even though the computation domain really is
789 // complex.
Chris Lattner0d965302007-08-26 21:41:21 +0000790 QualType ComputeType = E->getComputationType();
Chris Lattner660e31d2007-08-24 21:00:35 +0000791
Chris Lattner9c9f4bb2007-08-26 22:37:40 +0000792 // If the computation type is complex, then the RHS is complex. Emit the RHS.
793 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
794 ComputeType = CT->getElementType();
795
796 // Emit the RHS, only keeping the real component.
797 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
798 RHSTy = RHSTy->getAsComplexType()->getElementType();
799 } else {
800 // Otherwise the RHS is a simple scalar value.
801 OpInfo.RHS = Visit(E->getRHS());
802 }
803
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000804 QualType LComputeTy, RComputeTy, ResultTy;
805
806 // Compound assignment does not contain enough information about all
807 // the types involved for pointer arithmetic cases. Figure it out
808 // here for now.
809 if (E->getLHS()->getType()->isPointerType()) {
810 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr,
811 assert((E->getOpcode() == BinaryOperator::AddAssign ||
812 E->getOpcode() == BinaryOperator::SubAssign) &&
813 "Invalid compound assignment operator on pointer type.");
814 LComputeTy = E->getLHS()->getType();
815
816 if (E->getRHS()->getType()->isPointerType()) {
817 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast
818 // extension, the conversion from the pointer difference back to
819 // the LHS type is handled at the end.
820 assert(E->getOpcode() == BinaryOperator::SubAssign &&
821 "Invalid compound assignment operator on pointer type.");
822 RComputeTy = E->getLHS()->getType();
823 ResultTy = CGF.getContext().getPointerDiffType();
824 } else {
825 RComputeTy = E->getRHS()->getType();
826 ResultTy = LComputeTy;
827 }
828 } else if (E->getRHS()->getType()->isPointerType()) {
829 // Degenerate case of (int += ptr) allowed by GCC implicit cast
830 // extension.
831 assert(E->getOpcode() == BinaryOperator::AddAssign &&
832 "Invalid compound assignment operator on pointer type.");
833 LComputeTy = E->getLHS()->getType();
834 RComputeTy = E->getRHS()->getType();
835 ResultTy = RComputeTy;
836 } else {
837 LComputeTy = RComputeTy = ResultTy = ComputeType;
Chris Lattner660e31d2007-08-24 21:00:35 +0000838 }
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000839
840 // Convert the LHS/RHS values to the computation type.
841 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy);
842 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy);
843 OpInfo.Ty = ResultTy;
Chris Lattner660e31d2007-08-24 21:00:35 +0000844 OpInfo.E = E;
845
846 // Expand the binary operator.
847 Value *Result = (this->*Func)(OpInfo);
848
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000849 // Convert the result back to the LHS type.
850 Result = EmitScalarConversion(Result, ResultTy, LHSTy);
Chris Lattner660e31d2007-08-24 21:00:35 +0000851
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000852 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar2710fc92008-11-19 11:54:05 +0000853 // handled specially because the result is altered by the store,
854 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
855 // the left operand after the assignment...'.
Eli Friedmanf9b930c2008-05-25 14:13:57 +0000856 if (LHSLV.isBitfield())
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000857 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
858 &Result);
859 else
860 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
861
Chris Lattner660e31d2007-08-24 21:00:35 +0000862 return Result;
863}
864
865
Chris Lattner9fba49a2007-08-24 05:35:26 +0000866Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000867 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000868 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000869 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000870 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
871 else
872 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
873}
874
875Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
876 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000877 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000878 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
879 else
880 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
881}
882
883
884Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Chris Lattner660e31d2007-08-24 21:00:35 +0000885 if (!Ops.Ty->isPointerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000886 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Chris Lattner660e31d2007-08-24 21:00:35 +0000887
888 // FIXME: What about a pointer to a VLA?
Chris Lattner17c0cb02008-01-03 06:36:51 +0000889 Value *Ptr, *Idx;
890 Expr *IdxExp;
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000891 const PointerType *PT;
892 if ((PT = Ops.E->getLHS()->getType()->getAsPointerType())) {
Chris Lattner17c0cb02008-01-03 06:36:51 +0000893 Ptr = Ops.LHS;
894 Idx = Ops.RHS;
895 IdxExp = Ops.E->getRHS();
896 } else { // int + pointer
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000897 PT = Ops.E->getRHS()->getType()->getAsPointerType();
898 assert(PT && "Invalid add expr");
Chris Lattner17c0cb02008-01-03 06:36:51 +0000899 Ptr = Ops.RHS;
900 Idx = Ops.LHS;
901 IdxExp = Ops.E->getLHS();
902 }
903
904 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
905 if (Width < CGF.LLVMPointerWidth) {
906 // Zero or sign extend the pointer value based on whether the index is
907 // signed or not.
908 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +0000909 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +0000910 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
911 else
912 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
913 }
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000914
915 // Explicitly handle GNU void* and function pointer arithmetic
916 // extensions. The GNU void* casts amount to no-ops since our void*
917 // type is i8*, but this is future proof.
918 const QualType ElementType = PT->getPointeeType();
919 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
920 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
921 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
922 Value *Res = Builder.CreateGEP(Casted, Idx, "sub.ptr");
923 return Builder.CreateBitCast(Res, Ptr->getType());
924 }
Chris Lattner17c0cb02008-01-03 06:36:51 +0000925
926 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000927}
928
929Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
930 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
931 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner660e31d2007-08-24 21:00:35 +0000932
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000933 const QualType LHSType = Ops.E->getLHS()->getType();
934 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType();
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000935 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
936 // pointer - int
937 Value *Idx = Ops.RHS;
938 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
939 if (Width < CGF.LLVMPointerWidth) {
940 // Zero or sign extend the pointer value based on whether the index is
941 // signed or not.
942 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
943 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
944 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
945 else
946 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
947 }
948 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
949
950 // FIXME: The pointer could point to a VLA.
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +0000951
952 // Explicitly handle GNU void* and function pointer arithmetic
953 // extensions. The GNU void* casts amount to no-ops since our
954 // void* type is i8*, but this is future proof.
955 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
956 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
957 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
958 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
959 return Builder.CreateBitCast(Res, Ops.LHS->getType());
960 }
961
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000962 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000963 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000964 // pointer - pointer
965 Value *LHS = Ops.LHS;
966 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +0000967
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000968 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +0000969
Chris Lattner6d2e3492009-02-11 07:21:43 +0000970 // Handle GCC extension for pointer arithmetic on void* and function pointer
971 // types.
972 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000973 ElementSize = 1;
974 } else {
975 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
976 }
977
978 const llvm::Type *ResultType = ConvertType(Ops.Ty);
979 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
980 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
981 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
982
Chris Lattner6d2e3492009-02-11 07:21:43 +0000983 // Optimize out the shift for element size of 1.
984 if (ElementSize == 1)
985 return BytesBetween;
986
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000987 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
988 // remainder. As such, we handle common power-of-two cases here to generate
989 // better code. See PR2247.
990 if (llvm::isPowerOf2_64(ElementSize)) {
991 Value *ShAmt =
992 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
993 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
994 }
995
996 // Otherwise, do a full sdiv.
997 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
998 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000999 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001000}
1001
1002Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1003 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1004 // RHS to the same size as the LHS.
1005 Value *RHS = Ops.RHS;
1006 if (Ops.LHS->getType() != RHS->getType())
1007 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1008
1009 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1010}
1011
1012Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1013 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1014 // RHS to the same size as the LHS.
1015 Value *RHS = Ops.RHS;
1016 if (Ops.LHS->getType() != RHS->getType())
1017 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1018
Chris Lattner660e31d2007-08-24 21:00:35 +00001019 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +00001020 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1021 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1022}
1023
1024Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1025 unsigned SICmpOpc, unsigned FCmpOpc) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001026 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001027 QualType LHSTy = E->getLHS()->getType();
Nate Begeman1591bc52008-07-25 20:16:05 +00001028 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001029 Value *LHS = Visit(E->getLHS());
1030 Value *RHS = Visit(E->getRHS());
1031
1032 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman1591bc52008-07-25 20:16:05 +00001033 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001034 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +00001035 } else if (LHSTy->isSignedIntegerType()) {
1036 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001037 LHS, RHS, "cmp");
1038 } else {
Eli Friedman850ea372008-05-29 15:09:15 +00001039 // Unsigned integers and pointers.
1040 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001041 LHS, RHS, "cmp");
1042 }
Nate Begeman1591bc52008-07-25 20:16:05 +00001043 } else if (LHSTy->isVectorType()) {
1044 Value *LHS = Visit(E->getLHS());
1045 Value *RHS = Visit(E->getRHS());
1046
1047 if (LHS->getType()->isFPOrFPVector()) {
1048 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1049 LHS, RHS, "cmp");
1050 } else if (LHSTy->isUnsignedIntegerType()) {
1051 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc,
1052 LHS, RHS, "cmp");
1053 } else {
1054 // Signed integers and pointers.
1055 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc,
1056 LHS, RHS, "cmp");
1057 }
1058 return Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001059 } else {
1060 // Complex Comparison: can only be an equality comparison.
1061 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1062 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1063
Chris Lattnerc154ac12008-07-26 22:37:01 +00001064 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001065
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001066 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001067 if (CETy->isRealFloatingType()) {
1068 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1069 LHS.first, RHS.first, "cmp.r");
1070 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1071 LHS.second, RHS.second, "cmp.i");
1072 } else {
1073 // Complex comparisons can only be equality comparisons. As such, signed
1074 // and unsigned opcodes are the same.
1075 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1076 LHS.first, RHS.first, "cmp.r");
1077 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1078 LHS.second, RHS.second, "cmp.i");
1079 }
1080
1081 if (E->getOpcode() == BinaryOperator::EQ) {
1082 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1083 } else {
1084 assert(E->getOpcode() == BinaryOperator::NE &&
1085 "Complex comparison other than == or != ?");
1086 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1087 }
1088 }
Nuno Lopes92577002009-01-11 23:22:37 +00001089
1090 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001091}
1092
1093Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1094 LValue LHS = EmitLValue(E->getLHS());
1095 Value *RHS = Visit(E->getRHS());
1096
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001097 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar2710fc92008-11-19 11:54:05 +00001098 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1099 // 'An assignment expression has the value of the left operand after
1100 // the assignment...'.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001101 // FIXME: Volatility!
Eli Friedmanf9b930c2008-05-25 14:13:57 +00001102 if (LHS.isBitfield())
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001103 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1104 &RHS);
1105 else
1106 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbare6c31752008-08-29 08:11:39 +00001107
Chris Lattner9fba49a2007-08-24 05:35:26 +00001108 // Return the RHS.
1109 return RHS;
1110}
1111
1112Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001113 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1114 // If we have 1 && X, just emit X without inserting the control flow.
1115 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1116 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001117 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1118 // ZExt result to int.
1119 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1120 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001121
1122 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1123 if (!CGF.ContainsLabel(E->getRHS()))
1124 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001125 }
1126
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001127 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1128 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner715c2a72008-11-12 08:26:50 +00001129
Chris Lattner7f80bb32008-11-12 08:38:24 +00001130 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1131 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1132
1133 // Any edges into the ContBlock are now from an (indeterminate number of)
1134 // edges from this first condition. All of these values will be false. Start
1135 // setting up the PHI node in the Cont Block for this.
1136 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1137 PN->reserveOperandSpace(2); // Normal case, two inputs.
1138 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1139 PI != PE; ++PI)
1140 PN->addIncoming(llvm::ConstantInt::getFalse(), *PI);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001141
1142 CGF.EmitBlock(RHSBlock);
1143 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1144
1145 // Reaquire the RHS block, as there may be subblocks inserted.
1146 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f80bb32008-11-12 08:38:24 +00001147
1148 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1149 // into the phi node for the edge with the value of RHSCond.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001150 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001151 PN->addIncoming(RHSCond, RHSBlock);
1152
1153 // ZExt result to int.
1154 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1155}
1156
1157Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001158 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1159 // If we have 0 || X, just emit X without inserting the control flow.
1160 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1161 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001162 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1163 // ZExt result to int.
1164 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1165 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001166
Eli Friedmanea137cd2008-12-02 16:02:46 +00001167 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner715c2a72008-11-12 08:26:50 +00001168 if (!CGF.ContainsLabel(E->getRHS()))
Eli Friedmanea137cd2008-12-02 16:02:46 +00001169 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001170 }
1171
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001172 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1173 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001174
Chris Lattner7f80bb32008-11-12 08:38:24 +00001175 // Branch on the LHS first. If it is true, go to the success (cont) block.
1176 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1177
1178 // Any edges into the ContBlock are now from an (indeterminate number of)
1179 // edges from this first condition. All of these values will be true. Start
1180 // setting up the PHI node in the Cont Block for this.
1181 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1182 PN->reserveOperandSpace(2); // Normal case, two inputs.
1183 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1184 PI != PE; ++PI)
1185 PN->addIncoming(llvm::ConstantInt::getTrue(), *PI);
1186
1187 // Emit the RHS condition as a bool value.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001188 CGF.EmitBlock(RHSBlock);
1189 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1190
1191 // Reaquire the RHS block, as there may be subblocks inserted.
1192 RHSBlock = Builder.GetInsertBlock();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001193
Chris Lattner7f80bb32008-11-12 08:38:24 +00001194 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1195 // into the phi node for the edge with the value of RHSCond.
1196 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001197 PN->addIncoming(RHSCond, RHSBlock);
1198
1199 // ZExt result to int.
1200 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1201}
1202
1203Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1204 CGF.EmitStmt(E->getLHS());
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001205 CGF.EnsureInsertPoint();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001206 return Visit(E->getRHS());
1207}
1208
1209//===----------------------------------------------------------------------===//
1210// Other Operators
1211//===----------------------------------------------------------------------===//
1212
Chris Lattner504a5282008-11-12 08:55:54 +00001213/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1214/// expression is cheap enough and side-effect-free enough to evaluate
1215/// unconditionally instead of conditionally. This is used to convert control
1216/// flow into selects in some cases.
1217static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1218 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1219 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1220
1221 // TODO: Allow anything we can constant fold to an integer or fp constant.
1222 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1223 isa<FloatingLiteral>(E))
1224 return true;
1225
1226 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1227 // X and Y are local variables.
1228 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1229 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1230 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1231 return true;
1232
1233 return false;
1234}
1235
1236
Chris Lattner9fba49a2007-08-24 05:35:26 +00001237Value *ScalarExprEmitter::
1238VisitConditionalOperator(const ConditionalOperator *E) {
Chris Lattner3d6606b2008-11-12 08:04:58 +00001239 // If the condition constant folds and can be elided, try to avoid emitting
1240 // the condition and the dead arm.
1241 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattner044bffc2008-11-11 18:56:45 +00001242 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001243 if (Cond == -1)
Chris Lattner044bffc2008-11-11 18:56:45 +00001244 std::swap(Live, Dead);
Chris Lattner3d6606b2008-11-12 08:04:58 +00001245
1246 // If the dead side doesn't have labels we need, and if the Live side isn't
1247 // the gnu missing ?: extension (which we could handle, but don't bother
1248 // to), just emit the Live part.
1249 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1250 Live) // Live part isn't missing.
1251 return Visit(Live);
Chris Lattner044bffc2008-11-11 18:56:45 +00001252 }
1253
Chris Lattner504a5282008-11-12 08:55:54 +00001254
1255 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1256 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner1f11af22008-11-16 06:16:27 +00001257 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner504a5282008-11-12 08:55:54 +00001258 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1259 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1260 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1261 llvm::Value *LHS = Visit(E->getLHS());
1262 llvm::Value *RHS = Visit(E->getRHS());
1263 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1264 }
1265
1266
Daniel Dunbarb23e9922008-11-12 10:13:37 +00001267 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1268 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001269 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner67e22462008-11-12 08:08:13 +00001270 Value *CondVal = 0;
Chris Lattner3d6606b2008-11-12 08:04:58 +00001271
Chris Lattner86031712009-02-13 23:35:32 +00001272 // If we don't have the GNU missing condition extension, emit a branch on
1273 // bool the normal way.
1274 if (E->getLHS()) {
1275 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1276 // the branch on bool.
1277 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1278 } else {
1279 // Otherwise, for the ?: extension, evaluate the conditional and then
1280 // convert it to bool the hard way. We do this explicitly because we need
1281 // the unconverted value for the missing middle value of the ?:.
Chris Lattner67e22462008-11-12 08:08:13 +00001282 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner86031712009-02-13 23:35:32 +00001283
1284 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1285 // if there are no extra uses (an optimization). Inhibit this by making an
1286 // extra dead use, because we're going to add a use of CondVal later. We
1287 // don't use the builder for this, because we don't want it to get optimized
1288 // away. This leaves dead code, but the ?: extension isn't common.
1289 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1290 Builder.GetInsertBlock());
1291
Chris Lattner67e22462008-11-12 08:08:13 +00001292 Value *CondBoolVal =
1293 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1294 CGF.getContext().BoolTy);
1295 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner67e22462008-11-12 08:08:13 +00001296 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001297
1298 CGF.EmitBlock(LHSBlock);
1299
1300 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001301 Value *LHS;
1302 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001303 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001304 else // Perform promotions, to handle cases like "short ?: int"
1305 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1306
Chris Lattner9fba49a2007-08-24 05:35:26 +00001307 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001308 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001309
1310 CGF.EmitBlock(RHSBlock);
1311
Eli Friedmance8d7032008-05-16 20:38:39 +00001312 Value *RHS = Visit(E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001313 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001314 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001315
1316 CGF.EmitBlock(ContBlock);
1317
Nuno Lopesb62ff242008-06-04 19:15:45 +00001318 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001319 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1320 return 0;
1321 }
1322
Chris Lattner9fba49a2007-08-24 05:35:26 +00001323 // Create a PHI node for the real part.
1324 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1325 PN->reserveOperandSpace(2);
1326 PN->addIncoming(LHS, LHSBlock);
1327 PN->addIncoming(RHS, RHSBlock);
1328 return PN;
1329}
1330
1331Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001332 // Emit the LHS or RHS as appropriate.
Devang Patel0f2a8fb2007-10-30 20:59:40 +00001333 return
1334 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001335}
1336
Chris Lattner307da022007-11-30 17:56:23 +00001337Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman8f5e8782009-01-20 17:46:04 +00001338 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson285611e2008-11-04 05:30:00 +00001339 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1340
1341 // If EmitVAArg fails, we fall back to the LLVM instruction.
1342 if (!ArgPtr)
1343 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1344
1345 // FIXME: volatile?
1346 return Builder.CreateLoad(ArgPtr);
Anders Carlsson36760332007-10-15 20:28:48 +00001347}
1348
Mike Stump4eb81dc2009-02-12 18:29:15 +00001349Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stumpf1711822009-02-25 23:33:13 +00001350 llvm::Value *V = CGF.BuildBlockLiteralTmp(BE);
1351 return V;
Mike Stump4eb81dc2009-02-12 18:29:15 +00001352}
1353
Chris Lattner9fba49a2007-08-24 05:35:26 +00001354//===----------------------------------------------------------------------===//
1355// Entry Point into this File
1356//===----------------------------------------------------------------------===//
1357
1358/// EmitComplexExpr - Emit the computation of the specified expression of
1359/// complex type, ignoring the result.
1360Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1361 assert(E && !hasAggregateLLVMType(E->getType()) &&
1362 "Invalid scalar expression to emit");
1363
1364 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1365}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001366
1367/// EmitScalarConversion - Emit a conversion from the specified type to the
1368/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001369Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1370 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001371 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1372 "Invalid scalar expression to emit");
1373 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1374}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001375
1376/// EmitComplexToScalarConversion - Emit a conversion from the specified
1377/// complex type to the specified destination type, where the destination
1378/// type is an LLVM scalar type.
1379Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1380 QualType SrcTy,
1381 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001382 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001383 "Invalid complex -> scalar conversion");
1384 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1385 DstTy);
1386}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001387
1388Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1389 assert(V1->getType() == V2->getType() &&
1390 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001391 unsigned NumElements =
1392 cast<llvm::VectorType>(V1->getType())->getNumElements();
1393
1394 va_list va;
1395 va_start(va, V2);
1396
1397 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001398 for (unsigned i = 0; i < NumElements; i++) {
1399 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001400 assert(n >= 0 && n < (int)NumElements * 2 &&
1401 "Vector shuffle index out of bounds!");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001402 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1403 }
1404
1405 const char *Name = va_arg(va, const char *);
1406 va_end(va);
1407
1408 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1409
1410 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1411}
1412
Anders Carlsson68b8be92007-12-15 21:23:30 +00001413llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001414 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001415 llvm::Value *Vec
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001416 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001417
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001418 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001419 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Anders Carlsson68b8be92007-12-15 21:23:30 +00001420 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001421 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001422 }
1423
1424 return Vec;
1425}