blob: 129b4c7846ef75b2b4ba394cef63b95dcf434ea7 [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner7f02f722007-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 Dunbarde7fb842008-08-11 05:00:27 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000017#include "clang/AST/DeclObjC.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000019#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000020#include "llvm/Constants.h"
21#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000022#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000023#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000024#include "llvm/Module.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000025#include "llvm/Support/Compiler.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000026#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000028#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000029
Chris Lattner7f02f722007-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 Lattner1f1ded92007-08-24 21:00:35 +000041 QualType Ty; // Computation Type.
Chris Lattner7f02f722007-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 Dunbar45d196b2008-11-01 01:53:16 +000049 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000050 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000051 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000052public:
53
Mike Stump7f79f9b2009-05-29 15:46:01 +000054 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Owen Andersona1cf15f2009-07-14 23:10:40 +000055 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
56 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000057 }
Chris Lattner7f02f722007-08-24 05:35:26 +000058
59 //===--------------------------------------------------------------------===//
60 // Utilities
61 //===--------------------------------------------------------------------===//
62
Mike Stump7f79f9b2009-05-29 15:46:01 +000063 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000064 bool I = IgnoreResultAssign;
65 IgnoreResultAssign = false;
66 return I;
67 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000068
Chris Lattner7f02f722007-08-24 05:35:26 +000069 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
70 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
71
72 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000073 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000074 }
75
76 /// EmitLoadOfLValue - Given an expression with complex type that represents a
77 /// value l-value, this method emits the address of the l-value, then loads
78 /// and returns the result.
79 Value *EmitLoadOfLValue(const Expr *E) {
Chris Lattner7f02f722007-08-24 05:35:26 +000080 return EmitLoadOfLValue(EmitLValue(E), E->getType());
81 }
82
Chris Lattner9abc84e2007-08-26 16:42:57 +000083 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000084 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000085 Value *EmitConversionToBool(Value *Src, QualType DstTy);
86
Chris Lattner3707b252007-08-26 06:48:56 +000087 /// EmitScalarConversion - Emit a conversion from the specified type to the
88 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000089 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
90
91 /// EmitComplexToScalarConversion - Emit a conversion from the specified
92 /// complex type to the specified destination type, where the destination
93 /// type is an LLVM scalar type.
94 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
95 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +000096
Chris Lattner7f02f722007-08-24 05:35:26 +000097 //===--------------------------------------------------------------------===//
98 // Visitor Methods
99 //===--------------------------------------------------------------------===//
100
101 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000102 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000103 assert(0 && "Stmt can't have complex result type!");
104 return 0;
105 }
106 Value *VisitExpr(Expr *S);
107 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
108
109 // Leaves.
110 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000111 return VMContext.getConstantInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000112 }
113 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000114 return VMContext.getConstantFP(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000115 }
116 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000117 return VMContext.getConstantInt(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000118 }
Nate Begemane7579b52007-11-15 05:40:03 +0000119 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000120 return VMContext.getConstantInt(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000121 }
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000122 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000123 return VMContext.getNullValue(ConvertType(E->getType()));
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000124 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000125 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000126 return VMContext.getNullValue(ConvertType(E->getType()));
Anders Carlsson3f704562008-12-21 22:39:40 +0000127 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000128 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000129 return VMContext.getConstantInt(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000130 CGF.getContext().typesAreCompatible(
131 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000132 }
Sebastian Redl05189992008-11-11 17:56:53 +0000133 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000134 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbar54d19092008-08-16 01:41:47 +0000135 llvm::Value *V =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000136 VMContext.getConstantInt(llvm::Type::Int32Ty,
Daniel Dunbar54d19092008-08-16 01:41:47 +0000137 CGF.GetIDForAddrOfLabel(E->getLabel()));
138
139 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000140 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000141
142 // l-values.
143 Value *VisitDeclRefExpr(DeclRefExpr *E) {
144 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
Owen Andersona1cf15f2009-07-14 23:10:40 +0000145 return VMContext.getConstantInt(EC->getInitVal());
Chris Lattner7f02f722007-08-24 05:35:26 +0000146 return EmitLoadOfLValue(E);
147 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000148 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
149 return CGF.EmitObjCSelectorExpr(E);
150 }
151 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
152 return CGF.EmitObjCProtocolExpr(E);
153 }
154 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
155 return EmitLoadOfLValue(E);
156 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000157 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000158 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000159 }
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000160 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
161 return EmitLoadOfLValue(E);
162 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000163 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
164 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000165 }
166
Chris Lattner7f02f722007-08-24 05:35:26 +0000167 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000168 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000169 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begeman213541a2008-04-18 23:10:10 +0000170 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000171 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
172 return EmitLoadOfLValue(E);
173 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000174 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000175 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
176 return EmitLValue(E).getAddress();
177 }
178
Chris Lattnerd9f69102008-08-10 01:53:14 +0000179 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel35634f52007-10-24 17:18:43 +0000180
181 Value *VisitInitListExpr(InitListExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000182 bool Ignore = TestAndClearIgnoreResultAssign();
183 (void)Ignore;
184 assert (Ignore == false && "init list ignored");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000185 unsigned NumInitElements = E->getNumInits();
186
Douglas Gregora9c87802009-01-29 19:42:23 +0000187 if (E->hadArrayRangeDesignator()) {
188 CGF.ErrorUnsupported(E, "GNU array range designator extension");
189 }
190
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000191 const llvm::VectorType *VType =
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000192 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
193
194 // We have a scalar in braces. Just use the first element.
195 if (!VType)
196 return Visit(E->getInit(0));
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000197
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000198 unsigned NumVectorElements = VType->getNumElements();
199 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000200
201 // Emit individual vector element stores.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000202 llvm::Value *V = VMContext.getUndef(VType);
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000203
Anders Carlsson222d2c82007-12-18 02:45:33 +0000204 // Emit initializers
205 unsigned i;
206 for (i = 0; i < NumInitElements; ++i) {
Devang Patela83cc332007-10-24 18:05:48 +0000207 Value *NewV = Visit(E->getInit(i));
Owen Andersona1cf15f2009-07-14 23:10:40 +0000208 Value *Idx = VMContext.getConstantInt(llvm::Type::Int32Ty, i);
Devang Patela83cc332007-10-24 18:05:48 +0000209 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel35634f52007-10-24 17:18:43 +0000210 }
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000211
212 // Emit remaining default initializers
213 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000214 Value *Idx = VMContext.getConstantInt(llvm::Type::Int32Ty, i);
215 llvm::Value *NewV = VMContext.getNullValue(ElementType);
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000216 V = Builder.CreateInsertElement(V, NewV, Idx);
217 }
218
Devang Patela83cc332007-10-24 18:05:48 +0000219 return V;
Devang Patel35634f52007-10-24 17:18:43 +0000220 }
Chris Lattner04421082008-04-08 04:40:51 +0000221
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000222 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000223 return VMContext.getNullValue(ConvertType(E->getType()));
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000224 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000225 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmanc62aad82009-04-20 03:54:15 +0000226 Value *VisitCastExpr(const CastExpr *E) {
227 // Make sure to evaluate VLA bounds now so that we have them for later.
228 if (E->getType()->isVariablyModifiedType())
229 CGF.EmitVLASize(E->getType());
230
Chris Lattner7f02f722007-08-24 05:35:26 +0000231 return EmitCastExpr(E->getSubExpr(), E->getType());
232 }
233 Value *EmitCastExpr(const Expr *E, QualType T);
234
235 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000236 if (E->getCallReturnType()->isReferenceType())
237 return EmitLoadOfLValue(E);
238
Chris Lattner9b655512007-08-31 22:49:20 +0000239 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000240 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000241
Chris Lattner33793202007-08-31 22:09:40 +0000242 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000243
Mike Stumpa99038c2009-02-28 09:07:16 +0000244 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattner33793202007-08-31 22:09:40 +0000245
Chris Lattner7f02f722007-08-24 05:35:26 +0000246 // Unary Operators.
247 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
248 Value *VisitUnaryPostDec(const UnaryOperator *E) {
249 return VisitPrePostIncDec(E, false, false);
250 }
251 Value *VisitUnaryPostInc(const UnaryOperator *E) {
252 return VisitPrePostIncDec(E, true, false);
253 }
254 Value *VisitUnaryPreDec(const UnaryOperator *E) {
255 return VisitPrePostIncDec(E, false, true);
256 }
257 Value *VisitUnaryPreInc(const UnaryOperator *E) {
258 return VisitPrePostIncDec(E, true, true);
259 }
260 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
261 return EmitLValue(E->getSubExpr()).getAddress();
262 }
263 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
264 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000265 // This differs from gcc, though, most likely due to a bug in gcc.
266 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000267 return Visit(E->getSubExpr());
268 }
269 Value *VisitUnaryMinus (const UnaryOperator *E);
270 Value *VisitUnaryNot (const UnaryOperator *E);
271 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000272 Value *VisitUnaryReal (const UnaryOperator *E);
273 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000274 Value *VisitUnaryExtension(const UnaryOperator *E) {
275 return Visit(E->getSubExpr());
276 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000277 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000278
279 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000280 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
281 return Visit(DAE->getExpr());
282 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000283 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
284 return CGF.LoadCXXThis();
285 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000286
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000287 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlsson30824632009-05-31 00:09:15 +0000288 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000289 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000290 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
291 return CGF.EmitCXXNewExpr(E);
292 }
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000293
Chris Lattner7f02f722007-08-24 05:35:26 +0000294 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stump035cf892009-04-02 18:15:54 +0000296 if (CGF.getContext().getLangOptions().OverflowChecking
297 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +0000298 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +0000299 if (Ops.LHS->getType()->isFPOrFPVector())
300 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000301 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
302 }
Mike Stump2add4732009-04-01 20:28:16 +0000303 /// Create a binary op that checks for overflow.
304 /// Currently only supports +, - and *.
305 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner7f02f722007-08-24 05:35:26 +0000306 Value *EmitDiv(const BinOpInfo &Ops);
307 Value *EmitRem(const BinOpInfo &Ops);
308 Value *EmitAdd(const BinOpInfo &Ops);
309 Value *EmitSub(const BinOpInfo &Ops);
310 Value *EmitShl(const BinOpInfo &Ops);
311 Value *EmitShr(const BinOpInfo &Ops);
312 Value *EmitAnd(const BinOpInfo &Ops) {
313 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
314 }
315 Value *EmitXor(const BinOpInfo &Ops) {
316 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
317 }
318 Value *EmitOr (const BinOpInfo &Ops) {
319 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
320 }
321
Chris Lattner1f1ded92007-08-24 21:00:35 +0000322 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000323 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000324 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
325
326 // Binary operators and binary compound assignment operators.
327#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000328 Value *VisitBin ## OP(const BinaryOperator *E) { \
329 return Emit ## OP(EmitBinOps(E)); \
330 } \
331 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
332 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000333 }
334 HANDLEBINOP(Mul);
335 HANDLEBINOP(Div);
336 HANDLEBINOP(Rem);
337 HANDLEBINOP(Add);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000338 HANDLEBINOP(Sub);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000339 HANDLEBINOP(Shl);
340 HANDLEBINOP(Shr);
341 HANDLEBINOP(And);
342 HANDLEBINOP(Xor);
343 HANDLEBINOP(Or);
344#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000345
Chris Lattner7f02f722007-08-24 05:35:26 +0000346 // Comparisons.
347 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
348 unsigned SICmpOpc, unsigned FCmpOpc);
349#define VISITCOMP(CODE, UI, SI, FP) \
350 Value *VisitBin##CODE(const BinaryOperator *E) { \
351 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
352 llvm::FCmpInst::FP); }
353 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
354 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
355 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
356 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
357 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
358 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
359#undef VISITCOMP
360
361 Value *VisitBinAssign (const BinaryOperator *E);
362
363 Value *VisitBinLAnd (const BinaryOperator *E);
364 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000365 Value *VisitBinComma (const BinaryOperator *E);
366
367 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000368 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000369 Value *VisitConditionalOperator(const ConditionalOperator *CO);
370 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000371 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000372 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
373 return CGF.EmitObjCStringLiteral(E);
374 }
375};
376} // end anonymous namespace.
377
378//===----------------------------------------------------------------------===//
379// Utilities
380//===----------------------------------------------------------------------===//
381
Chris Lattner9abc84e2007-08-26 16:42:57 +0000382/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000383/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000384Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
385 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
386
387 if (SrcType->isRealFloatingType()) {
388 // Compare against 0.0 for fp scalars.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000389 llvm::Value *Zero = VMContext.getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000390 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
391 }
392
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000393 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000394 "Unknown scalar type to convert");
395
396 // Because of the type rules of C, we often end up computing a logical value,
397 // then zero extending it to int, then wanting it as a logical value again.
398 // Optimize this common case.
399 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
400 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
401 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000402 // If there aren't any more uses, zap the instruction to save space.
403 // Note that there can be more uses, for example if this
404 // is the result of an assignment.
405 if (ZI->use_empty())
406 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000407 return Result;
408 }
409 }
410
411 // Compare against an integer or pointer null.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000412 llvm::Value *Zero = VMContext.getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000413 return Builder.CreateICmpNE(Src, Zero, "tobool");
414}
415
Chris Lattner3707b252007-08-26 06:48:56 +0000416/// EmitScalarConversion - Emit a conversion from the specified type to the
417/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000418Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
419 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000420 SrcType = CGF.getContext().getCanonicalType(SrcType);
421 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000422 if (SrcType == DstType) return Src;
Chris Lattnercf289082007-08-26 07:21:11 +0000423
424 if (DstType->isVoidType()) return 0;
Chris Lattner3707b252007-08-26 06:48:56 +0000425
426 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000427 if (DstType->isBooleanType())
428 return EmitConversionToBool(Src, SrcType);
Chris Lattner3707b252007-08-26 06:48:56 +0000429
430 const llvm::Type *DstTy = ConvertType(DstType);
431
432 // Ignore conversions like int -> uint.
433 if (Src->getType() == DstTy)
434 return Src;
435
Daniel Dunbar270cc662008-08-25 09:51:32 +0000436 // Handle pointer conversions next: pointers can only be converted
437 // to/from other pointers and integers. Check for pointer types in
438 // terms of LLVM, as some native types (like Obj-C id) may map to a
439 // pointer type.
440 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000441 // The source value may be an integer, or a pointer.
442 if (isa<llvm::PointerType>(Src->getType()))
443 return Builder.CreateBitCast(Src, DstTy, "conv");
444 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000445 // First, convert to the correct width so that we control the kind of
446 // extension.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000447 const llvm::Type *MiddleTy = VMContext.getIntegerType(CGF.LLVMPointerWidth);
Eli Friedman25615422009-03-04 04:02:35 +0000448 bool InputSigned = SrcType->isSignedIntegerType();
449 llvm::Value* IntResult =
450 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
451 // Then, cast to pointer.
452 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000453 }
454
Daniel Dunbar270cc662008-08-25 09:51:32 +0000455 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000456 // Must be an ptr to int cast.
457 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000458 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000459 }
460
Nate Begeman213541a2008-04-18 23:10:10 +0000461 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000462 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
463 // Cast the scalar to element type
464 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
465 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
466
467 // Insert the element in element zero of an undef vector
Owen Andersona1cf15f2009-07-14 23:10:40 +0000468 llvm::Value *UnV = VMContext.getUndef(DstTy);
469 llvm::Value *Idx = VMContext.getConstantInt(llvm::Type::Int32Ty, 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000470 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
471
472 // Splat the element across to all elements
473 llvm::SmallVector<llvm::Constant*, 16> Args;
474 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
475 for (unsigned i = 0; i < NumElements; i++)
Owen Andersona1cf15f2009-07-14 23:10:40 +0000476 Args.push_back(VMContext.getConstantInt(llvm::Type::Int32Ty, 0));
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000477
Owen Andersona1cf15f2009-07-14 23:10:40 +0000478 llvm::Constant *Mask = VMContext.getConstantVector(&Args[0], NumElements);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000479 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
480 return Yay;
481 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000482
Chris Lattner3b1ae002008-02-02 04:51:41 +0000483 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000484 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000485 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000486 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000487
Chris Lattner3707b252007-08-26 06:48:56 +0000488 // Finally, we have the arithmetic types: real int/float.
489 if (isa<llvm::IntegerType>(Src->getType())) {
490 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000491 if (isa<llvm::IntegerType>(DstTy))
492 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
493 else if (InputSigned)
494 return Builder.CreateSIToFP(Src, DstTy, "conv");
495 else
496 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000497 }
498
499 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
500 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000501 if (DstType->isSignedIntegerType())
502 return Builder.CreateFPToSI(Src, DstTy, "conv");
503 else
504 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000505 }
506
507 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000508 if (DstTy->getTypeID() < Src->getType()->getTypeID())
509 return Builder.CreateFPTrunc(Src, DstTy, "conv");
510 else
511 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000512}
513
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000514/// EmitComplexToScalarConversion - Emit a conversion from the specified
515/// complex type to the specified destination type, where the destination
516/// type is an LLVM scalar type.
517Value *ScalarExprEmitter::
518EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
519 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000520 // Get the source element type.
Chris Lattner96196622008-07-26 22:37:01 +0000521 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnered70f0a2007-08-26 16:52:28 +0000522
523 // Handle conversions to bool first, they are special: comparisons against 0.
524 if (DstTy->isBooleanType()) {
525 // Complex != 0 -> (Real != 0) | (Imag != 0)
526 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
527 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
528 return Builder.CreateOr(Src.first, Src.second, "tobool");
529 }
530
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000531 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
532 // the imaginary part of the complex value is discarded and the value of the
533 // real part is converted according to the conversion rules for the
534 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000535 return EmitScalarConversion(Src.first, SrcTy, DstTy);
536}
537
538
Chris Lattner7f02f722007-08-24 05:35:26 +0000539//===----------------------------------------------------------------------===//
540// Visitor Methods
541//===----------------------------------------------------------------------===//
542
543Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000544 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000545 if (E->getType()->isVoidType())
546 return 0;
Owen Andersona1cf15f2009-07-14 23:10:40 +0000547 return VMContext.getUndef(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000548}
549
Eli Friedmand38617c2008-05-14 19:38:39 +0000550Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
551 llvm::SmallVector<llvm::Constant*, 32> indices;
552 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
553 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
554 }
555 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
556 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Owen Andersona1cf15f2009-07-14 23:10:40 +0000557 Value* SV = VMContext.getConstantVector(indices.begin(), indices.size());
Eli Friedmand38617c2008-05-14 19:38:39 +0000558 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
559}
560
Chris Lattner7f02f722007-08-24 05:35:26 +0000561Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000562 TestAndClearIgnoreResultAssign();
563
Chris Lattner7f02f722007-08-24 05:35:26 +0000564 // Emit subscript expressions in rvalue context's. For most cases, this just
565 // loads the lvalue formed by the subscript expr. However, we have to be
566 // careful, because the base of a vector subscript is occasionally an rvalue,
567 // so we can't get it as an lvalue.
568 if (!E->getBase()->getType()->isVectorType())
569 return EmitLoadOfLValue(E);
570
571 // Handle the vector case. The base must be a vector, the index must be an
572 // integer value.
573 Value *Base = Visit(E->getBase());
574 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000575 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Eli Friedman515ff5a2009-03-28 03:27:06 +0000576 Idx = Builder.CreateIntCast(Idx, llvm::Type::Int32Ty, IdxSigned,
577 "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000578 return Builder.CreateExtractElement(Base, Idx, "vecext");
579}
580
581/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
582/// also handle things like function to pointer-to-function decay, and array to
583/// pointer decay.
584Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
585 const Expr *Op = E->getSubExpr();
586
587 // If this is due to array->pointer conversion, emit the array expression as
588 // an l-value.
589 if (Op->getType()->isArrayType()) {
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000590 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000591
Eli Friedmandaa24a22009-03-28 02:45:41 +0000592 // Note that VLA pointers are always decayed, so we don't need to do
593 // anything here.
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000594 if (!Op->getType()->isVariableArrayType()) {
595 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
596 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
597 ->getElementType()) &&
598 "Expected pointer to array");
599 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar662174c82008-08-29 17:28:43 +0000600 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000601
602 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattnerf31627f2008-07-23 06:31:27 +0000603 // types as well (e.g. void*) and can be implicitly converted to integer.
604 const llvm::Type *DestTy = ConvertType(E->getType());
605 if (V->getType() != DestTy) {
606 if (isa<llvm::PointerType>(DestTy))
607 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
608 else {
609 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
610 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
611 }
612 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000613 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +0000614 }
Eli Friedmandaa24a22009-03-28 02:45:41 +0000615
Chris Lattner7f02f722007-08-24 05:35:26 +0000616 return EmitCastExpr(Op, E->getType());
617}
618
619
620// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
621// have to handle a more broad range of conversions than explicit casts, as they
622// handle things like function to ptr-to-function decay etc.
623Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000624 if (!DestTy->isVoidType())
625 TestAndClearIgnoreResultAssign();
626
Chris Lattner58a2e942007-08-26 07:26:12 +0000627 // Handle cases where the source is an non-complex type.
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000628
629 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000630 Value *Src = Visit(const_cast<Expr*>(E));
631
Chris Lattner3707b252007-08-26 06:48:56 +0000632 // Use EmitScalarConversion to perform the conversion.
633 return EmitScalarConversion(Src, E->getType(), DestTy);
634 }
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000635
Chris Lattner9b2dc282008-04-04 16:54:41 +0000636 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000637 // Handle cases where the source is a complex type.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000638 bool IgnoreImag = true;
639 bool IgnoreImagAssign = true;
640 bool IgnoreReal = IgnoreResultAssign;
641 bool IgnoreRealAssign = IgnoreResultAssign;
642 if (DestTy->isBooleanType())
643 IgnoreImagAssign = IgnoreImag = false;
644 else if (DestTy->isVoidType()) {
645 IgnoreReal = IgnoreImag = false;
646 IgnoreRealAssign = IgnoreImagAssign = true;
647 }
648 CodeGenFunction::ComplexPairTy V
649 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
650 IgnoreImagAssign);
651 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000652 }
Chris Lattner10b00cf2007-08-26 07:16:41 +0000653
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000654 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
655 // evaluate the result and return.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000656 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000657 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +0000658}
659
Chris Lattner33793202007-08-31 22:09:40 +0000660Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +0000661 return CGF.EmitCompoundStmt(*E->getSubStmt(),
662 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +0000663}
664
Mike Stumpa99038c2009-02-28 09:07:16 +0000665Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
666 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stump4e7a1f72009-02-21 20:00:35 +0000667}
Chris Lattner33793202007-08-31 22:09:40 +0000668
Chris Lattner7f02f722007-08-24 05:35:26 +0000669//===----------------------------------------------------------------------===//
670// Unary Operators
671//===----------------------------------------------------------------------===//
672
673Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattnerdfce2a52007-08-24 16:24:49 +0000674 bool isInc, bool isPre) {
Chris Lattner7f02f722007-08-24 05:35:26 +0000675 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedmanf52bbeb2009-03-23 03:00:06 +0000676 QualType ValTy = E->getSubExpr()->getType();
677 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000678
679 int AmountVal = isInc ? 1 : -1;
Eli Friedmandaa24a22009-03-28 02:45:41 +0000680
681 if (ValTy->isPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +0000682 ValTy->getAsPointerType()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +0000683 // The amount of the addition/subtraction needs to account for the VLA size
684 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
685 }
686
Chris Lattner7f02f722007-08-24 05:35:26 +0000687 Value *NextVal;
Chris Lattner8cc9d082009-03-18 04:25:13 +0000688 if (const llvm::PointerType *PT =
689 dyn_cast<llvm::PointerType>(InVal->getType())) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000690 llvm::Constant *Inc =
691 VMContext.getConstantInt(llvm::Type::Int32Ty, AmountVal);
Chris Lattner8cc9d082009-03-18 04:25:13 +0000692 if (!isa<llvm::FunctionType>(PT->getElementType())) {
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000693 QualType PTEE = ValTy->getPointeeType();
694 if (const ObjCInterfaceType *OIT =
695 dyn_cast<ObjCInterfaceType>(PTEE)) {
696 // Handle interface types, which are not represented with a concrete type.
697 int size = CGF.getContext().getTypeSize(OIT) / 8;
698 if (!isInc)
699 size = -size;
700 Inc = VMContext.getConstantInt(Inc->getType(), size);
701 const llvm::Type *i8Ty =
702 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
703 InVal = Builder.CreateBitCast(InVal, i8Ty);
704 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
705 llvm::Value *lhs = LV.getAddress();
706 lhs = Builder.CreateBitCast(lhs, VMContext.getPointerTypeUnqual(i8Ty));
707 LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(),
708 CGF.getContext().getObjCGCAttrKind(ValTy));
709 }
710 else
711 NextVal = Builder.CreateGEP(InVal, Inc, "ptrincdec");
Chris Lattner8cc9d082009-03-18 04:25:13 +0000712 } else {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000713 const llvm::Type *i8Ty =
714 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Chris Lattner8cc9d082009-03-18 04:25:13 +0000715 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
716 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
717 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
718 }
Chris Lattnerdb3bd4b2009-02-11 07:40:06 +0000719 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
720 // Bool++ is an interesting case, due to promotion rules, we get:
721 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
722 // Bool = ((int)Bool+1) != 0
723 // An interesting aspect of this is that increment is always true.
724 // Decrement does not have this property.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000725 NextVal = VMContext.getConstantIntTrue();
Chris Lattner87415d22009-06-17 06:36:24 +0000726 } else if (isa<llvm::IntegerType>(InVal->getType())) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000727 NextVal = VMContext.getConstantInt(InVal->getType(), AmountVal);
Chris Lattner87415d22009-06-17 06:36:24 +0000728 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000729 } else {
730 // Add the inc/dec to the real part.
Chris Lattner87415d22009-06-17 06:36:24 +0000731 if (InVal->getType() == llvm::Type::FloatTy)
Devang Patele9b8c0a2007-10-30 20:59:40 +0000732 NextVal =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000733 VMContext.getConstantFP(llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000734 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patele9b8c0a2007-10-30 20:59:40 +0000735 NextVal =
Owen Andersona1cf15f2009-07-14 23:10:40 +0000736 VMContext.getConstantFP(llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000737 else {
738 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesenee5a7002008-10-09 23:02:32 +0000739 bool ignored;
740 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
741 &ignored);
Owen Andersona1cf15f2009-07-14 23:10:40 +0000742 NextVal = VMContext.getConstantFP(F);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000743 }
Chris Lattner87415d22009-06-17 06:36:24 +0000744 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000745 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000746
747 // Store the updated result through the lvalue.
Eli Friedmanf52bbeb2009-03-23 03:00:06 +0000748 if (LV.isBitfield())
749 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
750 &NextVal);
751 else
752 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner7f02f722007-08-24 05:35:26 +0000753
754 // If this is a postinc, return the value read from memory, otherwise use the
755 // updated value.
756 return isPre ? NextVal : InVal;
757}
758
759
760Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000761 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000762 Value *Op = Visit(E->getSubExpr());
Chris Lattner87415d22009-06-17 06:36:24 +0000763 if (Op->getType()->isFPOrFPVector())
764 return Builder.CreateFNeg(Op, "neg");
Chris Lattner7f02f722007-08-24 05:35:26 +0000765 return Builder.CreateNeg(Op, "neg");
766}
767
768Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000769 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000770 Value *Op = Visit(E->getSubExpr());
771 return Builder.CreateNot(Op, "neg");
772}
773
774Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
775 // Compare operand to zero.
776 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
777
778 // Invert value.
779 // TODO: Could dynamically modify easy computations here. For example, if
780 // the operand is an icmp ne, turn into icmp eq.
781 BoolVal = Builder.CreateNot(BoolVal, "lnot");
782
Anders Carlsson9f84d882009-05-19 18:44:53 +0000783 // ZExt result to the expr type.
784 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +0000785}
786
Sebastian Redl05189992008-11-11 17:56:53 +0000787/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
788/// argument of the sizeof expression as an integer.
789Value *
790ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +0000791 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000792 if (E->isSizeOf()) {
793 if (const VariableArrayType *VAT =
794 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
795 if (E->isArgumentType()) {
796 // sizeof(type) - make sure to emit the VLA size.
797 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +0000798 } else {
799 // C99 6.5.3.4p2: If the argument is an expression of type
800 // VLA, it is evaluated.
801 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000802 }
Anders Carlsson6cd586d2009-01-30 16:41:04 +0000803
Anders Carlsson96f21472009-02-05 19:43:10 +0000804 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +0000805 }
Anders Carlsson5d463152008-12-12 07:38:43 +0000806 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000807
808 // If this isn't sizeof(vla), the result must be constant; use the
809 // constant folding logic so we don't have to duplicate it here.
810 Expr::EvalResult Result;
811 E->Evaluate(Result, CGF.getContext());
Owen Andersona1cf15f2009-07-14 23:10:40 +0000812 return VMContext.getConstantInt(Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +0000813}
814
Chris Lattner46f93d02007-08-24 21:20:17 +0000815Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
816 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000817 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +0000818 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner46f93d02007-08-24 21:20:17 +0000819 return Visit(Op);
820}
821Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
822 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000823 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +0000824 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Chris Lattner36f84062007-08-26 05:29:21 +0000825
Mike Stump7f79f9b2009-05-29 15:46:01 +0000826 // __imag on a scalar returns zero. Emit the subexpr to ensure side
827 // effects are evaluated, but not the actual value.
828 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
829 CGF.EmitLValue(Op);
830 else
831 CGF.EmitScalarExpr(Op, true);
Owen Andersona1cf15f2009-07-14 23:10:40 +0000832 return VMContext.getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +0000833}
834
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000835Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
836{
Eli Friedman35183ac2009-02-27 06:44:11 +0000837 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedman769e4112009-01-24 22:38:55 +0000838 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman35183ac2009-02-27 06:44:11 +0000839 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000840}
Chris Lattner46f93d02007-08-24 21:20:17 +0000841
Chris Lattner7f02f722007-08-24 05:35:26 +0000842//===----------------------------------------------------------------------===//
843// Binary Operators
844//===----------------------------------------------------------------------===//
845
846BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000847 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000848 BinOpInfo Result;
849 Result.LHS = Visit(E->getLHS());
850 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000851 Result.Ty = E->getType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000852 Result.E = E;
853 return Result;
854}
855
Chris Lattner3ccf7742007-08-26 21:41:21 +0000856Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000857 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000858 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner1f1ded92007-08-24 21:00:35 +0000859 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
860
861 BinOpInfo OpInfo;
862
Eli Friedmanab3a8522009-03-28 01:22:36 +0000863 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +0000864 // This needs to go through the complex expression emitter, but
Eli Friedmanab3a8522009-03-28 01:22:36 +0000865 // it's a tad complicated to do that... I'm leaving it out for now.
866 // (Note that we do actually need the imaginary part of the RHS for
867 // multiplication and division.)
868 CGF.ErrorUnsupported(E, "complex compound assignment");
Owen Andersona1cf15f2009-07-14 23:10:40 +0000869 return VMContext.getUndef(CGF.ConvertType(E->getType()));
Eli Friedmanab3a8522009-03-28 01:22:36 +0000870 }
871
Mike Stumpcc0442f2009-05-22 19:07:20 +0000872 // Emit the RHS first. __block variables need to have the rhs evaluated
873 // first, plus this should improve codegen a little.
874 OpInfo.RHS = Visit(E->getRHS());
875 OpInfo.Ty = E->getComputationResultType();
876 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +0000877 // Load/convert the LHS.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000878 LValue LHSLV = EmitLValue(E->getLHS());
879 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000880 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
881 E->getComputationLHSType());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000882
883 // Expand the binary operator.
884 Value *Result = (this->*Func)(OpInfo);
885
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000886 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +0000887 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
888
Daniel Dunbared3849b2008-11-19 09:36:46 +0000889 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar371d16f2008-11-19 11:54:05 +0000890 // handled specially because the result is altered by the store,
891 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
892 // the left operand after the assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000893 if (LHSLV.isBitfield()) {
894 if (!LHSLV.isVolatileQualified()) {
895 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
896 &Result);
897 return Result;
898 } else
899 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
900 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +0000901 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stump7f79f9b2009-05-29 15:46:01 +0000902 if (Ignore)
903 return 0;
904 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000905}
906
907
Chris Lattner7f02f722007-08-24 05:35:26 +0000908Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanb3ab8dc2007-12-30 01:28:16 +0000909 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner7f02f722007-08-24 05:35:26 +0000910 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000911 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000912 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
913 else
914 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
915}
916
917Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
918 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000919 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000920 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
921 else
922 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
923}
924
Mike Stump2add4732009-04-01 20:28:16 +0000925Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
926 unsigned IID;
927 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +0000928
Mike Stump035cf892009-04-02 18:15:54 +0000929 switch (Ops.E->getOpcode()) {
930 case BinaryOperator::Add:
931 case BinaryOperator::AddAssign:
932 OpID = 1;
933 IID = llvm::Intrinsic::sadd_with_overflow;
934 break;
935 case BinaryOperator::Sub:
936 case BinaryOperator::SubAssign:
937 OpID = 2;
938 IID = llvm::Intrinsic::ssub_with_overflow;
939 break;
940 case BinaryOperator::Mul:
941 case BinaryOperator::MulAssign:
942 OpID = 3;
943 IID = llvm::Intrinsic::smul_with_overflow;
944 break;
945 default:
946 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +0000947 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +0000948 }
Mike Stump035cf892009-04-02 18:15:54 +0000949 OpID <<= 1;
950 OpID |= 1;
951
Mike Stump2add4732009-04-01 20:28:16 +0000952 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
953
954 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
955
956 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
957 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
958 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
959
960 // Branch in case of overflow.
961 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
962 llvm::BasicBlock *overflowBB =
963 CGF.createBasicBlock("overflow", CGF.CurFn);
964 llvm::BasicBlock *continueBB =
965 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
966
967 Builder.CreateCondBr(overflow, overflowBB, continueBB);
968
969 // Handle overflow
970
971 Builder.SetInsertPoint(overflowBB);
972
973 // Handler is:
974 // long long *__overflow_handler)(long long a, long long b, char op,
975 // char width)
976 std::vector<const llvm::Type*> handerArgTypes;
977 handerArgTypes.push_back(llvm::Type::Int64Ty);
978 handerArgTypes.push_back(llvm::Type::Int64Ty);
979 handerArgTypes.push_back(llvm::Type::Int8Ty);
980 handerArgTypes.push_back(llvm::Type::Int8Ty);
Owen Andersona1cf15f2009-07-14 23:10:40 +0000981 llvm::FunctionType *handlerTy = VMContext.getFunctionType(llvm::Type::Int64Ty,
Mike Stump2add4732009-04-01 20:28:16 +0000982 handerArgTypes, false);
983 llvm::Value *handlerFunction =
984 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
Owen Andersona1cf15f2009-07-14 23:10:40 +0000985 VMContext.getPointerTypeUnqual(handlerTy));
Mike Stump2add4732009-04-01 20:28:16 +0000986 handlerFunction = Builder.CreateLoad(handlerFunction);
987
988 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
989 Builder.CreateSExt(Ops.LHS, llvm::Type::Int64Ty),
990 Builder.CreateSExt(Ops.RHS, llvm::Type::Int64Ty),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000991 VMContext.getConstantInt(llvm::Type::Int8Ty, OpID),
992 VMContext.getConstantInt(llvm::Type::Int8Ty,
Mike Stump2add4732009-04-01 20:28:16 +0000993 cast<llvm::IntegerType>(opTy)->getBitWidth()));
994
995 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
996
997 Builder.CreateBr(continueBB);
998
999 // Set up the continuation
1000 Builder.SetInsertPoint(continueBB);
1001 // Get the correct result
1002 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1003 phi->reserveOperandSpace(2);
1004 phi->addIncoming(result, initialBB);
1005 phi->addIncoming(handlerResult, overflowBB);
1006
1007 return phi;
1008}
Chris Lattner7f02f722007-08-24 05:35:26 +00001009
1010Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001011 if (!Ops.Ty->isAnyPointerType()) {
Chris Lattner87415d22009-06-17 06:36:24 +00001012 if (CGF.getContext().getLangOptions().OverflowChecking &&
1013 Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001014 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +00001015
1016 if (Ops.LHS->getType()->isFPOrFPVector())
1017 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1018
Chris Lattner7f02f722007-08-24 05:35:26 +00001019 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001020 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001021
Steve Naroff14108da2009-07-10 23:34:53 +00001022 if (Ops.Ty->isPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001023 Ops.Ty->getAsPointerType()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001024 // The amount of the addition needs to account for the VLA size
1025 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1026 }
Chris Lattner8f925282008-01-03 06:36:51 +00001027 Value *Ptr, *Idx;
1028 Expr *IdxExp;
Ted Kremenek35366a62009-07-17 17:50:17 +00001029 const PointerType *PT = Ops.E->getLHS()->getType()->getAsPointerType();
Steve Naroff14108da2009-07-10 23:34:53 +00001030 const ObjCObjectPointerType *OPT =
1031 Ops.E->getLHS()->getType()->getAsObjCObjectPointerType();
1032 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001033 Ptr = Ops.LHS;
1034 Idx = Ops.RHS;
1035 IdxExp = Ops.E->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001036 } else { // int + pointer
Ted Kremenek35366a62009-07-17 17:50:17 +00001037 PT = Ops.E->getRHS()->getType()->getAsPointerType();
Steve Naroff14108da2009-07-10 23:34:53 +00001038 OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType();
1039 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001040 Ptr = Ops.RHS;
1041 Idx = Ops.LHS;
1042 IdxExp = Ops.E->getLHS();
1043 }
1044
1045 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001046 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner8f925282008-01-03 06:36:51 +00001047 // Zero or sign extend the pointer value based on whether the index is
1048 // signed or not.
Owen Andersona1cf15f2009-07-14 23:10:40 +00001049 const llvm::Type *IdxType = VMContext.getIntegerType(CGF.LLVMPointerWidth);
Chris Lattner96196622008-07-26 22:37:01 +00001050 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001051 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1052 else
1053 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1054 }
Steve Naroff14108da2009-07-10 23:34:53 +00001055 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Daniel Dunbar2a866252009-04-25 05:08:32 +00001056 // Handle interface types, which are not represented with a concrete
1057 // type.
1058 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1059 llvm::Value *InterfaceSize =
Owen Andersona1cf15f2009-07-14 23:10:40 +00001060 VMContext.getConstantInt(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001061 CGF.getContext().getTypeSize(OIT) / 8);
1062 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001063 const llvm::Type *i8Ty = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001064 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1065 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1066 return Builder.CreateBitCast(Res, Ptr->getType());
1067 }
1068
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001069 // Explicitly handle GNU void* and function pointer arithmetic
1070 // extensions. The GNU void* casts amount to no-ops since our void*
1071 // type is i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001072 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Owen Andersona1cf15f2009-07-14 23:10:40 +00001073 const llvm::Type *i8Ty = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001074 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001075 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001076 return Builder.CreateBitCast(Res, Ptr->getType());
1077 }
Chris Lattner8f925282008-01-03 06:36:51 +00001078
1079 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001080}
1081
1082Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001083 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stump035cf892009-04-02 18:15:54 +00001084 if (CGF.getContext().getLangOptions().OverflowChecking
1085 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001086 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +00001087
1088 if (Ops.LHS->getType()->isFPOrFPVector())
1089 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner7f02f722007-08-24 05:35:26 +00001090 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001091 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001092
Steve Naroff14108da2009-07-10 23:34:53 +00001093 if (Ops.E->getLHS()->getType()->isPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001094 Ops.E->getLHS()->getType()->getAsPointerType()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001095 // The amount of the addition needs to account for the VLA size for
1096 // ptr-int
1097 // The amount of the division needs to account for the VLA size for
1098 // ptr-ptr.
1099 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1100 }
1101
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001102 const QualType LHSType = Ops.E->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001103 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001104 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1105 // pointer - int
1106 Value *Idx = Ops.RHS;
1107 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001108 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001109 // Zero or sign extend the pointer value based on whether the index is
1110 // signed or not.
Owen Andersona1cf15f2009-07-14 23:10:40 +00001111 const llvm::Type *IdxType =
1112 VMContext.getIntegerType(CGF.LLVMPointerWidth);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001113 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1114 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1115 else
1116 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1117 }
1118 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001119
Daniel Dunbar2a866252009-04-25 05:08:32 +00001120 // Handle interface types, which are not represented with a concrete
1121 // type.
1122 if (const ObjCInterfaceType *OIT =
1123 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1124 llvm::Value *InterfaceSize =
Owen Andersona1cf15f2009-07-14 23:10:40 +00001125 VMContext.getConstantInt(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001126 CGF.getContext().getTypeSize(OIT) / 8);
1127 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001128 const llvm::Type *i8Ty =
1129 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001130 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1131 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1132 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1133 }
1134
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001135 // Explicitly handle GNU void* and function pointer arithmetic
1136 // extensions. The GNU void* casts amount to no-ops since our
1137 // void* type is i8*, but this is future proof.
1138 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Owen Andersona1cf15f2009-07-14 23:10:40 +00001139 const llvm::Type *i8Ty =
1140 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001141 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1142 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1143 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1144 }
1145
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001146 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001147 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001148 // pointer - pointer
1149 Value *LHS = Ops.LHS;
1150 Value *RHS = Ops.RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +00001151
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001152 uint64_t ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001153
Chris Lattnere5ed1512009-02-11 07:21:43 +00001154 // Handle GCC extension for pointer arithmetic on void* and function pointer
1155 // types.
1156 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001157 ElementSize = 1;
1158 } else {
1159 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1160 }
1161
1162 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1163 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1164 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1165 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1166
Chris Lattnere5ed1512009-02-11 07:21:43 +00001167 // Optimize out the shift for element size of 1.
1168 if (ElementSize == 1)
1169 return BytesBetween;
1170
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001171 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1172 // remainder. As such, we handle common power-of-two cases here to generate
1173 // better code. See PR2247.
1174 if (llvm::isPowerOf2_64(ElementSize)) {
1175 Value *ShAmt =
Owen Andersona1cf15f2009-07-14 23:10:40 +00001176 VMContext.getConstantInt(ResultType, llvm::Log2_64(ElementSize));
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001177 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
1178 }
1179
1180 // Otherwise, do a full sdiv.
Owen Andersona1cf15f2009-07-14 23:10:40 +00001181 Value *BytesPerElt = VMContext.getConstantInt(ResultType, ElementSize);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001182 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001183 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001184}
1185
1186Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1187 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1188 // RHS to the same size as the LHS.
1189 Value *RHS = Ops.RHS;
1190 if (Ops.LHS->getType() != RHS->getType())
1191 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1192
1193 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1194}
1195
1196Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1197 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1198 // RHS to the same size as the LHS.
1199 Value *RHS = Ops.RHS;
1200 if (Ops.LHS->getType() != RHS->getType())
1201 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1202
Chris Lattner1f1ded92007-08-24 21:00:35 +00001203 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001204 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1205 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1206}
1207
1208Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1209 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001210 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001211 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001212 QualType LHSTy = E->getLHS()->getType();
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001213 if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001214 Value *LHS = Visit(E->getLHS());
1215 Value *RHS = Visit(E->getRHS());
1216
1217 if (LHS->getType()->isFloatingPoint()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001218 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001219 LHS, RHS, "cmp");
Eli Friedmanec2c1262008-05-29 15:09:15 +00001220 } else if (LHSTy->isSignedIntegerType()) {
1221 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001222 LHS, RHS, "cmp");
1223 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001224 // Unsigned integers and pointers.
1225 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001226 LHS, RHS, "cmp");
1227 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001228
1229 // If this is a vector comparison, sign extend the result to the appropriate
1230 // vector integer type and return it (don't convert to bool).
1231 if (LHSTy->isVectorType())
1232 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001233
Chris Lattner7f02f722007-08-24 05:35:26 +00001234 } else {
1235 // Complex Comparison: can only be an equality comparison.
1236 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1237 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1238
Chris Lattner96196622008-07-26 22:37:01 +00001239 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner7f02f722007-08-24 05:35:26 +00001240
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001241 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00001242 if (CETy->isRealFloatingType()) {
1243 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1244 LHS.first, RHS.first, "cmp.r");
1245 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1246 LHS.second, RHS.second, "cmp.i");
1247 } else {
1248 // Complex comparisons can only be equality comparisons. As such, signed
1249 // and unsigned opcodes are the same.
1250 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1251 LHS.first, RHS.first, "cmp.r");
1252 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1253 LHS.second, RHS.second, "cmp.i");
1254 }
1255
1256 if (E->getOpcode() == BinaryOperator::EQ) {
1257 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1258 } else {
1259 assert(E->getOpcode() == BinaryOperator::NE &&
1260 "Complex comparison other than == or != ?");
1261 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1262 }
1263 }
Nuno Lopes32f62092009-01-11 23:22:37 +00001264
1265 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001266}
1267
1268Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001269 bool Ignore = TestAndClearIgnoreResultAssign();
1270
1271 // __block variables need to have the rhs evaluated first, plus this should
1272 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00001273 Value *RHS = Visit(E->getRHS());
Mike Stump99459b62009-05-21 21:05:15 +00001274 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner7f02f722007-08-24 05:35:26 +00001275
Daniel Dunbared3849b2008-11-19 09:36:46 +00001276 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001277 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1278 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00001279 // the assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001280 if (LHS.isBitfield()) {
1281 if (!LHS.isVolatileQualified()) {
1282 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1283 &RHS);
1284 return RHS;
1285 } else
1286 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1287 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001288 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stump7f79f9b2009-05-29 15:46:01 +00001289 if (Ignore)
1290 return 0;
1291 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001292}
1293
1294Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001295 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1296 // If we have 1 && X, just emit X without inserting the control flow.
1297 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1298 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001299 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1300 // ZExt result to int.
1301 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1302 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001303
1304 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1305 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersona1cf15f2009-07-14 23:10:40 +00001306 return VMContext.getNullValue(CGF.LLVMIntTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001307 }
1308
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001309 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1310 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001311
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001312 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1313 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1314
1315 // Any edges into the ContBlock are now from an (indeterminate number of)
1316 // edges from this first condition. All of these values will be false. Start
1317 // setting up the PHI node in the Cont Block for this.
1318 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1319 PN->reserveOperandSpace(2); // Normal case, two inputs.
1320 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1321 PI != PE; ++PI)
Owen Andersona1cf15f2009-07-14 23:10:40 +00001322 PN->addIncoming(VMContext.getConstantIntFalse(), *PI);
Chris Lattner7f02f722007-08-24 05:35:26 +00001323
Anders Carlsson33da07d2009-06-04 02:53:13 +00001324 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001325 CGF.EmitBlock(RHSBlock);
1326 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlsson33da07d2009-06-04 02:53:13 +00001327 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001328
1329 // Reaquire the RHS block, as there may be subblocks inserted.
1330 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001331
1332 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1333 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001334 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001335 PN->addIncoming(RHSCond, RHSBlock);
1336
1337 // ZExt result to int.
1338 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1339}
1340
1341Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001342 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1343 // If we have 0 || X, just emit X without inserting the control flow.
1344 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1345 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001346 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1347 // ZExt result to int.
1348 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1349 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001350
Eli Friedman8de8d1d2008-12-02 16:02:46 +00001351 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001352 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersona1cf15f2009-07-14 23:10:40 +00001353 return VMContext.getConstantInt(CGF.LLVMIntTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001354 }
1355
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001356 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1357 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner7f02f722007-08-24 05:35:26 +00001358
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001359 // Branch on the LHS first. If it is true, go to the success (cont) block.
1360 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1361
1362 // Any edges into the ContBlock are now from an (indeterminate number of)
1363 // edges from this first condition. All of these values will be true. Start
1364 // setting up the PHI node in the Cont Block for this.
1365 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1366 PN->reserveOperandSpace(2); // Normal case, two inputs.
1367 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1368 PI != PE; ++PI)
Owen Andersona1cf15f2009-07-14 23:10:40 +00001369 PN->addIncoming(VMContext.getConstantIntTrue(), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001370
Anders Carlsson33da07d2009-06-04 02:53:13 +00001371 CGF.PushConditionalTempDestruction();
1372
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001373 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001374 CGF.EmitBlock(RHSBlock);
1375 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1376
Anders Carlsson33da07d2009-06-04 02:53:13 +00001377 CGF.PopConditionalTempDestruction();
1378
Chris Lattner7f02f722007-08-24 05:35:26 +00001379 // Reaquire the RHS block, as there may be subblocks inserted.
1380 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00001381
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001382 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1383 // into the phi node for the edge with the value of RHSCond.
1384 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001385 PN->addIncoming(RHSCond, RHSBlock);
1386
1387 // ZExt result to int.
1388 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1389}
1390
1391Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1392 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00001393 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00001394 return Visit(E->getRHS());
1395}
1396
1397//===----------------------------------------------------------------------===//
1398// Other Operators
1399//===----------------------------------------------------------------------===//
1400
Chris Lattner9802a512008-11-12 08:55:54 +00001401/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1402/// expression is cheap enough and side-effect-free enough to evaluate
1403/// unconditionally instead of conditionally. This is used to convert control
1404/// flow into selects in some cases.
1405static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1406 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1407 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1408
1409 // TODO: Allow anything we can constant fold to an integer or fp constant.
1410 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1411 isa<FloatingLiteral>(E))
1412 return true;
1413
1414 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1415 // X and Y are local variables.
1416 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1417 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1418 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1419 return true;
1420
1421 return false;
1422}
1423
1424
Chris Lattner7f02f722007-08-24 05:35:26 +00001425Value *ScalarExprEmitter::
1426VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001427 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00001428 // If the condition constant folds and can be elided, try to avoid emitting
1429 // the condition and the dead arm.
1430 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00001431 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00001432 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00001433 std::swap(Live, Dead);
Chris Lattner31a09842008-11-12 08:04:58 +00001434
1435 // If the dead side doesn't have labels we need, and if the Live side isn't
1436 // the gnu missing ?: extension (which we could handle, but don't bother
1437 // to), just emit the Live part.
1438 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1439 Live) // Live part isn't missing.
1440 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00001441 }
1442
Chris Lattner9802a512008-11-12 08:55:54 +00001443
1444 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1445 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00001446 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner9802a512008-11-12 08:55:54 +00001447 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1448 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1449 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1450 llvm::Value *LHS = Visit(E->getLHS());
1451 llvm::Value *RHS = Visit(E->getRHS());
1452 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1453 }
1454
1455
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00001456 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1457 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001458 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00001459 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00001460
Chris Lattner12d152f2009-02-13 23:35:32 +00001461 // If we don't have the GNU missing condition extension, emit a branch on
1462 // bool the normal way.
1463 if (E->getLHS()) {
1464 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1465 // the branch on bool.
1466 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1467 } else {
1468 // Otherwise, for the ?: extension, evaluate the conditional and then
1469 // convert it to bool the hard way. We do this explicitly because we need
1470 // the unconverted value for the missing middle value of the ?:.
Chris Lattner035cf422008-11-12 08:08:13 +00001471 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner12d152f2009-02-13 23:35:32 +00001472
1473 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1474 // if there are no extra uses (an optimization). Inhibit this by making an
1475 // extra dead use, because we're going to add a use of CondVal later. We
1476 // don't use the builder for this, because we don't want it to get optimized
1477 // away. This leaves dead code, but the ?: extension isn't common.
1478 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1479 Builder.GetInsertBlock());
1480
Chris Lattner035cf422008-11-12 08:08:13 +00001481 Value *CondBoolVal =
1482 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1483 CGF.getContext().BoolTy);
1484 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00001485 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001486
1487 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001488 CGF.EmitBlock(LHSBlock);
1489
1490 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00001491 Value *LHS;
1492 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00001493 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00001494 else // Perform promotions, to handle cases like "short ?: int"
1495 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1496
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001497 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001498 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001499 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001500
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001501 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001502 CGF.EmitBlock(RHSBlock);
1503
Eli Friedman856226c2008-05-16 20:38:39 +00001504 Value *RHS = Visit(E->getRHS());
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001505 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001506 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001507 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001508
1509 CGF.EmitBlock(ContBlock);
1510
Nuno Lopes108f55d2008-06-04 19:15:45 +00001511 if (!LHS || !RHS) {
Chris Lattner2202bce2007-11-30 17:56:23 +00001512 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1513 return 0;
1514 }
1515
Chris Lattner7f02f722007-08-24 05:35:26 +00001516 // Create a PHI node for the real part.
1517 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1518 PN->reserveOperandSpace(2);
1519 PN->addIncoming(LHS, LHSBlock);
1520 PN->addIncoming(RHS, RHSBlock);
1521 return PN;
1522}
1523
1524Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00001525 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001526}
1527
Chris Lattner2202bce2007-11-30 17:56:23 +00001528Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00001529 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001530 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1531
1532 // If EmitVAArg fails, we fall back to the LLVM instruction.
1533 if (!ArgPtr)
1534 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1535
Mike Stump7f79f9b2009-05-29 15:46:01 +00001536 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001537 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001538}
1539
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001540Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump08920992009-03-07 02:35:30 +00001541 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001542}
1543
Chris Lattner7f02f722007-08-24 05:35:26 +00001544//===----------------------------------------------------------------------===//
1545// Entry Point into this File
1546//===----------------------------------------------------------------------===//
1547
Mike Stump7f79f9b2009-05-29 15:46:01 +00001548/// EmitScalarExpr - Emit the computation of the specified expression of
1549/// scalar type, ignoring the result.
1550Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001551 assert(E && !hasAggregateLLVMType(E->getType()) &&
1552 "Invalid scalar expression to emit");
1553
Mike Stump7f79f9b2009-05-29 15:46:01 +00001554 return ScalarExprEmitter(*this, IgnoreResultAssign)
1555 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00001556}
Chris Lattner3707b252007-08-26 06:48:56 +00001557
1558/// EmitScalarConversion - Emit a conversion from the specified type to the
1559/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001560Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1561 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00001562 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1563 "Invalid scalar expression to emit");
1564 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1565}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001566
1567/// EmitComplexToScalarConversion - Emit a conversion from the specified
1568/// complex type to the specified destination type, where the destination
1569/// type is an LLVM scalar type.
1570Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1571 QualType SrcTy,
1572 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00001573 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001574 "Invalid complex -> scalar conversion");
1575 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1576 DstTy);
1577}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001578
1579Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1580 assert(V1->getType() == V2->getType() &&
1581 "Vector operands must be of the same type");
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001582 unsigned NumElements =
1583 cast<llvm::VectorType>(V1->getType())->getNumElements();
1584
1585 va_list va;
1586 va_start(va, V2);
1587
1588 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001589 for (unsigned i = 0; i < NumElements; i++) {
1590 int n = va_arg(va, int);
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001591 assert(n >= 0 && n < (int)NumElements * 2 &&
1592 "Vector shuffle index out of bounds!");
Owen Andersona1cf15f2009-07-14 23:10:40 +00001593 Args.push_back(VMContext.getConstantInt(llvm::Type::Int32Ty, n));
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001594 }
1595
1596 const char *Name = va_arg(va, const char *);
1597 va_end(va);
1598
Owen Andersona1cf15f2009-07-14 23:10:40 +00001599 llvm::Constant *Mask = VMContext.getConstantVector(&Args[0], NumElements);
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001600
1601 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1602}
1603
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001604llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattner345f7202008-07-26 20:15:14 +00001605 unsigned NumVals, bool isSplat) {
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001606 llvm::Value *Vec
Owen Andersona1cf15f2009-07-14 23:10:40 +00001607 = VMContext.getUndef(VMContext.getVectorType(Vals[0]->getType(), NumVals));
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001608
Chris Lattner345f7202008-07-26 20:15:14 +00001609 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001610 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Owen Andersona1cf15f2009-07-14 23:10:40 +00001611 llvm::Value *Idx = VMContext.getConstantInt(llvm::Type::Int32Ty, i);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001612 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001613 }
1614
1615 return Vec;
1616}