blob: b6613e7cdc360e2e22f48dbc4a1f07370c523828 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
45struct EvalInfo {
46 ASTContext &Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +000047
Anders Carlsson54da0492008-11-30 16:38:33 +000048 /// EvalResult - Contains information about the evaluation.
49 Expr::EvalResult &EvalResult;
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +000050
Eli Friedmanb2f295c2009-09-13 10:17:44 +000051 /// AnyLValue - Stack based LValue results are not discarded.
52 bool AnyLValue;
53
54 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult,
55 bool anylvalue = false)
56 : Ctx(ctx), EvalResult(evalresult), AnyLValue(anylvalue) {}
Chris Lattner87eae5e2008-07-11 22:52:41 +000057};
58
John McCallf4cf1a12010-05-07 17:22:02 +000059namespace {
60 struct ComplexValue {
61 private:
62 bool IsInt;
63
64 public:
65 APSInt IntReal, IntImag;
66 APFloat FloatReal, FloatImag;
67
68 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
69
70 void makeComplexFloat() { IsInt = false; }
71 bool isComplexFloat() const { return !IsInt; }
72 APFloat &getComplexFloatReal() { return FloatReal; }
73 APFloat &getComplexFloatImag() { return FloatImag; }
74
75 void makeComplexInt() { IsInt = true; }
76 bool isComplexInt() const { return IsInt; }
77 APSInt &getComplexIntReal() { return IntReal; }
78 APSInt &getComplexIntImag() { return IntImag; }
79
80 void moveInto(APValue &v) {
81 if (isComplexFloat())
82 v = APValue(FloatReal, FloatImag);
83 else
84 v = APValue(IntReal, IntImag);
85 }
86 };
John McCallefdb83e2010-05-07 21:00:08 +000087
88 struct LValue {
89 Expr *Base;
90 CharUnits Offset;
91
92 Expr *getLValueBase() { return Base; }
93 CharUnits getLValueOffset() { return Offset; }
94
95 void moveInto(APValue &v) {
96 v = APValue(Base, Offset);
97 }
98 };
John McCallf4cf1a12010-05-07 17:22:02 +000099}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000100
John McCallefdb83e2010-05-07 21:00:08 +0000101static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
102static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000103static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000104static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
105 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000106static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000107static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000108
109//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000110// Misc utilities
111//===----------------------------------------------------------------------===//
112
John McCallefdb83e2010-05-07 21:00:08 +0000113static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
114 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000115
John McCallefdb83e2010-05-07 21:00:08 +0000116 Result = Base || !Value.Offset.isZero();
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000117
118 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
119 if (!DeclRef)
120 return true;
121
122 const ValueDecl* Decl = DeclRef->getDecl();
123 if (Decl->hasAttr<WeakAttr>() ||
124 Decl->hasAttr<WeakRefAttr>() ||
125 Decl->hasAttr<WeakImportAttr>())
126 return false;
127
Eli Friedman5bc86102009-06-14 02:17:33 +0000128 return true;
129}
130
John McCallcd7a4452010-01-05 23:42:56 +0000131static bool HandleConversionToBool(const Expr* E, bool& Result,
132 EvalInfo &Info) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000133 if (E->getType()->isIntegralType()) {
134 APSInt IntResult;
135 if (!EvaluateInteger(E, IntResult, Info))
136 return false;
137 Result = IntResult != 0;
138 return true;
139 } else if (E->getType()->isRealFloatingType()) {
140 APFloat FloatResult(0.0);
141 if (!EvaluateFloat(E, FloatResult, Info))
142 return false;
143 Result = !FloatResult.isZero();
144 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000145 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000146 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000147 if (!EvaluatePointer(E, PointerResult, Info))
148 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000149 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000150 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000151 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000152 if (!EvaluateComplex(E, ComplexResult, Info))
153 return false;
154 if (ComplexResult.isComplexFloat()) {
155 Result = !ComplexResult.getComplexFloatReal().isZero() ||
156 !ComplexResult.getComplexFloatImag().isZero();
157 } else {
158 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
159 ComplexResult.getComplexIntImag().getBoolValue();
160 }
161 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000162 }
163
164 return false;
165}
166
Mike Stump1eb44332009-09-09 15:08:12 +0000167static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000168 APFloat &Value, ASTContext &Ctx) {
169 unsigned DestWidth = Ctx.getIntWidth(DestType);
170 // Determine whether we are converting to unsigned or signed.
171 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000173 // FIXME: Warning for overflow.
174 uint64_t Space[4];
175 bool ignored;
176 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
177 llvm::APFloat::rmTowardZero, &ignored);
178 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
179}
180
Mike Stump1eb44332009-09-09 15:08:12 +0000181static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000182 APFloat &Value, ASTContext &Ctx) {
183 bool ignored;
184 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000185 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000186 APFloat::rmNearestTiesToEven, &ignored);
187 return Result;
188}
189
Mike Stump1eb44332009-09-09 15:08:12 +0000190static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000191 APSInt &Value, ASTContext &Ctx) {
192 unsigned DestWidth = Ctx.getIntWidth(DestType);
193 APSInt Result = Value;
194 // Figure out if this is a truncate, extend or noop cast.
195 // If the input is signed, do a sign extend, noop, or truncate.
196 Result.extOrTrunc(DestWidth);
197 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
198 return Result;
199}
200
Mike Stump1eb44332009-09-09 15:08:12 +0000201static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000202 APSInt &Value, ASTContext &Ctx) {
203
204 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
205 Result.convertFromAPInt(Value, Value.isSigned(),
206 APFloat::rmNearestTiesToEven);
207 return Result;
208}
209
Mike Stumpc4c90452009-10-27 22:09:17 +0000210namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000211class HasSideEffect
Mike Stumpc4c90452009-10-27 22:09:17 +0000212 : public StmtVisitor<HasSideEffect, bool> {
213 EvalInfo &Info;
214public:
215
216 HasSideEffect(EvalInfo &info) : Info(info) {}
217
218 // Unhandled nodes conservatively default to having side effects.
219 bool VisitStmt(Stmt *S) {
220 return true;
221 }
222
223 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
224 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000225 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000226 return true;
227 return false;
228 }
229 // We don't want to evaluate BlockExprs multiple times, as they generate
230 // a ton of code.
231 bool VisitBlockExpr(BlockExpr *E) { return true; }
232 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
233 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
234 { return Visit(E->getInitializer()); }
235 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
236 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
237 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
238 bool VisitStringLiteral(StringLiteral *E) { return false; }
239 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
240 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
241 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000242 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000243 bool VisitChooseExpr(ChooseExpr *E)
244 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
245 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
246 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stump3f0147e2009-10-29 23:34:20 +0000247 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stump980ca222009-10-29 20:48:09 +0000248 bool VisitBinaryOperator(BinaryOperator *E)
249 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000250 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
251 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
252 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
253 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
254 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000255 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000256 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000257 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000258 }
259 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000260
261 // Has side effects if any element does.
262 bool VisitInitListExpr(InitListExpr *E) {
263 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
264 if (Visit(E->getInit(i))) return true;
265 return false;
266 }
Mike Stumpc4c90452009-10-27 22:09:17 +0000267};
268
Mike Stumpc4c90452009-10-27 22:09:17 +0000269} // end anonymous namespace
270
Eli Friedman4efaa272008-11-12 09:44:48 +0000271//===----------------------------------------------------------------------===//
272// LValue Evaluation
273//===----------------------------------------------------------------------===//
274namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000275class LValueExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000276 : public StmtVisitor<LValueExprEvaluator, bool> {
Eli Friedman4efaa272008-11-12 09:44:48 +0000277 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000278 LValue &Result;
279
280 bool Success(Expr *E) {
281 Result.Base = E;
282 Result.Offset = CharUnits::Zero();
283 return true;
284 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000285public:
Mike Stump1eb44332009-09-09 15:08:12 +0000286
John McCallefdb83e2010-05-07 21:00:08 +0000287 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
288 Info(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000289
John McCallefdb83e2010-05-07 21:00:08 +0000290 bool VisitStmt(Stmt *S) {
291 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000292 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000293
John McCallefdb83e2010-05-07 21:00:08 +0000294 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
295 bool VisitDeclRefExpr(DeclRefExpr *E);
296 bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); }
297 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
298 bool VisitMemberExpr(MemberExpr *E);
299 bool VisitStringLiteral(StringLiteral *E) { return Success(E); }
300 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); }
301 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E);
302 bool VisitUnaryDeref(UnaryOperator *E);
303 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000304 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000305 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000306 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlsson26bc2202009-10-03 16:30:22 +0000307
John McCallefdb83e2010-05-07 21:00:08 +0000308 bool VisitCastExpr(CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000309 switch (E->getCastKind()) {
310 default:
John McCallefdb83e2010-05-07 21:00:08 +0000311 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000312
313 case CastExpr::CK_NoOp:
314 return Visit(E->getSubExpr());
315 }
316 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000317 // FIXME: Missing: __real__, __imag__
Eli Friedman4efaa272008-11-12 09:44:48 +0000318};
319} // end anonymous namespace
320
John McCallefdb83e2010-05-07 21:00:08 +0000321static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
322 return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Eli Friedman4efaa272008-11-12 09:44:48 +0000323}
324
John McCallefdb83e2010-05-07 21:00:08 +0000325bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000326 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000327 return Success(E);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000328 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedmanb2f295c2009-09-13 10:17:44 +0000329 if (!Info.AnyLValue && !VD->hasGlobalStorage())
John McCallefdb83e2010-05-07 21:00:08 +0000330 return false;
Eli Friedman50c39ea2009-05-27 06:04:58 +0000331 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000332 return Success(E);
Eli Friedmand933a012009-08-29 19:09:59 +0000333 // FIXME: Check whether VD might be overridden!
Sebastian Redl31310a22010-02-01 20:16:42 +0000334 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000335 return Visit(const_cast<Expr *>(Init));
Eli Friedman50c39ea2009-05-27 06:04:58 +0000336 }
337
John McCallefdb83e2010-05-07 21:00:08 +0000338 return false;
Anders Carlsson35873c42008-11-24 04:41:22 +0000339}
340
John McCallefdb83e2010-05-07 21:00:08 +0000341bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
Eli Friedmanb2f295c2009-09-13 10:17:44 +0000342 if (!Info.AnyLValue && !E->isFileScope())
John McCallefdb83e2010-05-07 21:00:08 +0000343 return false;
344 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000345}
346
John McCallefdb83e2010-05-07 21:00:08 +0000347bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000348 QualType Ty;
349 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000350 if (!EvaluatePointer(E->getBase(), Result, Info))
351 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000352 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000353 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000354 if (!Visit(E->getBase()))
355 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000356 Ty = E->getBase()->getType();
357 }
358
Ted Kremenek6217b802009-07-29 21:53:49 +0000359 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000360 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000361
362 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
363 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000364 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000365
366 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000367 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000368
Eli Friedman4efaa272008-11-12 09:44:48 +0000369 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000370 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000371 for (RecordDecl::field_iterator Field = RD->field_begin(),
372 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000373 Field != FieldEnd; (void)++Field, ++i) {
374 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000375 break;
376 }
377
John McCallefdb83e2010-05-07 21:00:08 +0000378 Result.Offset += CharUnits::fromQuantity(RL.getFieldOffset(i) / 8);
379 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000380}
381
John McCallefdb83e2010-05-07 21:00:08 +0000382bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000383 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000384 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Anders Carlsson3068d112008-11-16 19:01:22 +0000386 APSInt Index;
387 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000388 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000389
Ken Dyck199c3d62010-01-11 17:06:35 +0000390 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000391 Result.Offset += Index.getSExtValue() * ElementSize;
392 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000393}
Eli Friedman4efaa272008-11-12 09:44:48 +0000394
John McCallefdb83e2010-05-07 21:00:08 +0000395bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
396 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000397}
398
Eli Friedman4efaa272008-11-12 09:44:48 +0000399//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000400// Pointer Evaluation
401//===----------------------------------------------------------------------===//
402
Anders Carlssonc754aa62008-07-08 05:13:58 +0000403namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000404class PointerExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000405 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000406 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000407 LValue &Result;
408
409 bool Success(Expr *E) {
410 Result.Base = E;
411 Result.Offset = CharUnits::Zero();
412 return true;
413 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000414public:
Mike Stump1eb44332009-09-09 15:08:12 +0000415
John McCallefdb83e2010-05-07 21:00:08 +0000416 PointerExprEvaluator(EvalInfo &info, LValue &Result)
417 : Info(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000418
John McCallefdb83e2010-05-07 21:00:08 +0000419 bool VisitStmt(Stmt *S) {
420 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000421 }
422
John McCallefdb83e2010-05-07 21:00:08 +0000423 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000424
John McCallefdb83e2010-05-07 21:00:08 +0000425 bool VisitBinaryOperator(const BinaryOperator *E);
426 bool VisitCastExpr(CastExpr* E);
427 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman2217c872009-02-22 11:46:18 +0000428 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000429 bool VisitUnaryAddrOf(const UnaryOperator *E);
430 bool VisitObjCStringLiteral(ObjCStringLiteral *E)
431 { return Success(E); }
432 bool VisitAddrLabelExpr(AddrLabelExpr *E)
433 { return Success(E); }
434 bool VisitCallExpr(CallExpr *E);
435 bool VisitBlockExpr(BlockExpr *E) {
Mike Stumpb83d2872009-02-19 22:01:56 +0000436 if (!E->hasBlockDeclRefExprs())
John McCallefdb83e2010-05-07 21:00:08 +0000437 return Success(E);
438 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000439 }
John McCallefdb83e2010-05-07 21:00:08 +0000440 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
441 { return Success((Expr*)0); }
442 bool VisitConditionalOperator(ConditionalOperator *E);
443 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000444 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallefdb83e2010-05-07 21:00:08 +0000445 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
446 { return Success((Expr*)0); }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000447 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000448};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000449} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000450
John McCallefdb83e2010-05-07 21:00:08 +0000451static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000452 assert(E->getType()->hasPointerRepresentation());
John McCallefdb83e2010-05-07 21:00:08 +0000453 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000454}
455
John McCallefdb83e2010-05-07 21:00:08 +0000456bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000457 if (E->getOpcode() != BinaryOperator::Add &&
458 E->getOpcode() != BinaryOperator::Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000459 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000461 const Expr *PExp = E->getLHS();
462 const Expr *IExp = E->getRHS();
463 if (IExp->getType()->isPointerType())
464 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000465
John McCallefdb83e2010-05-07 21:00:08 +0000466 if (!EvaluatePointer(PExp, Result, Info))
467 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000468
John McCallefdb83e2010-05-07 21:00:08 +0000469 llvm::APSInt Offset;
470 if (!EvaluateInteger(IExp, Offset, Info))
471 return false;
472 int64_t AdditionalOffset
473 = Offset.isSigned() ? Offset.getSExtValue()
474 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000475
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000476 // Compute the new offset in the appropriate width.
477
478 QualType PointeeType =
479 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000480 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000482 // Explicitly handle GNU void* and function pointer arithmetic extensions.
483 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000484 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000485 else
John McCallefdb83e2010-05-07 21:00:08 +0000486 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000487
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000488 if (E->getOpcode() == BinaryOperator::Add)
John McCallefdb83e2010-05-07 21:00:08 +0000489 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000490 else
John McCallefdb83e2010-05-07 21:00:08 +0000491 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000492
John McCallefdb83e2010-05-07 21:00:08 +0000493 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000494}
Eli Friedman4efaa272008-11-12 09:44:48 +0000495
John McCallefdb83e2010-05-07 21:00:08 +0000496bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
497 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000498}
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000500
John McCallefdb83e2010-05-07 21:00:08 +0000501bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000502 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000503
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000504 switch (E->getCastKind()) {
505 default:
506 break;
507
508 case CastExpr::CK_Unknown: {
509 // FIXME: The handling for CK_Unknown is ugly/shouldn't be necessary!
510
511 // Check for pointer->pointer cast
512 if (SubExpr->getType()->isPointerType() ||
513 SubExpr->getType()->isObjCObjectPointerType() ||
514 SubExpr->getType()->isNullPtrType() ||
515 SubExpr->getType()->isBlockPointerType())
516 return Visit(SubExpr);
517
518 if (SubExpr->getType()->isIntegralType()) {
John McCallefdb83e2010-05-07 21:00:08 +0000519 APValue Value;
520 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000521 break;
522
John McCallefdb83e2010-05-07 21:00:08 +0000523 if (Value.isInt()) {
524 Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
525 Result.Base = 0;
526 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
527 return true;
528 } else {
529 Result.Base = Value.getLValueBase();
530 Result.Offset = Value.getLValueOffset();
531 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000532 }
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000533 }
534 break;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000537 case CastExpr::CK_NoOp:
538 case CastExpr::CK_BitCast:
539 case CastExpr::CK_AnyPointerToObjCPointerCast:
540 case CastExpr::CK_AnyPointerToBlockPointerCast:
541 return Visit(SubExpr);
542
543 case CastExpr::CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000544 APValue Value;
545 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000546 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000547
John McCallefdb83e2010-05-07 21:00:08 +0000548 if (Value.isInt()) {
549 Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
550 Result.Base = 0;
551 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
552 return true;
553 } else {
554 // Cast is of an lvalue, no need to change value.
555 Result.Base = Value.getLValueBase();
556 Result.Offset = Value.getLValueOffset();
557 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000558 }
559 }
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000560 case CastExpr::CK_ArrayToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000561 case CastExpr::CK_FunctionToPointerDecay:
562 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000563 }
564
John McCallefdb83e2010-05-07 21:00:08 +0000565 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000566}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000567
John McCallefdb83e2010-05-07 21:00:08 +0000568bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000569 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000570 Builtin::BI__builtin___CFStringMakeConstantString ||
571 E->isBuiltinCall(Info.Ctx) ==
572 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000573 return Success(E);
574 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000575}
576
John McCallefdb83e2010-05-07 21:00:08 +0000577bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000578 bool BoolResult;
579 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000580 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000581
582 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000583 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000584}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000585
586//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000587// Vector Evaluation
588//===----------------------------------------------------------------------===//
589
590namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000591 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000592 : public StmtVisitor<VectorExprEvaluator, APValue> {
593 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000594 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000595 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Nate Begeman59b5da62009-01-18 03:20:47 +0000597 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Nate Begeman59b5da62009-01-18 03:20:47 +0000599 APValue VisitStmt(Stmt *S) {
600 return APValue();
601 }
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Eli Friedman91110ee2009-02-23 04:23:56 +0000603 APValue VisitParenExpr(ParenExpr *E)
604 { return Visit(E->getSubExpr()); }
605 APValue VisitUnaryExtension(const UnaryOperator *E)
606 { return Visit(E->getSubExpr()); }
607 APValue VisitUnaryPlus(const UnaryOperator *E)
608 { return Visit(E->getSubExpr()); }
609 APValue VisitUnaryReal(const UnaryOperator *E)
610 { return Visit(E->getSubExpr()); }
611 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
612 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000613 APValue VisitCastExpr(const CastExpr* E);
614 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
615 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000616 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000617 APValue VisitChooseExpr(const ChooseExpr *E)
618 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000619 APValue VisitUnaryImag(const UnaryOperator *E);
620 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000621 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000622 // shufflevector, ExtVectorElementExpr
623 // (Note that these require implementing conversions
624 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000625 };
626} // end anonymous namespace
627
628static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
629 if (!E->getType()->isVectorType())
630 return false;
631 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
632 return !Result.isUninit();
633}
634
635APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000636 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000637 QualType EltTy = VTy->getElementType();
638 unsigned NElts = VTy->getNumElements();
639 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Nate Begeman59b5da62009-01-18 03:20:47 +0000641 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000642 QualType SETy = SE->getType();
643 APValue Result = APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000644
Nate Begemane8c9e922009-06-26 18:22:18 +0000645 // Check for vector->vector bitcast and scalar->vector splat.
646 if (SETy->isVectorType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000647 return this->Visit(const_cast<Expr*>(SE));
Nate Begemane8c9e922009-06-26 18:22:18 +0000648 } else if (SETy->isIntegerType()) {
649 APSInt IntResult;
Daniel Dunbard906dc72009-07-01 20:37:45 +0000650 if (!EvaluateInteger(SE, IntResult, Info))
651 return APValue();
652 Result = APValue(IntResult);
Nate Begemane8c9e922009-06-26 18:22:18 +0000653 } else if (SETy->isRealFloatingType()) {
654 APFloat F(0.0);
Daniel Dunbard906dc72009-07-01 20:37:45 +0000655 if (!EvaluateFloat(SE, F, Info))
656 return APValue();
657 Result = APValue(F);
658 } else
Nate Begemanc0b8b192009-07-01 07:50:47 +0000659 return APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000660
Nate Begemanc0b8b192009-07-01 07:50:47 +0000661 // For casts of a scalar to ExtVector, convert the scalar to the element type
662 // and splat it to all elements.
663 if (E->getType()->isExtVectorType()) {
664 if (EltTy->isIntegerType() && Result.isInt())
665 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
666 Info.Ctx));
667 else if (EltTy->isIntegerType())
668 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
669 Info.Ctx));
670 else if (EltTy->isRealFloatingType() && Result.isInt())
671 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
672 Info.Ctx));
673 else if (EltTy->isRealFloatingType())
674 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
675 Info.Ctx));
676 else
677 return APValue();
678
679 // Splat and create vector APValue.
680 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
681 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000682 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000683
684 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
685 // to the vector. To construct the APValue vector initializer, bitcast the
686 // initializing value to an APInt, and shift out the bits pertaining to each
687 // element.
688 APSInt Init;
689 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Nate Begemanc0b8b192009-07-01 07:50:47 +0000691 llvm::SmallVector<APValue, 4> Elts;
692 for (unsigned i = 0; i != NElts; ++i) {
693 APSInt Tmp = Init;
694 Tmp.extOrTrunc(EltWidth);
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Nate Begemanc0b8b192009-07-01 07:50:47 +0000696 if (EltTy->isIntegerType())
697 Elts.push_back(APValue(Tmp));
698 else if (EltTy->isRealFloatingType())
699 Elts.push_back(APValue(APFloat(Tmp)));
700 else
701 return APValue();
702
703 Init >>= EltWidth;
704 }
705 return APValue(&Elts[0], Elts.size());
Nate Begeman59b5da62009-01-18 03:20:47 +0000706}
707
Mike Stump1eb44332009-09-09 15:08:12 +0000708APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000709VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
710 return this->Visit(const_cast<Expr*>(E->getInitializer()));
711}
712
Mike Stump1eb44332009-09-09 15:08:12 +0000713APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000714VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000715 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000716 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000717 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Nate Begeman59b5da62009-01-18 03:20:47 +0000719 QualType EltTy = VT->getElementType();
720 llvm::SmallVector<APValue, 4> Elements;
721
Eli Friedman91110ee2009-02-23 04:23:56 +0000722 for (unsigned i = 0; i < NumElements; i++) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000723 if (EltTy->isIntegerType()) {
724 llvm::APSInt sInt(32);
Eli Friedman91110ee2009-02-23 04:23:56 +0000725 if (i < NumInits) {
726 if (!EvaluateInteger(E->getInit(i), sInt, Info))
727 return APValue();
728 } else {
729 sInt = Info.Ctx.MakeIntValue(0, EltTy);
730 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000731 Elements.push_back(APValue(sInt));
732 } else {
733 llvm::APFloat f(0.0);
Eli Friedman91110ee2009-02-23 04:23:56 +0000734 if (i < NumInits) {
735 if (!EvaluateFloat(E->getInit(i), f, Info))
736 return APValue();
737 } else {
738 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
739 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000740 Elements.push_back(APValue(f));
741 }
742 }
743 return APValue(&Elements[0], Elements.size());
744}
745
Mike Stump1eb44332009-09-09 15:08:12 +0000746APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000747VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000748 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000749 QualType EltTy = VT->getElementType();
750 APValue ZeroElement;
751 if (EltTy->isIntegerType())
752 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
753 else
754 ZeroElement =
755 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
756
757 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
758 return APValue(&Elements[0], Elements.size());
759}
760
761APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
762 bool BoolResult;
763 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
764 return APValue();
765
766 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
767
768 APValue Result;
769 if (EvaluateVector(EvalExpr, Result, Info))
770 return Result;
771 return APValue();
772}
773
Eli Friedman91110ee2009-02-23 04:23:56 +0000774APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
775 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
776 Info.EvalResult.HasSideEffects = true;
777 return GetZeroVector(E->getType());
778}
779
Nate Begeman59b5da62009-01-18 03:20:47 +0000780//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000781// Integer Evaluation
782//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000783
784namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000785class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000786 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000787 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000788 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000789public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000790 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000791 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000792
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000793 bool Success(const llvm::APSInt &SI, const Expr *E) {
Daniel Dunbar4fff4812009-02-21 18:14:20 +0000794 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000795 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000796 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000797 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000798 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000799 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000800 return true;
801 }
802
Daniel Dunbar131eb432009-02-19 09:06:44 +0000803 bool Success(const llvm::APInt &I, const Expr *E) {
Daniel Dunbar4fff4812009-02-21 18:14:20 +0000804 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000805 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000806 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000807 Result = APValue(APSInt(I));
808 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000809 return true;
810 }
811
812 bool Success(uint64_t Value, const Expr *E) {
Daniel Dunbar4fff4812009-02-21 18:14:20 +0000813 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000814 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000815 return true;
816 }
817
Anders Carlsson82206e22008-11-30 18:14:57 +0000818 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000819 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000820 if (Info.EvalResult.Diag == 0) {
821 Info.EvalResult.DiagLoc = L;
822 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000823 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000824 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000825 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000826 }
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Anders Carlssonc754aa62008-07-08 05:13:58 +0000828 //===--------------------------------------------------------------------===//
829 // Visitor Methods
830 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Chris Lattner32fea9d2008-11-12 07:43:42 +0000832 bool VisitStmt(Stmt *) {
833 assert(0 && "This should be called on integers, stmts are not integers");
834 return false;
835 }
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Chris Lattner32fea9d2008-11-12 07:43:42 +0000837 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000838 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000839 }
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Chris Lattnerb542afe2008-07-11 19:10:17 +0000841 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000842
Chris Lattner4c4867e2008-07-12 00:38:25 +0000843 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000844 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000845 }
846 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000847 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000848 }
849 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarac620de2008-10-24 08:07:57 +0000850 // Per gcc docs "this built-in function ignores top level
851 // qualifiers". We need to use the canonical version to properly
852 // be able to strip CRV qualifiers from the type.
853 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
854 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Mike Stump1eb44332009-09-09 15:08:12 +0000855 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
Daniel Dunbar131eb432009-02-19 09:06:44 +0000856 T1.getUnqualifiedType()),
857 E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000858 }
Eli Friedman04309752009-11-24 05:28:59 +0000859
860 bool CheckReferencedDecl(const Expr *E, const Decl *D);
861 bool VisitDeclRefExpr(const DeclRefExpr *E) {
862 return CheckReferencedDecl(E, E->getDecl());
863 }
864 bool VisitMemberExpr(const MemberExpr *E) {
865 if (CheckReferencedDecl(E, E->getMemberDecl())) {
866 // Conservatively assume a MemberExpr will have side-effects
867 Info.EvalResult.HasSideEffects = true;
868 return true;
869 }
870 return false;
871 }
872
Eli Friedmanc4a26382010-02-13 00:10:10 +0000873 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000874 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000875 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000876 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000877 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000878
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000879 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000880 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
881
Anders Carlsson3068d112008-11-16 19:01:22 +0000882 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000883 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000884 }
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Anders Carlsson3f704562008-12-21 22:39:40 +0000886 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000887 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +0000888 }
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Anders Carlsson3068d112008-11-16 19:01:22 +0000890 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000891 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000892 }
893
Eli Friedman664a1042009-02-27 04:45:43 +0000894 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
895 return Success(0, E);
896 }
897
Sebastian Redl64b45f72009-01-05 20:52:13 +0000898 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +0000899 return Success(E->EvaluateTrait(Info.Ctx), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000900 }
901
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000902 bool VisitChooseExpr(const ChooseExpr *E) {
903 return Visit(E->getChosenSubExpr(Info.Ctx));
904 }
905
Eli Friedman722c7172009-02-28 03:59:05 +0000906 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000907 bool VisitUnaryImag(const UnaryOperator *E);
908
Chris Lattnerfcee0012008-07-11 21:24:13 +0000909private:
Ken Dyck8b752f12010-01-27 17:10:57 +0000910 CharUnits GetAlignOfExpr(const Expr *E);
911 CharUnits GetAlignOfType(QualType T);
Eli Friedman664a1042009-02-27 04:45:43 +0000912 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000913};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000914} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000915
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000916static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000917 assert(E->getType()->isIntegralType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000918 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
919}
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000920
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000921static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000922 assert(E->getType()->isIntegralType());
923
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000924 APValue Val;
925 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
926 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000927 Result = Val.getInt();
928 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +0000929}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000930
Eli Friedman04309752009-11-24 05:28:59 +0000931bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000932 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +0000933 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
934 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +0000935
936 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +0000937 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000938 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
939 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +0000940
941 if (isa<ParmVarDecl>(D))
942 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
943
Eli Friedman04309752009-11-24 05:28:59 +0000944 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000945 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +0000946 if (APValue *V = VD->getEvaluatedValue()) {
947 if (V->isInt())
948 return Success(V->getInt(), E);
949 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
950 }
951
952 if (VD->isEvaluatingValue())
953 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
954
955 VD->setEvaluatingValue();
956
Douglas Gregor78d15832009-05-26 18:54:04 +0000957 if (Visit(const_cast<Expr*>(Init))) {
958 // Cache the evaluated value in the variable declaration.
Eli Friedmanc0131182009-12-03 20:31:57 +0000959 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +0000960 return true;
961 }
962
Eli Friedmanc0131182009-12-03 20:31:57 +0000963 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +0000964 return false;
965 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +0000966 }
967 }
968
Chris Lattner4c4867e2008-07-12 00:38:25 +0000969 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000970 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000971}
972
Chris Lattnera4d55d82008-10-06 06:40:35 +0000973/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
974/// as GCC.
975static int EvaluateBuiltinClassifyType(const CallExpr *E) {
976 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000977 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +0000978 enum gcc_type_class {
979 no_type_class = -1,
980 void_type_class, integer_type_class, char_type_class,
981 enumeral_type_class, boolean_type_class,
982 pointer_type_class, reference_type_class, offset_type_class,
983 real_type_class, complex_type_class,
984 function_type_class, method_type_class,
985 record_type_class, union_type_class,
986 array_type_class, string_type_class,
987 lang_type_class
988 };
Mike Stump1eb44332009-09-09 15:08:12 +0000989
990 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +0000991 // ideal, however it is what gcc does.
992 if (E->getNumArgs() == 0)
993 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Chris Lattnera4d55d82008-10-06 06:40:35 +0000995 QualType ArgTy = E->getArg(0)->getType();
996 if (ArgTy->isVoidType())
997 return void_type_class;
998 else if (ArgTy->isEnumeralType())
999 return enumeral_type_class;
1000 else if (ArgTy->isBooleanType())
1001 return boolean_type_class;
1002 else if (ArgTy->isCharType())
1003 return string_type_class; // gcc doesn't appear to use char_type_class
1004 else if (ArgTy->isIntegerType())
1005 return integer_type_class;
1006 else if (ArgTy->isPointerType())
1007 return pointer_type_class;
1008 else if (ArgTy->isReferenceType())
1009 return reference_type_class;
1010 else if (ArgTy->isRealType())
1011 return real_type_class;
1012 else if (ArgTy->isComplexType())
1013 return complex_type_class;
1014 else if (ArgTy->isFunctionType())
1015 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001016 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001017 return record_type_class;
1018 else if (ArgTy->isUnionType())
1019 return union_type_class;
1020 else if (ArgTy->isArrayType())
1021 return array_type_class;
1022 else if (ArgTy->isUnionType())
1023 return union_type_class;
1024 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1025 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1026 return -1;
1027}
1028
Eli Friedmanc4a26382010-02-13 00:10:10 +00001029bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001030 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001031 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001032 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001033
1034 case Builtin::BI__builtin_object_size: {
Mike Stump64eda9e2009-10-26 18:35:08 +00001035 const Expr *Arg = E->getArg(0)->IgnoreParens();
1036 Expr::EvalResult Base;
Eric Christopherb2aaf512010-01-19 22:58:35 +00001037
1038 // TODO: Perhaps we should let LLVM lower this?
Mike Stump660e6f72009-10-26 23:05:19 +00001039 if (Arg->EvaluateAsAny(Base, Info.Ctx)
Mike Stump64eda9e2009-10-26 18:35:08 +00001040 && Base.Val.getKind() == APValue::LValue
1041 && !Base.HasSideEffects)
1042 if (const Expr *LVBase = Base.Val.getLValueBase())
1043 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVBase)) {
1044 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Mike Stump460d1382009-10-28 21:22:24 +00001045 if (!VD->getType()->isIncompleteType()
1046 && VD->getType()->isObjectType()
1047 && !VD->getType()->isVariablyModifiedType()
1048 && !VD->getType()->isDependentType()) {
Ken Dyck199c3d62010-01-11 17:06:35 +00001049 CharUnits Size = Info.Ctx.getTypeSizeInChars(VD->getType());
Ken Dycka7305832010-01-15 12:37:54 +00001050 CharUnits Offset = Base.Val.getLValueOffset();
Ken Dyck199c3d62010-01-11 17:06:35 +00001051 if (!Offset.isNegative() && Offset <= Size)
1052 Size -= Offset;
Mike Stump460d1382009-10-28 21:22:24 +00001053 else
Ken Dyck199c3d62010-01-11 17:06:35 +00001054 Size = CharUnits::Zero();
1055 return Success(Size.getQuantity(), E);
Mike Stump460d1382009-10-28 21:22:24 +00001056 }
Mike Stump64eda9e2009-10-26 18:35:08 +00001057 }
1058 }
1059
Eric Christopherb2aaf512010-01-19 22:58:35 +00001060 // If evaluating the argument has side-effects we can't determine
1061 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001062 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001063 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001064 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001065 return Success(0, E);
1066 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001067
Mike Stump64eda9e2009-10-26 18:35:08 +00001068 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1069 }
1070
Chris Lattner019f4e82008-10-06 05:28:25 +00001071 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001072 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001074 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001075 // __builtin_constant_p always has one operand: it returns true if that
1076 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001077 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001078
1079 case Builtin::BI__builtin_eh_return_data_regno: {
1080 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1081 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1082 return Success(Operand, E);
1083 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001084
1085 case Builtin::BI__builtin_expect:
1086 return Visit(E->getArg(0));
Chris Lattner019f4e82008-10-06 05:28:25 +00001087 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001088}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001089
Chris Lattnerb542afe2008-07-11 19:10:17 +00001090bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001091 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001092 if (!Visit(E->getRHS()))
1093 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001094
Eli Friedman33ef1452009-02-26 10:19:36 +00001095 // If we can't evaluate the LHS, it might have side effects;
1096 // conservatively mark it.
1097 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1098 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001099
Anders Carlsson027f62e2008-12-01 02:07:06 +00001100 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001101 }
1102
1103 if (E->isLogicalOp()) {
1104 // These need to be handled specially because the operands aren't
1105 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001106 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001108 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001109 // We were able to evaluate the LHS, see if we can get away with not
1110 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Eli Friedman33ef1452009-02-26 10:19:36 +00001111 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001112 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001113
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001114 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001115 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001116 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001117 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001118 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001119 }
1120 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001121 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001122 // We can't evaluate the LHS; however, sometimes the result
1123 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Mike Stump1eb44332009-09-09 15:08:12 +00001124 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001125 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001126 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001127 // must have had side effects.
1128 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001129
1130 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001131 }
1132 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001133 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001134
Eli Friedmana6afa762008-11-13 06:09:17 +00001135 return false;
1136 }
1137
Anders Carlsson286f85e2008-11-16 07:17:21 +00001138 QualType LHSTy = E->getLHS()->getType();
1139 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001140
1141 if (LHSTy->isAnyComplexType()) {
1142 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001143 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001144
1145 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1146 return false;
1147
1148 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1149 return false;
1150
1151 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001152 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001153 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001154 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001155 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1156
Daniel Dunbar4087e242009-01-29 06:43:41 +00001157 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001158 return Success((CR_r == APFloat::cmpEqual &&
1159 CR_i == APFloat::cmpEqual), E);
1160 else {
1161 assert(E->getOpcode() == BinaryOperator::NE &&
1162 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001163 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001164 CR_r == APFloat::cmpLessThan ||
1165 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001166 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001167 CR_i == APFloat::cmpLessThan ||
1168 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001169 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001170 } else {
Daniel Dunbar4087e242009-01-29 06:43:41 +00001171 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001172 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1173 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1174 else {
1175 assert(E->getOpcode() == BinaryOperator::NE &&
1176 "Invalid compex comparison.");
1177 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1178 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1179 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001180 }
1181 }
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Anders Carlsson286f85e2008-11-16 07:17:21 +00001183 if (LHSTy->isRealFloatingType() &&
1184 RHSTy->isRealFloatingType()) {
1185 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Anders Carlsson286f85e2008-11-16 07:17:21 +00001187 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1188 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Anders Carlsson286f85e2008-11-16 07:17:21 +00001190 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1191 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Anders Carlsson286f85e2008-11-16 07:17:21 +00001193 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001194
Anders Carlsson286f85e2008-11-16 07:17:21 +00001195 switch (E->getOpcode()) {
1196 default:
1197 assert(0 && "Invalid binary operator!");
1198 case BinaryOperator::LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001199 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001200 case BinaryOperator::GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001201 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001202 case BinaryOperator::LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001203 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001204 case BinaryOperator::GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001205 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001206 E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001207 case BinaryOperator::EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001208 return Success(CR == APFloat::cmpEqual, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001209 case BinaryOperator::NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001210 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001211 || CR == APFloat::cmpLessThan
1212 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001213 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001214 }
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001216 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1217 if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001218 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001219 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1220 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001221
John McCallefdb83e2010-05-07 21:00:08 +00001222 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001223 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1224 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001225
Eli Friedman5bc86102009-06-14 02:17:33 +00001226 // Reject any bases from the normal codepath; we special-case comparisons
1227 // to null.
1228 if (LHSValue.getLValueBase()) {
1229 if (!E->isEqualityOp())
1230 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001231 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001232 return false;
1233 bool bres;
1234 if (!EvalPointerValueAsBool(LHSValue, bres))
1235 return false;
1236 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1237 } else if (RHSValue.getLValueBase()) {
1238 if (!E->isEqualityOp())
1239 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001240 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001241 return false;
1242 bool bres;
1243 if (!EvalPointerValueAsBool(RHSValue, bres))
1244 return false;
1245 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1246 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001247
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001248 if (E->getOpcode() == BinaryOperator::Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001249 QualType Type = E->getLHS()->getType();
1250 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001251
Ken Dycka7305832010-01-15 12:37:54 +00001252 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001253 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001254 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001255
Ken Dycka7305832010-01-15 12:37:54 +00001256 CharUnits Diff = LHSValue.getLValueOffset() -
1257 RHSValue.getLValueOffset();
1258 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001259 }
1260 bool Result;
1261 if (E->getOpcode() == BinaryOperator::EQ) {
1262 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001263 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001264 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1265 }
1266 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001267 }
1268 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001269 if (!LHSTy->isIntegralType() ||
1270 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001271 // We can't continue from here for non-integral types, and they
1272 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001273 return false;
1274 }
1275
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001276 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001277 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001278 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001279
Eli Friedman42edd0d2009-03-24 01:14:50 +00001280 APValue RHSVal;
1281 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001282 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001283
1284 // Handle cases like (unsigned long)&a + 4.
1285 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001286 CharUnits Offset = Result.getLValueOffset();
1287 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1288 RHSVal.getInt().getZExtValue());
Eli Friedman42edd0d2009-03-24 01:14:50 +00001289 if (E->getOpcode() == BinaryOperator::Add)
Ken Dycka7305832010-01-15 12:37:54 +00001290 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001291 else
Ken Dycka7305832010-01-15 12:37:54 +00001292 Offset -= AdditionalOffset;
1293 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001294 return true;
1295 }
1296
1297 // Handle cases like 4 + (unsigned long)&a
1298 if (E->getOpcode() == BinaryOperator::Add &&
1299 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001300 CharUnits Offset = RHSVal.getLValueOffset();
1301 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1302 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001303 return true;
1304 }
1305
1306 // All the following cases expect both operands to be an integer
1307 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001308 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001309
Eli Friedman42edd0d2009-03-24 01:14:50 +00001310 APSInt& RHS = RHSVal.getInt();
1311
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001312 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001313 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001314 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001315 case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1316 case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1317 case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1318 case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1319 case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1320 case BinaryOperator::Or: return Success(Result.getInt() | RHS, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001321 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001322 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001323 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001324 return Success(Result.getInt() / RHS, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001325 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001326 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001327 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001328 return Success(Result.getInt() % RHS, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001329 case BinaryOperator::Shl: {
Chris Lattner54176fd2008-07-12 00:14:42 +00001330 // FIXME: Warn about out of range shift amounts!
Mike Stump1eb44332009-09-09 15:08:12 +00001331 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001332 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1333 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001334 }
1335 case BinaryOperator::Shr: {
Mike Stump1eb44332009-09-09 15:08:12 +00001336 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001337 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1338 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001339 }
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001341 case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1342 case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1343 case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1344 case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1345 case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1346 case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001347 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001348}
1349
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001350bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001351 bool Cond;
1352 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001353 return false;
1354
Nuno Lopesa25bd552008-11-16 22:06:39 +00001355 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001356}
1357
Ken Dyck8b752f12010-01-27 17:10:57 +00001358CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001359 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1360 // the result is the size of the referenced type."
1361 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1362 // result shall be the alignment of the referenced type."
1363 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1364 T = Ref->getPointeeType();
1365
Chris Lattnere9feb472009-01-24 21:09:06 +00001366 // Get information about the alignment.
1367 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Douglas Gregor18857642009-04-30 17:32:17 +00001368
Eli Friedman2be58612009-05-30 21:09:44 +00001369 // __alignof is defined to return the preferred alignment.
Ken Dyck8b752f12010-01-27 17:10:57 +00001370 return CharUnits::fromQuantity(
1371 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
Chris Lattnere9feb472009-01-24 21:09:06 +00001372}
1373
Ken Dyck8b752f12010-01-27 17:10:57 +00001374CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001375 E = E->IgnoreParens();
1376
1377 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001378 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001379 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001380 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1381 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001382
Chris Lattneraf707ab2009-01-24 21:53:27 +00001383 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001384 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1385 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001386
Chris Lattnere9feb472009-01-24 21:09:06 +00001387 return GetAlignOfType(E->getType());
1388}
1389
1390
Sebastian Redl05189992008-11-11 17:56:53 +00001391/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1392/// expression's type.
1393bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001394 // Handle alignof separately.
1395 if (!E->isSizeOf()) {
1396 if (E->isArgumentType())
Ken Dyck8b752f12010-01-27 17:10:57 +00001397 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001398 else
Ken Dyck8b752f12010-01-27 17:10:57 +00001399 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001400 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001401
Sebastian Redl05189992008-11-11 17:56:53 +00001402 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl5d484e82009-11-23 17:18:46 +00001403 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1404 // the result is the size of the referenced type."
1405 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1406 // result shall be the alignment of the referenced type."
1407 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1408 SrcTy = Ref->getPointeeType();
Sebastian Redl05189992008-11-11 17:56:53 +00001409
Daniel Dunbar131eb432009-02-19 09:06:44 +00001410 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1411 // extension.
1412 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1413 return Success(1, E);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001414
Chris Lattnerfcee0012008-07-11 21:24:13 +00001415 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001416 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001417 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001418
Chris Lattnere9feb472009-01-24 21:09:06 +00001419 // Get information about the size.
Ken Dyck199c3d62010-01-11 17:06:35 +00001420 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001421}
1422
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001423bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1424 CharUnits Result;
1425 unsigned n = E->getNumComponents();
1426 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1427 if (n == 0)
1428 return false;
1429 QualType CurrentType = E->getTypeSourceInfo()->getType();
1430 for (unsigned i = 0; i != n; ++i) {
1431 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1432 switch (ON.getKind()) {
1433 case OffsetOfExpr::OffsetOfNode::Array: {
1434 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1435 APSInt IdxResult;
1436 if (!EvaluateInteger(Idx, IdxResult, Info))
1437 return false;
1438 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1439 if (!AT)
1440 return false;
1441 CurrentType = AT->getElementType();
1442 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1443 Result += IdxResult.getSExtValue() * ElementSize;
1444 break;
1445 }
1446
1447 case OffsetOfExpr::OffsetOfNode::Field: {
1448 FieldDecl *MemberDecl = ON.getField();
1449 const RecordType *RT = CurrentType->getAs<RecordType>();
1450 if (!RT)
1451 return false;
1452 RecordDecl *RD = RT->getDecl();
1453 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1454 unsigned i = 0;
1455 // FIXME: It would be nice if we didn't have to loop here!
1456 for (RecordDecl::field_iterator Field = RD->field_begin(),
1457 FieldEnd = RD->field_end();
1458 Field != FieldEnd; (void)++Field, ++i) {
1459 if (*Field == MemberDecl)
1460 break;
1461 }
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001462 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1463 Result += CharUnits::fromQuantity(
1464 RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001465 CurrentType = MemberDecl->getType().getNonReferenceType();
1466 break;
1467 }
1468
1469 case OffsetOfExpr::OffsetOfNode::Identifier:
1470 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001471 return false;
1472
1473 case OffsetOfExpr::OffsetOfNode::Base: {
1474 CXXBaseSpecifier *BaseSpec = ON.getBase();
1475 if (BaseSpec->isVirtual())
1476 return false;
1477
1478 // Find the layout of the class whose base we are looking into.
1479 const RecordType *RT = CurrentType->getAs<RecordType>();
1480 if (!RT)
1481 return false;
1482 RecordDecl *RD = RT->getDecl();
1483 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1484
1485 // Find the base class itself.
1486 CurrentType = BaseSpec->getType();
1487 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1488 if (!BaseRT)
1489 return false;
1490
1491 // Add the offset to the base.
1492 Result += CharUnits::fromQuantity(
1493 RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()))
1494 / Info.Ctx.getCharWidth());
1495 break;
1496 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001497 }
1498 }
1499 return Success(Result.getQuantity(), E);
1500}
1501
Chris Lattnerb542afe2008-07-11 19:10:17 +00001502bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001503 // Special case unary operators that do not need their subexpression
1504 // evaluated. offsetof/sizeof/alignof are all special.
Eli Friedman35183ac2009-02-27 06:44:11 +00001505 if (E->isOffsetOfOp()) {
1506 // The AST for offsetof is defined in such a way that we can just
1507 // directly Evaluate it as an l-value.
John McCallefdb83e2010-05-07 21:00:08 +00001508 LValue LV;
Eli Friedman35183ac2009-02-27 06:44:11 +00001509 if (!EvaluateLValue(E->getSubExpr(), LV, Info))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001510 return false;
Eli Friedman35183ac2009-02-27 06:44:11 +00001511 if (LV.getLValueBase())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001512 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001513 return Success(LV.getLValueOffset().getQuantity(), E);
Eli Friedman35183ac2009-02-27 06:44:11 +00001514 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001515
Eli Friedmana6afa762008-11-13 06:09:17 +00001516 if (E->getOpcode() == UnaryOperator::LNot) {
1517 // LNot's operand isn't necessarily an integer, so we handle it specially.
1518 bool bres;
1519 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1520 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001521 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001522 }
1523
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001524 // Only handle integral operations...
1525 if (!E->getSubExpr()->getType()->isIntegralType())
1526 return false;
1527
Chris Lattner87eae5e2008-07-11 22:52:41 +00001528 // Get the operand value into 'Result'.
1529 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001530 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001531
Chris Lattner75a48812008-07-11 22:15:16 +00001532 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001533 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001534 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1535 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001536 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001537 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001538 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1539 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001540 return true;
Chris Lattner75a48812008-07-11 22:15:16 +00001541 case UnaryOperator::Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001542 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001543 return true;
Chris Lattner75a48812008-07-11 22:15:16 +00001544 case UnaryOperator::Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001545 if (!Result.isInt()) return false;
1546 return Success(-Result.getInt(), E);
Chris Lattner75a48812008-07-11 22:15:16 +00001547 case UnaryOperator::Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001548 if (!Result.isInt()) return false;
1549 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001550 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001551}
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Chris Lattner732b2232008-07-12 01:15:53 +00001553/// HandleCast - This is used to evaluate implicit or explicit casts where the
1554/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001555bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001556 Expr *SubExpr = E->getSubExpr();
1557 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001558 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001559
Eli Friedman4efaa272008-11-12 09:44:48 +00001560 if (DestType->isBooleanType()) {
1561 bool BoolResult;
1562 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1563 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001564 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001565 }
1566
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001567 // Handle simple integer->integer casts.
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001568 if (SrcType->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001569 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001570 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001571
Eli Friedmanbe265702009-02-20 01:15:07 +00001572 if (!Result.isInt()) {
1573 // Only allow casts of lvalues if they are lossless.
1574 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1575 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001576
Daniel Dunbardd211642009-02-19 22:24:01 +00001577 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001578 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001579 }
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Chris Lattner732b2232008-07-12 01:15:53 +00001581 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001582 if (SrcType->isPointerType()) {
John McCallefdb83e2010-05-07 21:00:08 +00001583 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001584 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001585 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001586
Daniel Dunbardd211642009-02-19 22:24:01 +00001587 if (LV.getLValueBase()) {
1588 // Only allow based lvalue casts if they are lossless.
1589 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1590 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001591
John McCallefdb83e2010-05-07 21:00:08 +00001592 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001593 return true;
1594 }
1595
Ken Dycka7305832010-01-15 12:37:54 +00001596 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1597 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001598 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001599 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001600
Eli Friedmanbe265702009-02-20 01:15:07 +00001601 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1602 // This handles double-conversion cases, where there's both
1603 // an l-value promotion and an implicit conversion to int.
John McCallefdb83e2010-05-07 21:00:08 +00001604 LValue LV;
Eli Friedmanbe265702009-02-20 01:15:07 +00001605 if (!EvaluateLValue(SubExpr, LV, Info))
1606 return false;
1607
1608 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1609 return false;
1610
John McCallefdb83e2010-05-07 21:00:08 +00001611 LV.moveInto(Result);
Eli Friedmanbe265702009-02-20 01:15:07 +00001612 return true;
1613 }
1614
Eli Friedman1725f682009-04-22 19:23:09 +00001615 if (SrcType->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001616 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001617 if (!EvaluateComplex(SubExpr, C, Info))
1618 return false;
1619 if (C.isComplexFloat())
1620 return Success(HandleFloatToIntCast(DestType, SrcType,
1621 C.getComplexFloatReal(), Info.Ctx),
1622 E);
1623 else
1624 return Success(HandleIntToIntCast(DestType, SrcType,
1625 C.getComplexIntReal(), Info.Ctx), E);
1626 }
Eli Friedman2217c872009-02-22 11:46:18 +00001627 // FIXME: Handle vectors
1628
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001629 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001630 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001631
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001632 APFloat F(0.0);
1633 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001634 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001636 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001637}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001638
Eli Friedman722c7172009-02-28 03:59:05 +00001639bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1640 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001641 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001642 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1643 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1644 return Success(LV.getComplexIntReal(), E);
1645 }
1646
1647 return Visit(E->getSubExpr());
1648}
1649
Eli Friedman664a1042009-02-27 04:45:43 +00001650bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001651 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001652 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001653 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1654 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1655 return Success(LV.getComplexIntImag(), E);
1656 }
1657
Eli Friedman664a1042009-02-27 04:45:43 +00001658 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1659 Info.EvalResult.HasSideEffects = true;
1660 return Success(0, E);
1661}
1662
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001663//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001664// Float Evaluation
1665//===----------------------------------------------------------------------===//
1666
1667namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001668class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001669 : public StmtVisitor<FloatExprEvaluator, bool> {
1670 EvalInfo &Info;
1671 APFloat &Result;
1672public:
1673 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1674 : Info(info), Result(result) {}
1675
1676 bool VisitStmt(Stmt *S) {
1677 return false;
1678 }
1679
1680 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001681 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001682
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001683 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001684 bool VisitBinaryOperator(const BinaryOperator *E);
1685 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001686 bool VisitCastExpr(CastExpr *E);
1687 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001688 bool VisitConditionalOperator(ConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001689
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001690 bool VisitChooseExpr(const ChooseExpr *E)
1691 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1692 bool VisitUnaryExtension(const UnaryOperator *E)
1693 { return Visit(E->getSubExpr()); }
1694
1695 // FIXME: Missing: __real__/__imag__, array subscript of vector,
Eli Friedman67f85fc2009-12-04 02:12:53 +00001696 // member of vector, ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001697};
1698} // end anonymous namespace
1699
1700static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001701 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001702 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1703}
1704
John McCalldb7b72a2010-02-28 13:00:19 +00001705static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1706 QualType ResultTy,
1707 const Expr *Arg,
1708 bool SNaN,
1709 llvm::APFloat &Result) {
1710 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1711 if (!S) return false;
1712
1713 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1714
1715 llvm::APInt fill;
1716
1717 // Treat empty strings as if they were zero.
1718 if (S->getString().empty())
1719 fill = llvm::APInt(32, 0);
1720 else if (S->getString().getAsInteger(0, fill))
1721 return false;
1722
1723 if (SNaN)
1724 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1725 else
1726 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1727 return true;
1728}
1729
Chris Lattner019f4e82008-10-06 05:28:25 +00001730bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001731 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001732 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001733 case Builtin::BI__builtin_huge_val:
1734 case Builtin::BI__builtin_huge_valf:
1735 case Builtin::BI__builtin_huge_vall:
1736 case Builtin::BI__builtin_inf:
1737 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001738 case Builtin::BI__builtin_infl: {
1739 const llvm::fltSemantics &Sem =
1740 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001741 Result = llvm::APFloat::getInf(Sem);
1742 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001743 }
Mike Stump1eb44332009-09-09 15:08:12 +00001744
John McCalldb7b72a2010-02-28 13:00:19 +00001745 case Builtin::BI__builtin_nans:
1746 case Builtin::BI__builtin_nansf:
1747 case Builtin::BI__builtin_nansl:
1748 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1749 true, Result);
1750
Chris Lattner9e621712008-10-06 06:31:58 +00001751 case Builtin::BI__builtin_nan:
1752 case Builtin::BI__builtin_nanf:
1753 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00001754 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00001755 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00001756 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1757 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001758
1759 case Builtin::BI__builtin_fabs:
1760 case Builtin::BI__builtin_fabsf:
1761 case Builtin::BI__builtin_fabsl:
1762 if (!EvaluateFloat(E->getArg(0), Result, Info))
1763 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001765 if (Result.isNegative())
1766 Result.changeSign();
1767 return true;
1768
Mike Stump1eb44332009-09-09 15:08:12 +00001769 case Builtin::BI__builtin_copysign:
1770 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001771 case Builtin::BI__builtin_copysignl: {
1772 APFloat RHS(0.);
1773 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1774 !EvaluateFloat(E->getArg(1), RHS, Info))
1775 return false;
1776 Result.copySign(RHS);
1777 return true;
1778 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001779 }
1780}
1781
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001782bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopesa468d342008-11-19 17:44:31 +00001783 if (E->getOpcode() == UnaryOperator::Deref)
1784 return false;
1785
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001786 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1787 return false;
1788
1789 switch (E->getOpcode()) {
1790 default: return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001791 case UnaryOperator::Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001792 return true;
1793 case UnaryOperator::Minus:
1794 Result.changeSign();
1795 return true;
1796 }
1797}
Chris Lattner019f4e82008-10-06 05:28:25 +00001798
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001799bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman7f92f032009-11-16 04:25:37 +00001800 if (E->getOpcode() == BinaryOperator::Comma) {
1801 if (!EvaluateFloat(E->getRHS(), Result, Info))
1802 return false;
1803
1804 // If we can't evaluate the LHS, it might have side effects;
1805 // conservatively mark it.
1806 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1807 Info.EvalResult.HasSideEffects = true;
1808
1809 return true;
1810 }
1811
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001812 // FIXME: Diagnostics? I really don't understand how the warnings
1813 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001814 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001815 if (!EvaluateFloat(E->getLHS(), Result, Info))
1816 return false;
1817 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1818 return false;
1819
1820 switch (E->getOpcode()) {
1821 default: return false;
1822 case BinaryOperator::Mul:
1823 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1824 return true;
1825 case BinaryOperator::Add:
1826 Result.add(RHS, APFloat::rmNearestTiesToEven);
1827 return true;
1828 case BinaryOperator::Sub:
1829 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1830 return true;
1831 case BinaryOperator::Div:
1832 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1833 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001834 }
1835}
1836
1837bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1838 Result = E->getValue();
1839 return true;
1840}
1841
Eli Friedman4efaa272008-11-12 09:44:48 +00001842bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1843 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Eli Friedman4efaa272008-11-12 09:44:48 +00001845 if (SubExpr->getType()->isIntegralType()) {
1846 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001847 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00001848 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001849 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001850 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001851 return true;
1852 }
1853 if (SubExpr->getType()->isRealFloatingType()) {
1854 if (!Visit(SubExpr))
1855 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001856 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1857 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001858 return true;
1859 }
Eli Friedman2217c872009-02-22 11:46:18 +00001860 // FIXME: Handle complex types
Eli Friedman4efaa272008-11-12 09:44:48 +00001861
1862 return false;
1863}
1864
1865bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1866 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1867 return true;
1868}
1869
Eli Friedman67f85fc2009-12-04 02:12:53 +00001870bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
1871 bool Cond;
1872 if (!HandleConversionToBool(E->getCond(), Cond, Info))
1873 return false;
1874
1875 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1876}
1877
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001878//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001879// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001880//===----------------------------------------------------------------------===//
1881
1882namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001883class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00001884 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001885 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00001886 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001888public:
John McCallf4cf1a12010-05-07 17:22:02 +00001889 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
1890 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001892 //===--------------------------------------------------------------------===//
1893 // Visitor Methods
1894 //===--------------------------------------------------------------------===//
1895
John McCallf4cf1a12010-05-07 17:22:02 +00001896 bool VisitStmt(Stmt *S) {
1897 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899
John McCallf4cf1a12010-05-07 17:22:02 +00001900 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001901
John McCallf4cf1a12010-05-07 17:22:02 +00001902 bool VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001903 Expr* SubExpr = E->getSubExpr();
1904
1905 if (SubExpr->getType()->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001906 Result.makeComplexFloat();
1907 APFloat &Imag = Result.FloatImag;
1908 if (!EvaluateFloat(SubExpr, Imag, Info))
1909 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001910
John McCallf4cf1a12010-05-07 17:22:02 +00001911 Result.FloatReal = APFloat(Imag.getSemantics());
1912 return true;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001913 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001914 assert(SubExpr->getType()->isIntegerType() &&
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001915 "Unexpected imaginary literal.");
1916
John McCallf4cf1a12010-05-07 17:22:02 +00001917 Result.makeComplexInt();
1918 APSInt &Imag = Result.IntImag;
1919 if (!EvaluateInteger(SubExpr, Imag, Info))
1920 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001921
John McCallf4cf1a12010-05-07 17:22:02 +00001922 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
1923 return true;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001924 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001925 }
1926
John McCallf4cf1a12010-05-07 17:22:02 +00001927 bool VisitCastExpr(CastExpr *E) {
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001928 Expr* SubExpr = E->getSubExpr();
John McCall183700f2009-09-21 23:43:11 +00001929 QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001930 QualType SubType = SubExpr->getType();
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001931
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001932 if (SubType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001933 APFloat &Real = Result.FloatReal;
1934 if (!EvaluateFloat(SubExpr, Real, Info))
1935 return false;
Eli Friedman1725f682009-04-22 19:23:09 +00001936
1937 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001938 Result.makeComplexFloat();
1939 Real = HandleFloatToFloatCast(EltType, SubType, Real, Info.Ctx);
1940 Result.FloatImag = APFloat(Real.getSemantics());
1941 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00001942 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00001943 Result.makeComplexInt();
1944 Result.IntReal = HandleFloatToIntCast(EltType, SubType, Real, Info.Ctx);
1945 Result.IntImag = APSInt(Result.IntReal.getBitWidth(),
1946 !Result.IntReal.isSigned());
1947 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00001948 }
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001949 } else if (SubType->isIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001950 APSInt &Real = Result.IntReal;
1951 if (!EvaluateInteger(SubExpr, Real, Info))
1952 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001953
Eli Friedman1725f682009-04-22 19:23:09 +00001954 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001955 Result.makeComplexFloat();
1956 Result.FloatReal
1957 = HandleIntToFloatCast(EltType, SubType, Real, Info.Ctx);
1958 Result.FloatImag = APFloat(Result.FloatReal.getSemantics());
1959 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00001960 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00001961 Result.makeComplexInt();
1962 Real = HandleIntToIntCast(EltType, SubType, Real, Info.Ctx);
1963 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
1964 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00001965 }
John McCall183700f2009-09-21 23:43:11 +00001966 } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001967 if (!Visit(SubExpr))
1968 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001969
1970 QualType SrcType = CT->getElementType();
1971
John McCallf4cf1a12010-05-07 17:22:02 +00001972 if (Result.isComplexFloat()) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001973 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001974 Result.makeComplexFloat();
1975 Result.FloatReal = HandleFloatToFloatCast(EltType, SrcType,
1976 Result.FloatReal,
1977 Info.Ctx);
1978 Result.FloatImag = HandleFloatToFloatCast(EltType, SrcType,
1979 Result.FloatImag,
1980 Info.Ctx);
1981 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001982 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00001983 Result.makeComplexInt();
1984 Result.IntReal = HandleFloatToIntCast(EltType, SrcType,
1985 Result.FloatReal,
1986 Info.Ctx);
1987 Result.IntImag = HandleFloatToIntCast(EltType, SrcType,
1988 Result.FloatImag,
1989 Info.Ctx);
1990 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001991 }
1992 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00001993 assert(Result.isComplexInt() && "Invalid evaluate result.");
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001994 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001995 Result.makeComplexFloat();
1996 Result.FloatReal = HandleIntToFloatCast(EltType, SrcType,
1997 Result.IntReal,
1998 Info.Ctx);
1999 Result.FloatImag = HandleIntToFloatCast(EltType, SrcType,
2000 Result.IntImag,
2001 Info.Ctx);
2002 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002003 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002004 Result.makeComplexInt();
2005 Result.IntReal = HandleIntToIntCast(EltType, SrcType,
2006 Result.IntReal,
2007 Info.Ctx);
2008 Result.IntImag = HandleIntToIntCast(EltType, SrcType,
2009 Result.IntImag,
2010 Info.Ctx);
2011 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002012 }
2013 }
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002014 }
2015
2016 // FIXME: Handle more casts.
John McCallf4cf1a12010-05-07 17:22:02 +00002017 return false;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002018 }
Mike Stump1eb44332009-09-09 15:08:12 +00002019
John McCallf4cf1a12010-05-07 17:22:02 +00002020 bool VisitBinaryOperator(const BinaryOperator *E);
2021 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002022 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002023 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002024 { return Visit(E->getSubExpr()); }
2025 // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
Eli Friedman2217c872009-02-22 11:46:18 +00002026 // conditional ?:, comma
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002027};
2028} // end anonymous namespace
2029
John McCallf4cf1a12010-05-07 17:22:02 +00002030static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2031 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002032 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002033 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002034}
2035
John McCallf4cf1a12010-05-07 17:22:02 +00002036bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2037 if (!Visit(E->getLHS()))
2038 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002039
John McCallf4cf1a12010-05-07 17:22:02 +00002040 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002041 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002042 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002043
Daniel Dunbar3f279872009-01-29 01:32:56 +00002044 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2045 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002046 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002047 default: return false;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002048 case BinaryOperator::Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002049 if (Result.isComplexFloat()) {
2050 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2051 APFloat::rmNearestTiesToEven);
2052 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2053 APFloat::rmNearestTiesToEven);
2054 } else {
2055 Result.getComplexIntReal() += RHS.getComplexIntReal();
2056 Result.getComplexIntImag() += RHS.getComplexIntImag();
2057 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002058 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002059 case BinaryOperator::Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002060 if (Result.isComplexFloat()) {
2061 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2062 APFloat::rmNearestTiesToEven);
2063 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2064 APFloat::rmNearestTiesToEven);
2065 } else {
2066 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2067 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2068 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002069 break;
2070 case BinaryOperator::Mul:
2071 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002072 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002073 APFloat &LHS_r = LHS.getComplexFloatReal();
2074 APFloat &LHS_i = LHS.getComplexFloatImag();
2075 APFloat &RHS_r = RHS.getComplexFloatReal();
2076 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Daniel Dunbar3f279872009-01-29 01:32:56 +00002078 APFloat Tmp = LHS_r;
2079 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2080 Result.getComplexFloatReal() = Tmp;
2081 Tmp = LHS_i;
2082 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2083 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2084
2085 Tmp = LHS_r;
2086 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2087 Result.getComplexFloatImag() = Tmp;
2088 Tmp = LHS_i;
2089 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2090 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2091 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002092 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002093 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002094 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2095 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002096 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002097 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2098 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2099 }
2100 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002101 }
2102
John McCallf4cf1a12010-05-07 17:22:02 +00002103 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002104}
2105
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002106//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002107// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002108//===----------------------------------------------------------------------===//
2109
John McCallefdb83e2010-05-07 21:00:08 +00002110static bool Evaluate(const Expr *E, EvalInfo &Info) {
2111 if (E->getType()->isVectorType()) {
2112 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002113 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002114 } else if (E->getType()->isIntegerType()) {
2115 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002116 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002117 } else if (E->getType()->hasPointerRepresentation()) {
2118 LValue LV;
2119 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002120 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002121 LV.moveInto(Info.EvalResult.Val);
2122 } else if (E->getType()->isRealFloatingType()) {
2123 llvm::APFloat F(0.0);
2124 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002125 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002126
John McCallefdb83e2010-05-07 21:00:08 +00002127 Info.EvalResult.Val = APValue(F);
2128 } else if (E->getType()->isAnyComplexType()) {
2129 ComplexValue C;
2130 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002131 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002132 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002133 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002134 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002135
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002136 return true;
2137}
2138
John McCallefdb83e2010-05-07 21:00:08 +00002139/// Evaluate - Return true if this is a constant which we can fold using
2140/// any crazy technique (that has nothing to do with language standards) that
2141/// we want to. If this function returns true, it returns the folded constant
2142/// in Result.
2143bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2144 EvalInfo Info(Ctx, Result);
2145 return ::Evaluate(this, Info);
2146}
2147
Mike Stump660e6f72009-10-26 23:05:19 +00002148bool Expr::EvaluateAsAny(EvalResult &Result, ASTContext &Ctx) const {
2149 EvalInfo Info(Ctx, Result, true);
John McCallefdb83e2010-05-07 21:00:08 +00002150 return ::Evaluate(this, Info);
Mike Stump660e6f72009-10-26 23:05:19 +00002151}
2152
John McCallcd7a4452010-01-05 23:42:56 +00002153bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2154 EvalResult Scratch;
2155 EvalInfo Info(Ctx, Scratch);
2156
2157 return HandleConversionToBool(this, Result, Info);
2158}
2159
Anders Carlsson1b782762009-04-10 04:54:13 +00002160bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2161 EvalInfo Info(Ctx, Result);
2162
John McCallefdb83e2010-05-07 21:00:08 +00002163 LValue LV;
2164 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects) {
2165 LV.moveInto(Result.Val);
2166 return true;
2167 }
2168 return false;
Anders Carlsson1b782762009-04-10 04:54:13 +00002169}
2170
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002171bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2172 EvalInfo Info(Ctx, Result, true);
2173
John McCallefdb83e2010-05-07 21:00:08 +00002174 LValue LV;
2175 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects) {
2176 LV.moveInto(Result.Val);
2177 return true;
2178 }
2179 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002180}
2181
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002182/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002183/// folded, but discard the result.
2184bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002185 EvalResult Result;
2186 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002187}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002188
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002189bool Expr::HasSideEffects(ASTContext &Ctx) const {
2190 Expr::EvalResult Result;
2191 EvalInfo Info(Ctx, Result);
2192 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2193}
2194
Anders Carlsson51fe9962008-11-22 21:04:56 +00002195APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002196 EvalResult EvalResult;
2197 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarf1853192009-01-15 18:32:35 +00002198 Result = Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002199 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002200 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002201
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002202 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002203}
John McCalld905f5a2010-05-07 05:32:02 +00002204
2205/// isIntegerConstantExpr - this recursive routine will test if an expression is
2206/// an integer constant expression.
2207
2208/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2209/// comma, etc
2210///
2211/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2212/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2213/// cast+dereference.
2214
2215// CheckICE - This function does the fundamental ICE checking: the returned
2216// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2217// Note that to reduce code duplication, this helper does no evaluation
2218// itself; the caller checks whether the expression is evaluatable, and
2219// in the rare cases where CheckICE actually cares about the evaluated
2220// value, it calls into Evalute.
2221//
2222// Meanings of Val:
2223// 0: This expression is an ICE if it can be evaluated by Evaluate.
2224// 1: This expression is not an ICE, but if it isn't evaluated, it's
2225// a legal subexpression for an ICE. This return value is used to handle
2226// the comma operator in C99 mode.
2227// 2: This expression is not an ICE, and is not a legal subexpression for one.
2228
2229struct ICEDiag {
2230 unsigned Val;
2231 SourceLocation Loc;
2232
2233 public:
2234 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2235 ICEDiag() : Val(0) {}
2236};
2237
2238ICEDiag NoDiag() { return ICEDiag(); }
2239
2240static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2241 Expr::EvalResult EVResult;
2242 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2243 !EVResult.Val.isInt()) {
2244 return ICEDiag(2, E->getLocStart());
2245 }
2246 return NoDiag();
2247}
2248
2249static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2250 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
2251 if (!E->getType()->isIntegralType()) {
2252 return ICEDiag(2, E->getLocStart());
2253 }
2254
2255 switch (E->getStmtClass()) {
2256#define STMT(Node, Base) case Expr::Node##Class:
2257#define EXPR(Node, Base)
2258#include "clang/AST/StmtNodes.inc"
2259 case Expr::PredefinedExprClass:
2260 case Expr::FloatingLiteralClass:
2261 case Expr::ImaginaryLiteralClass:
2262 case Expr::StringLiteralClass:
2263 case Expr::ArraySubscriptExprClass:
2264 case Expr::MemberExprClass:
2265 case Expr::CompoundAssignOperatorClass:
2266 case Expr::CompoundLiteralExprClass:
2267 case Expr::ExtVectorElementExprClass:
2268 case Expr::InitListExprClass:
2269 case Expr::DesignatedInitExprClass:
2270 case Expr::ImplicitValueInitExprClass:
2271 case Expr::ParenListExprClass:
2272 case Expr::VAArgExprClass:
2273 case Expr::AddrLabelExprClass:
2274 case Expr::StmtExprClass:
2275 case Expr::CXXMemberCallExprClass:
2276 case Expr::CXXDynamicCastExprClass:
2277 case Expr::CXXTypeidExprClass:
2278 case Expr::CXXNullPtrLiteralExprClass:
2279 case Expr::CXXThisExprClass:
2280 case Expr::CXXThrowExprClass:
2281 case Expr::CXXNewExprClass:
2282 case Expr::CXXDeleteExprClass:
2283 case Expr::CXXPseudoDestructorExprClass:
2284 case Expr::UnresolvedLookupExprClass:
2285 case Expr::DependentScopeDeclRefExprClass:
2286 case Expr::CXXConstructExprClass:
2287 case Expr::CXXBindTemporaryExprClass:
2288 case Expr::CXXBindReferenceExprClass:
2289 case Expr::CXXExprWithTemporariesClass:
2290 case Expr::CXXTemporaryObjectExprClass:
2291 case Expr::CXXUnresolvedConstructExprClass:
2292 case Expr::CXXDependentScopeMemberExprClass:
2293 case Expr::UnresolvedMemberExprClass:
2294 case Expr::ObjCStringLiteralClass:
2295 case Expr::ObjCEncodeExprClass:
2296 case Expr::ObjCMessageExprClass:
2297 case Expr::ObjCSelectorExprClass:
2298 case Expr::ObjCProtocolExprClass:
2299 case Expr::ObjCIvarRefExprClass:
2300 case Expr::ObjCPropertyRefExprClass:
2301 case Expr::ObjCImplicitSetterGetterRefExprClass:
2302 case Expr::ObjCSuperExprClass:
2303 case Expr::ObjCIsaExprClass:
2304 case Expr::ShuffleVectorExprClass:
2305 case Expr::BlockExprClass:
2306 case Expr::BlockDeclRefExprClass:
2307 case Expr::NoStmtClass:
2308 return ICEDiag(2, E->getLocStart());
2309
2310 case Expr::GNUNullExprClass:
2311 // GCC considers the GNU __null value to be an integral constant expression.
2312 return NoDiag();
2313
2314 case Expr::ParenExprClass:
2315 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2316 case Expr::IntegerLiteralClass:
2317 case Expr::CharacterLiteralClass:
2318 case Expr::CXXBoolLiteralExprClass:
2319 case Expr::CXXZeroInitValueExprClass:
2320 case Expr::TypesCompatibleExprClass:
2321 case Expr::UnaryTypeTraitExprClass:
2322 return NoDiag();
2323 case Expr::CallExprClass:
2324 case Expr::CXXOperatorCallExprClass: {
2325 const CallExpr *CE = cast<CallExpr>(E);
2326 if (CE->isBuiltinCall(Ctx))
2327 return CheckEvalInICE(E, Ctx);
2328 return ICEDiag(2, E->getLocStart());
2329 }
2330 case Expr::DeclRefExprClass:
2331 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2332 return NoDiag();
2333 if (Ctx.getLangOptions().CPlusPlus &&
2334 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2335 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2336
2337 // Parameter variables are never constants. Without this check,
2338 // getAnyInitializer() can find a default argument, which leads
2339 // to chaos.
2340 if (isa<ParmVarDecl>(D))
2341 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2342
2343 // C++ 7.1.5.1p2
2344 // A variable of non-volatile const-qualified integral or enumeration
2345 // type initialized by an ICE can be used in ICEs.
2346 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2347 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2348 if (Quals.hasVolatile() || !Quals.hasConst())
2349 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2350
2351 // Look for a declaration of this variable that has an initializer.
2352 const VarDecl *ID = 0;
2353 const Expr *Init = Dcl->getAnyInitializer(ID);
2354 if (Init) {
2355 if (ID->isInitKnownICE()) {
2356 // We have already checked whether this subexpression is an
2357 // integral constant expression.
2358 if (ID->isInitICE())
2359 return NoDiag();
2360 else
2361 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2362 }
2363
2364 // It's an ICE whether or not the definition we found is
2365 // out-of-line. See DR 721 and the discussion in Clang PR
2366 // 6206 for details.
2367
2368 if (Dcl->isCheckingICE()) {
2369 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2370 }
2371
2372 Dcl->setCheckingICE();
2373 ICEDiag Result = CheckICE(Init, Ctx);
2374 // Cache the result of the ICE test.
2375 Dcl->setInitKnownICE(Result.Val == 0);
2376 return Result;
2377 }
2378 }
2379 }
2380 return ICEDiag(2, E->getLocStart());
2381 case Expr::UnaryOperatorClass: {
2382 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2383 switch (Exp->getOpcode()) {
2384 case UnaryOperator::PostInc:
2385 case UnaryOperator::PostDec:
2386 case UnaryOperator::PreInc:
2387 case UnaryOperator::PreDec:
2388 case UnaryOperator::AddrOf:
2389 case UnaryOperator::Deref:
2390 return ICEDiag(2, E->getLocStart());
2391 case UnaryOperator::Extension:
2392 case UnaryOperator::LNot:
2393 case UnaryOperator::Plus:
2394 case UnaryOperator::Minus:
2395 case UnaryOperator::Not:
2396 case UnaryOperator::Real:
2397 case UnaryOperator::Imag:
2398 return CheckICE(Exp->getSubExpr(), Ctx);
2399 case UnaryOperator::OffsetOf:
2400 break;
2401 }
2402
2403 // OffsetOf falls through here.
2404 }
2405 case Expr::OffsetOfExprClass: {
2406 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2407 // Evaluate matches the proposed gcc behavior for cases like
2408 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2409 // compliance: we should warn earlier for offsetof expressions with
2410 // array subscripts that aren't ICEs, and if the array subscripts
2411 // are ICEs, the value of the offsetof must be an integer constant.
2412 return CheckEvalInICE(E, Ctx);
2413 }
2414 case Expr::SizeOfAlignOfExprClass: {
2415 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2416 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2417 return ICEDiag(2, E->getLocStart());
2418 return NoDiag();
2419 }
2420 case Expr::BinaryOperatorClass: {
2421 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2422 switch (Exp->getOpcode()) {
2423 case BinaryOperator::PtrMemD:
2424 case BinaryOperator::PtrMemI:
2425 case BinaryOperator::Assign:
2426 case BinaryOperator::MulAssign:
2427 case BinaryOperator::DivAssign:
2428 case BinaryOperator::RemAssign:
2429 case BinaryOperator::AddAssign:
2430 case BinaryOperator::SubAssign:
2431 case BinaryOperator::ShlAssign:
2432 case BinaryOperator::ShrAssign:
2433 case BinaryOperator::AndAssign:
2434 case BinaryOperator::XorAssign:
2435 case BinaryOperator::OrAssign:
2436 return ICEDiag(2, E->getLocStart());
2437
2438 case BinaryOperator::Mul:
2439 case BinaryOperator::Div:
2440 case BinaryOperator::Rem:
2441 case BinaryOperator::Add:
2442 case BinaryOperator::Sub:
2443 case BinaryOperator::Shl:
2444 case BinaryOperator::Shr:
2445 case BinaryOperator::LT:
2446 case BinaryOperator::GT:
2447 case BinaryOperator::LE:
2448 case BinaryOperator::GE:
2449 case BinaryOperator::EQ:
2450 case BinaryOperator::NE:
2451 case BinaryOperator::And:
2452 case BinaryOperator::Xor:
2453 case BinaryOperator::Or:
2454 case BinaryOperator::Comma: {
2455 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2456 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2457 if (Exp->getOpcode() == BinaryOperator::Div ||
2458 Exp->getOpcode() == BinaryOperator::Rem) {
2459 // Evaluate gives an error for undefined Div/Rem, so make sure
2460 // we don't evaluate one.
2461 if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2462 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2463 if (REval == 0)
2464 return ICEDiag(1, E->getLocStart());
2465 if (REval.isSigned() && REval.isAllOnesValue()) {
2466 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2467 if (LEval.isMinSignedValue())
2468 return ICEDiag(1, E->getLocStart());
2469 }
2470 }
2471 }
2472 if (Exp->getOpcode() == BinaryOperator::Comma) {
2473 if (Ctx.getLangOptions().C99) {
2474 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2475 // if it isn't evaluated.
2476 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2477 return ICEDiag(1, E->getLocStart());
2478 } else {
2479 // In both C89 and C++, commas in ICEs are illegal.
2480 return ICEDiag(2, E->getLocStart());
2481 }
2482 }
2483 if (LHSResult.Val >= RHSResult.Val)
2484 return LHSResult;
2485 return RHSResult;
2486 }
2487 case BinaryOperator::LAnd:
2488 case BinaryOperator::LOr: {
2489 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2490 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2491 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2492 // Rare case where the RHS has a comma "side-effect"; we need
2493 // to actually check the condition to see whether the side
2494 // with the comma is evaluated.
2495 if ((Exp->getOpcode() == BinaryOperator::LAnd) !=
2496 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2497 return RHSResult;
2498 return NoDiag();
2499 }
2500
2501 if (LHSResult.Val >= RHSResult.Val)
2502 return LHSResult;
2503 return RHSResult;
2504 }
2505 }
2506 }
2507 case Expr::ImplicitCastExprClass:
2508 case Expr::CStyleCastExprClass:
2509 case Expr::CXXFunctionalCastExprClass:
2510 case Expr::CXXStaticCastExprClass:
2511 case Expr::CXXReinterpretCastExprClass:
2512 case Expr::CXXConstCastExprClass: {
2513 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
2514 if (SubExpr->getType()->isIntegralType())
2515 return CheckICE(SubExpr, Ctx);
2516 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2517 return NoDiag();
2518 return ICEDiag(2, E->getLocStart());
2519 }
2520 case Expr::ConditionalOperatorClass: {
2521 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2522 // If the condition (ignoring parens) is a __builtin_constant_p call,
2523 // then only the true side is actually considered in an integer constant
2524 // expression, and it is fully evaluated. This is an important GNU
2525 // extension. See GCC PR38377 for discussion.
2526 if (const CallExpr *CallCE
2527 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2528 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2529 Expr::EvalResult EVResult;
2530 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2531 !EVResult.Val.isInt()) {
2532 return ICEDiag(2, E->getLocStart());
2533 }
2534 return NoDiag();
2535 }
2536 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2537 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2538 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2539 if (CondResult.Val == 2)
2540 return CondResult;
2541 if (TrueResult.Val == 2)
2542 return TrueResult;
2543 if (FalseResult.Val == 2)
2544 return FalseResult;
2545 if (CondResult.Val == 1)
2546 return CondResult;
2547 if (TrueResult.Val == 0 && FalseResult.Val == 0)
2548 return NoDiag();
2549 // Rare case where the diagnostics depend on which side is evaluated
2550 // Note that if we get here, CondResult is 0, and at least one of
2551 // TrueResult and FalseResult is non-zero.
2552 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2553 return FalseResult;
2554 }
2555 return TrueResult;
2556 }
2557 case Expr::CXXDefaultArgExprClass:
2558 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2559 case Expr::ChooseExprClass: {
2560 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2561 }
2562 }
2563
2564 // Silence a GCC warning
2565 return ICEDiag(2, E->getLocStart());
2566}
2567
2568bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2569 SourceLocation *Loc, bool isEvaluated) const {
2570 ICEDiag d = CheckICE(this, Ctx);
2571 if (d.Val != 0) {
2572 if (Loc) *Loc = d.Loc;
2573 return false;
2574 }
2575 EvalResult EvalResult;
2576 if (!Evaluate(EvalResult, Ctx))
2577 llvm_unreachable("ICE cannot be evaluated!");
2578 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2579 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2580 Result = EvalResult.Val.getInt();
2581 return true;
2582}