blob: 524afb11b6a44f2e57e2efebf989a154345337a9 [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.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Benjamin Kramerc54061a2011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
49 /// EvalResult - Contains information about the evaluation.
50 Expr::EvalResult &EvalResult;
51
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
61 : Ctx(ctx), EvalResult(evalresult) {}
62 };
63
John McCallf4cf1a12010-05-07 17:22:02 +000064 struct ComplexValue {
65 private:
66 bool IsInt;
67
68 public:
69 APSInt IntReal, IntImag;
70 APFloat FloatReal, FloatImag;
71
72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
73
74 void makeComplexFloat() { IsInt = false; }
75 bool isComplexFloat() const { return !IsInt; }
76 APFloat &getComplexFloatReal() { return FloatReal; }
77 APFloat &getComplexFloatImag() { return FloatImag; }
78
79 void makeComplexInt() { IsInt = true; }
80 bool isComplexInt() const { return IsInt; }
81 APSInt &getComplexIntReal() { return IntReal; }
82 APSInt &getComplexIntImag() { return IntImag; }
83
John McCall56ca35d2011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCall56ca35d2011-02-17 10:25:35 +000090 void setFrom(const APValue &v) {
91 assert(v.isComplexFloat() || v.isComplexInt());
92 if (v.isComplexFloat()) {
93 makeComplexFloat();
94 FloatReal = v.getComplexFloatReal();
95 FloatImag = v.getComplexFloatImag();
96 } else {
97 makeComplexInt();
98 IntReal = v.getComplexIntReal();
99 IntImag = v.getComplexIntImag();
100 }
101 }
John McCallf4cf1a12010-05-07 17:22:02 +0000102 };
John McCallefdb83e2010-05-07 21:00:08 +0000103
104 struct LValue {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000105 const Expr *Base;
John McCallefdb83e2010-05-07 21:00:08 +0000106 CharUnits Offset;
107
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000108 const Expr *getLValueBase() { return Base; }
John McCallefdb83e2010-05-07 21:00:08 +0000109 CharUnits getLValueOffset() { return Offset; }
110
John McCall56ca35d2011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCallefdb83e2010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCall56ca35d2011-02-17 10:25:35 +0000114 void setFrom(const APValue &v) {
115 assert(v.isLValue());
116 Base = v.getLValueBase();
117 Offset = v.getLValueOffset();
118 }
John McCallefdb83e2010-05-07 21:00:08 +0000119 };
John McCallf4cf1a12010-05-07 17:22:02 +0000120}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000121
John McCall56ca35d2011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000136 if (!E) return true;
137
138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
139 if (isa<FunctionDecl>(DRE->getDecl()))
140 return true;
141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
142 return VD->hasGlobalStorage();
143 return false;
144 }
145
146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
147 return CLE->isFileScope();
148
149 return true;
150}
151
John McCallefdb83e2010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000154
John McCall35542832010-05-07 21:34:32 +0000155 // A null base expression indicates a null pointer. These are always
156 // evaluatable, and they are false unless the offset is zero.
157 if (!Base) {
158 Result = !Value.Offset.isZero();
159 return true;
160 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000161
John McCall42c8f872010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000164
John McCall35542832010-05-07 21:34:32 +0000165 // We have a non-null base expression. These are generally known to
166 // be true, but if it'a decl-ref to a weak symbol it can be null at
167 // runtime.
John McCall35542832010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCall35542832010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman5bc86102009-06-14 02:17:33 +0000181 return true;
182}
183
John McCallcd7a4452010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000187 APSInt IntResult;
188 if (!EvaluateInteger(E, IntResult, Info))
189 return false;
190 Result = IntResult != 0;
191 return true;
192 } else if (E->getType()->isRealFloatingType()) {
193 APFloat FloatResult(0.0);
194 if (!EvaluateFloat(E, FloatResult, Info))
195 return false;
196 Result = !FloatResult.isZero();
197 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000205 if (!EvaluateComplex(E, ComplexResult, Info))
206 return false;
207 if (ComplexResult.isComplexFloat()) {
208 Result = !ComplexResult.getComplexFloatReal().isZero() ||
209 !ComplexResult.getComplexFloatImag().isZero();
210 } else {
211 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
212 ComplexResult.getComplexIntImag().getBoolValue();
213 }
214 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump1eb44332009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000224 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000227 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000228 bool ignored;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000229 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
230 return Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000231}
232
Mike Stump1eb44332009-09-09 15:08:12 +0000233static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000234 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000235 bool ignored;
236 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000237 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000238 APFloat::rmNearestTiesToEven, &ignored);
239 return Result;
240}
241
Mike Stump1eb44332009-09-09 15:08:12 +0000242static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000243 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000244 unsigned DestWidth = Ctx.getIntWidth(DestType);
245 APSInt Result = Value;
246 // Figure out if this is a truncate, extend or noop cast.
247 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000248 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000249 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000250 return Result;
251}
252
Mike Stump1eb44332009-09-09 15:08:12 +0000253static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000254 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000255
256 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
257 Result.convertFromAPInt(Value, Value.isSigned(),
258 APFloat::rmNearestTiesToEven);
259 return Result;
260}
261
Mike Stumpc4c90452009-10-27 22:09:17 +0000262namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000263class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000264 : public ConstStmtVisitor<HasSideEffect, bool> {
Mike Stumpc4c90452009-10-27 22:09:17 +0000265 EvalInfo &Info;
266public:
267
268 HasSideEffect(EvalInfo &info) : Info(info) {}
269
270 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000271 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +0000272 return true;
273 }
274
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000275 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
276 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000277 return Visit(E->getResultExpr());
278 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000279 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000280 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000281 return true;
282 return false;
283 }
John McCallf85e1932011-06-15 23:02:42 +0000284 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
285 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
286 return true;
287 return false;
288 }
289 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
290 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
291 return true;
292 return false;
293 }
294
Mike Stumpc4c90452009-10-27 22:09:17 +0000295 // We don't want to evaluate BlockExprs multiple times, as they generate
296 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000297 bool VisitBlockExpr(const BlockExpr *E) { return true; }
298 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
299 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000300 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000301 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
302 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
303 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
304 bool VisitStringLiteral(const StringLiteral *E) { return false; }
305 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
306 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000307 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000308 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000309 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000310 bool VisitChooseExpr(const ChooseExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000311 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000312 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
313 bool VisitBinAssign(const BinaryOperator *E) { return true; }
314 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
315 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +0000316 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000317 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
318 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
319 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
320 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
321 bool VisitUnaryDeref(const UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000322 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000323 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000324 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000325 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000326 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000327
328 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000329 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +0000330 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
331 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000332 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000333 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000334 return false;
335 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000336
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000337 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000338};
339
John McCall56ca35d2011-02-17 10:25:35 +0000340class OpaqueValueEvaluation {
341 EvalInfo &info;
342 OpaqueValueExpr *opaqueValue;
343
344public:
345 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
346 Expr *value)
347 : info(info), opaqueValue(opaqueValue) {
348
349 // If evaluation fails, fail immediately.
350 if (!Evaluate(info, value)) {
351 this->opaqueValue = 0;
352 return;
353 }
354 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
355 }
356
357 bool hasError() const { return opaqueValue == 0; }
358
359 ~OpaqueValueEvaluation() {
360 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
361 }
362};
363
Mike Stumpc4c90452009-10-27 22:09:17 +0000364} // end anonymous namespace
365
Eli Friedman4efaa272008-11-12 09:44:48 +0000366//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000367// Generic Evaluation
368//===----------------------------------------------------------------------===//
369namespace {
370
371template <class Derived, typename RetTy=void>
372class ExprEvaluatorBase
373 : public ConstStmtVisitor<Derived, RetTy> {
374private:
375 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
376 return static_cast<Derived*>(this)->Success(V, E);
377 }
378 RetTy DerivedError(const Expr *E) {
379 return static_cast<Derived*>(this)->Error(E);
380 }
381
382protected:
383 EvalInfo &Info;
384 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
385 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
386
387public:
388 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
389
390 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000391 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000392 }
393 RetTy VisitExpr(const Expr *E) {
394 return DerivedError(E);
395 }
396
397 RetTy VisitParenExpr(const ParenExpr *E)
398 { return StmtVisitorTy::Visit(E->getSubExpr()); }
399 RetTy VisitUnaryExtension(const UnaryOperator *E)
400 { return StmtVisitorTy::Visit(E->getSubExpr()); }
401 RetTy VisitUnaryPlus(const UnaryOperator *E)
402 { return StmtVisitorTy::Visit(E->getSubExpr()); }
403 RetTy VisitChooseExpr(const ChooseExpr *E)
404 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
405 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
406 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000407 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
408 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000409
410 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
411 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
412 if (opaque.hasError())
413 return DerivedError(E);
414
415 bool cond;
416 if (!HandleConversionToBool(E->getCond(), cond, Info))
417 return DerivedError(E);
418
419 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
420 }
421
422 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
423 bool BoolResult;
424 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
425 return DerivedError(E);
426
427 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
428 return StmtVisitorTy::Visit(EvalExpr);
429 }
430
431 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
432 const APValue *value = Info.getOpaqueValue(E);
433 if (!value)
434 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
435 : DerivedError(E));
436 return DerivedSuccess(*value, E);
437 }
438};
439
440}
441
442//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000443// LValue Evaluation
444//===----------------------------------------------------------------------===//
445namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000446class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000447 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000448 LValue &Result;
Chandler Carruth01248392011-08-22 17:24:56 +0000449 const Decl *PrevDecl;
John McCallefdb83e2010-05-07 21:00:08 +0000450
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000451 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000452 Result.Base = E;
453 Result.Offset = CharUnits::Zero();
454 return true;
455 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000456public:
Mike Stump1eb44332009-09-09 15:08:12 +0000457
John McCallefdb83e2010-05-07 21:00:08 +0000458 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth01248392011-08-22 17:24:56 +0000459 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000460
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000461 bool Success(const APValue &V, const Expr *E) {
462 Result.setFrom(V);
463 return true;
464 }
465 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000466 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000467 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000468
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000469 bool VisitDeclRefExpr(const DeclRefExpr *E);
470 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
471 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
472 bool VisitMemberExpr(const MemberExpr *E);
473 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
474 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
475 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
476 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +0000477
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000478 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000479 switch (E->getCastKind()) {
480 default:
John McCallefdb83e2010-05-07 21:00:08 +0000481 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000482
John McCall2de56d12010-08-25 11:45:40 +0000483 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000484 return Visit(E->getSubExpr());
485 }
486 }
Sebastian Redlcea8d962011-09-24 17:48:14 +0000487
488 bool VisitInitListExpr(const InitListExpr *E) {
489 if (Info.Ctx.getLangOptions().CPlusPlus0x && E->getNumInits() == 1)
490 return Visit(E->getInit(0));
491 return Error(E);
492 }
493
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000494 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000495
Eli Friedman4efaa272008-11-12 09:44:48 +0000496};
497} // end anonymous namespace
498
John McCallefdb83e2010-05-07 21:00:08 +0000499static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000500 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000501}
502
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000503bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000504 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000505 return Success(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000506 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000507 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000508 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000509 // Reference parameters can refer to anything even if they have an
510 // "initializer" in the form of a default argument.
Chandler Carruth01248392011-08-22 17:24:56 +0000511 if (!isa<ParmVarDecl>(VD)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000512 // FIXME: Check whether VD might be overridden!
Chandler Carruth01248392011-08-22 17:24:56 +0000513
514 // Check for recursive initializers of references.
515 if (PrevDecl == VD)
516 return Error(E);
517 PrevDecl = VD;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000518 if (const Expr *Init = VD->getAnyInitializer())
519 return Visit(Init);
Chandler Carruth01248392011-08-22 17:24:56 +0000520 }
Eli Friedman50c39ea2009-05-27 06:04:58 +0000521 }
522
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000523 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlsson35873c42008-11-24 04:41:22 +0000524}
525
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000526bool
527LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000528 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000529}
530
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000531bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000532 QualType Ty;
533 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000534 if (!EvaluatePointer(E->getBase(), Result, Info))
535 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000536 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000537 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000538 if (!Visit(E->getBase()))
539 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000540 Ty = E->getBase()->getType();
541 }
542
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000543 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000544 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000545
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000546 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor86f19402008-12-20 23:49:58 +0000547 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000548 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000549
550 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000551 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000552
Eli Friedman82905742011-07-07 01:54:01 +0000553 unsigned i = FD->getFieldIndex();
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000554 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000555 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000556}
557
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000558bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000559 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000560 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Anders Carlsson3068d112008-11-16 19:01:22 +0000562 APSInt Index;
563 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000564 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000565
Ken Dyck199c3d62010-01-11 17:06:35 +0000566 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000567 Result.Offset += Index.getSExtValue() * ElementSize;
568 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000569}
Eli Friedman4efaa272008-11-12 09:44:48 +0000570
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000571bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000572 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000573}
574
Eli Friedman4efaa272008-11-12 09:44:48 +0000575//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000576// Pointer Evaluation
577//===----------------------------------------------------------------------===//
578
Anders Carlssonc754aa62008-07-08 05:13:58 +0000579namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000580class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000581 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000582 LValue &Result;
583
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000584 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000585 Result.Base = E;
586 Result.Offset = CharUnits::Zero();
587 return true;
588 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000589public:
Mike Stump1eb44332009-09-09 15:08:12 +0000590
John McCallefdb83e2010-05-07 21:00:08 +0000591 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000592 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000593
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000594 bool Success(const APValue &V, const Expr *E) {
595 Result.setFrom(V);
596 return true;
597 }
598 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +0000599 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000600 }
601
John McCallefdb83e2010-05-07 21:00:08 +0000602 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000603 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +0000604 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000605 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +0000606 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000607 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000608 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000609 bool VisitCallExpr(const CallExpr *E);
610 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000611 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000612 return Success(E);
613 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000614 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000615 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000616 { return Success((Expr*)0); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000617 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000618 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000619
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000620 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000621};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000622} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000623
John McCallefdb83e2010-05-07 21:00:08 +0000624static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000625 assert(E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000626 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000627}
628
John McCallefdb83e2010-05-07 21:00:08 +0000629bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000630 if (E->getOpcode() != BO_Add &&
631 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000632 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000634 const Expr *PExp = E->getLHS();
635 const Expr *IExp = E->getRHS();
636 if (IExp->getType()->isPointerType())
637 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
John McCallefdb83e2010-05-07 21:00:08 +0000639 if (!EvaluatePointer(PExp, Result, Info))
640 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000641
John McCallefdb83e2010-05-07 21:00:08 +0000642 llvm::APSInt Offset;
643 if (!EvaluateInteger(IExp, Offset, Info))
644 return false;
645 int64_t AdditionalOffset
646 = Offset.isSigned() ? Offset.getSExtValue()
647 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000648
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000649 // Compute the new offset in the appropriate width.
650
651 QualType PointeeType =
652 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000653 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000655 // Explicitly handle GNU void* and function pointer arithmetic extensions.
656 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000657 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000658 else
John McCallefdb83e2010-05-07 21:00:08 +0000659 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000660
John McCall2de56d12010-08-25 11:45:40 +0000661 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000662 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000663 else
John McCallefdb83e2010-05-07 21:00:08 +0000664 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000665
John McCallefdb83e2010-05-07 21:00:08 +0000666 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000667}
Eli Friedman4efaa272008-11-12 09:44:48 +0000668
John McCallefdb83e2010-05-07 21:00:08 +0000669bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
670 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000671}
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000673
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000674bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
675 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000676
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000677 switch (E->getCastKind()) {
678 default:
679 break;
680
John McCall2de56d12010-08-25 11:45:40 +0000681 case CK_NoOp:
682 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +0000683 case CK_CPointerToObjCPointerCast:
684 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +0000685 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000686 return Visit(SubExpr);
687
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000688 case CK_DerivedToBase:
689 case CK_UncheckedDerivedToBase: {
690 LValue BaseLV;
691 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
692 return false;
693
694 // Now figure out the necessary offset to add to the baseLV to get from
695 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000696 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000697
698 QualType Ty = E->getSubExpr()->getType();
699 const CXXRecordDecl *DerivedDecl =
700 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
701
702 for (CastExpr::path_const_iterator PathI = E->path_begin(),
703 PathE = E->path_end(); PathI != PathE; ++PathI) {
704 const CXXBaseSpecifier *Base = *PathI;
705
706 // FIXME: If the base is virtual, we'd need to determine the type of the
707 // most derived class and we don't support that right now.
708 if (Base->isVirtual())
709 return false;
710
711 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
712 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
713
Ken Dyck7c7f8202011-01-26 02:17:08 +0000714 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000715 DerivedDecl = BaseDecl;
716 }
717
718 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000719 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000720 return true;
721 }
722
John McCall404cd162010-11-13 01:35:44 +0000723 case CK_NullToPointer: {
724 Result.Base = 0;
725 Result.Offset = CharUnits::Zero();
726 return true;
727 }
728
John McCall2de56d12010-08-25 11:45:40 +0000729 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000730 APValue Value;
731 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000732 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000733
John McCallefdb83e2010-05-07 21:00:08 +0000734 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000735 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000736 Result.Base = 0;
737 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
738 return true;
739 } else {
740 // Cast is of an lvalue, no need to change value.
741 Result.Base = Value.getLValueBase();
742 Result.Offset = Value.getLValueOffset();
743 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000744 }
745 }
John McCall2de56d12010-08-25 11:45:40 +0000746 case CK_ArrayToPointerDecay:
747 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000748 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000749 }
750
John McCallefdb83e2010-05-07 21:00:08 +0000751 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000752}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000753
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000754bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000755 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000756 Builtin::BI__builtin___CFStringMakeConstantString ||
757 E->isBuiltinCall(Info.Ctx) ==
758 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000759 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +0000760
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000761 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000762}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000763
764//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000765// Vector Evaluation
766//===----------------------------------------------------------------------===//
767
768namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000769 class VectorExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000770 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman91110ee2009-02-23 04:23:56 +0000771 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000772 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000774 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000776 APValue Success(const APValue &V, const Expr *E) { return V; }
777 APValue Error(const Expr *E) { return APValue(); }
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Eli Friedman91110ee2009-02-23 04:23:56 +0000779 APValue VisitUnaryReal(const UnaryOperator *E)
780 { return Visit(E->getSubExpr()); }
781 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
782 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000783 APValue VisitCastExpr(const CastExpr* E);
784 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
785 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000786 APValue VisitUnaryImag(const UnaryOperator *E);
787 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000788 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000789 // shufflevector, ExtVectorElementExpr
790 // (Note that these require implementing conversions
791 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000792 };
793} // end anonymous namespace
794
795static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
796 if (!E->getType()->isVectorType())
797 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000798 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +0000799 return !Result.isUninit();
800}
801
802APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000803 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000804 QualType EltTy = VTy->getElementType();
805 unsigned NElts = VTy->getNumElements();
806 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Nate Begeman59b5da62009-01-18 03:20:47 +0000808 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000809 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000810
Eli Friedman46a52322011-03-25 00:43:55 +0000811 switch (E->getCastKind()) {
812 case CK_VectorSplat: {
813 APValue Result = APValue();
814 if (SETy->isIntegerType()) {
815 APSInt IntResult;
816 if (!EvaluateInteger(SE, IntResult, Info))
817 return APValue();
818 Result = APValue(IntResult);
819 } else if (SETy->isRealFloatingType()) {
820 APFloat F(0.0);
821 if (!EvaluateFloat(SE, F, Info))
822 return APValue();
823 Result = APValue(F);
824 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000825 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000826 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000827
828 // Splat and create vector APValue.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000829 SmallVector<APValue, 4> Elts(NElts, Result);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000830 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000831 }
Eli Friedman46a52322011-03-25 00:43:55 +0000832 case CK_BitCast: {
833 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000834 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000835
Eli Friedman46a52322011-03-25 00:43:55 +0000836 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000837 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Eli Friedman46a52322011-03-25 00:43:55 +0000839 APSInt Init;
840 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000841 return APValue();
842
Eli Friedman46a52322011-03-25 00:43:55 +0000843 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
844 "Vectors must be composed of ints or floats");
845
Chris Lattner5f9e2722011-07-23 10:55:15 +0000846 SmallVector<APValue, 4> Elts;
Eli Friedman46a52322011-03-25 00:43:55 +0000847 for (unsigned i = 0; i != NElts; ++i) {
848 APSInt Tmp = Init.extOrTrunc(EltWidth);
849
850 if (EltTy->isIntegerType())
851 Elts.push_back(APValue(Tmp));
852 else
853 Elts.push_back(APValue(APFloat(Tmp)));
854
855 Init >>= EltWidth;
856 }
857 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000858 }
Eli Friedman46a52322011-03-25 00:43:55 +0000859 case CK_LValueToRValue:
860 case CK_NoOp:
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000861 return Visit(SE);
Eli Friedman46a52322011-03-25 00:43:55 +0000862 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000863 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000864 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000865}
866
Mike Stump1eb44332009-09-09 15:08:12 +0000867APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000868VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000869 return this->Visit(E->getInitializer());
Nate Begeman59b5da62009-01-18 03:20:47 +0000870}
871
Mike Stump1eb44332009-09-09 15:08:12 +0000872APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000873VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000874 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000875 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000876 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Nate Begeman59b5da62009-01-18 03:20:47 +0000878 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000879 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +0000880
John McCalla7d6c222010-06-11 17:54:15 +0000881 // If a vector is initialized with a single element, that value
882 // becomes every element of the vector, not just the first.
883 // This is the behavior described in the IBM AltiVec documentation.
884 if (NumInits == 1) {
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000885
886 // Handle the case where the vector is initialized by a another
887 // vector (OpenCL 6.1.6).
888 if (E->getInit(0)->getType()->isVectorType())
889 return this->Visit(const_cast<Expr*>(E->getInit(0)));
890
John McCalla7d6c222010-06-11 17:54:15 +0000891 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000892 if (EltTy->isIntegerType()) {
893 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000894 if (!EvaluateInteger(E->getInit(0), sInt, Info))
895 return APValue();
896 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000897 } else {
898 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000899 if (!EvaluateFloat(E->getInit(0), f, Info))
900 return APValue();
901 InitValue = APValue(f);
902 }
903 for (unsigned i = 0; i < NumElements; i++) {
904 Elements.push_back(InitValue);
905 }
906 } else {
907 for (unsigned i = 0; i < NumElements; i++) {
908 if (EltTy->isIntegerType()) {
909 llvm::APSInt sInt(32);
910 if (i < NumInits) {
911 if (!EvaluateInteger(E->getInit(i), sInt, Info))
912 return APValue();
913 } else {
914 sInt = Info.Ctx.MakeIntValue(0, EltTy);
915 }
916 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000917 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000918 llvm::APFloat f(0.0);
919 if (i < NumInits) {
920 if (!EvaluateFloat(E->getInit(i), f, Info))
921 return APValue();
922 } else {
923 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
924 }
925 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000926 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000927 }
928 }
929 return APValue(&Elements[0], Elements.size());
930}
931
Mike Stump1eb44332009-09-09 15:08:12 +0000932APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000933VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000934 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000935 QualType EltTy = VT->getElementType();
936 APValue ZeroElement;
937 if (EltTy->isIntegerType())
938 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
939 else
940 ZeroElement =
941 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
942
Chris Lattner5f9e2722011-07-23 10:55:15 +0000943 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Eli Friedman91110ee2009-02-23 04:23:56 +0000944 return APValue(&Elements[0], Elements.size());
945}
946
Eli Friedman91110ee2009-02-23 04:23:56 +0000947APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
948 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
949 Info.EvalResult.HasSideEffects = true;
950 return GetZeroVector(E->getType());
951}
952
Nate Begeman59b5da62009-01-18 03:20:47 +0000953//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000954// Integer Evaluation
955//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000956
957namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000958class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000959 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000960 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000961public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000962 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000963 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000964
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000965 bool Success(const llvm::APSInt &SI, const Expr *E) {
966 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000967 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000968 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000969 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000970 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000971 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000972 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000973 return true;
974 }
975
Daniel Dunbar131eb432009-02-19 09:06:44 +0000976 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000977 assert(E->getType()->isIntegralOrEnumerationType() &&
978 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000979 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000980 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000981 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +0000982 Result.getInt().setIsUnsigned(
983 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000984 return true;
985 }
986
987 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000988 assert(E->getType()->isIntegralOrEnumerationType() &&
989 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000990 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000991 return true;
992 }
993
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000994 bool Success(CharUnits Size, const Expr *E) {
995 return Success(Size.getQuantity(), E);
996 }
997
998
Anders Carlsson82206e22008-11-30 18:14:57 +0000999 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001000 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +00001001 if (Info.EvalResult.Diag == 0) {
1002 Info.EvalResult.DiagLoc = L;
1003 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +00001004 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +00001005 }
Chris Lattner54176fd2008-07-12 00:14:42 +00001006 return false;
Chris Lattner7a767782008-07-11 19:24:49 +00001007 }
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001009 bool Success(const APValue &V, const Expr *E) {
1010 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00001011 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001012 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001013 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00001014 }
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001016 //===--------------------------------------------------------------------===//
1017 // Visitor Methods
1018 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00001019
Chris Lattner4c4867e2008-07-12 00:38:25 +00001020 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001021 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001022 }
1023 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001024 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001025 }
Eli Friedman04309752009-11-24 05:28:59 +00001026
1027 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1028 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001029 if (CheckReferencedDecl(E, E->getDecl()))
1030 return true;
1031
1032 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001033 }
1034 bool VisitMemberExpr(const MemberExpr *E) {
1035 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1036 // Conservatively assume a MemberExpr will have side-effects
1037 Info.EvalResult.HasSideEffects = true;
1038 return true;
1039 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001040
1041 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001042 }
1043
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001044 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001045 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001046 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001047 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001048
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001049 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001050 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001051
Anders Carlsson3068d112008-11-16 19:01:22 +00001052 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001053 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001054 }
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Anders Carlsson3f704562008-12-21 22:39:40 +00001056 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001057 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001058 }
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Douglas Gregored8abf12010-07-08 06:14:04 +00001060 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001061 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001062 }
1063
Eli Friedman664a1042009-02-27 04:45:43 +00001064 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1065 return Success(0, E);
1066 }
1067
Sebastian Redl64b45f72009-01-05 20:52:13 +00001068 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001069 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001070 }
1071
Francois Pichet6ad6f282010-12-07 00:08:36 +00001072 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1073 return Success(E->getValue(), E);
1074 }
1075
John Wiegley21ff2e52011-04-28 00:16:57 +00001076 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1077 return Success(E->getValue(), E);
1078 }
1079
John Wiegley55262202011-04-25 06:54:41 +00001080 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1081 return Success(E->getValue(), E);
1082 }
1083
Eli Friedman722c7172009-02-28 03:59:05 +00001084 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001085 bool VisitUnaryImag(const UnaryOperator *E);
1086
Sebastian Redl295995c2010-09-10 20:55:47 +00001087 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001088 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00001089
1090 bool VisitInitListExpr(const InitListExpr *E);
1091
Chris Lattnerfcee0012008-07-11 21:24:13 +00001092private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001093 CharUnits GetAlignOfExpr(const Expr *E);
1094 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001095 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001096 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001097 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001098};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001099} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001100
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001101static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001102 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001103 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001104}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001105
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001106static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001107 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001108
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001109 APValue Val;
1110 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1111 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001112 Result = Val.getInt();
1113 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001114}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001115
Eli Friedman04309752009-11-24 05:28:59 +00001116bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001117 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001118 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001119 // Check for signedness/width mismatches between E type and ECD value.
1120 bool SameSign = (ECD->getInitVal().isSigned()
1121 == E->getType()->isSignedIntegerOrEnumerationType());
1122 bool SameWidth = (ECD->getInitVal().getBitWidth()
1123 == Info.Ctx.getIntWidth(E->getType()));
1124 if (SameSign && SameWidth)
1125 return Success(ECD->getInitVal(), E);
1126 else {
1127 // Get rid of mismatch (otherwise Success assertions will fail)
1128 // by computing a new value matching the type of E.
1129 llvm::APSInt Val = ECD->getInitVal();
1130 if (!SameSign)
1131 Val.setIsSigned(!ECD->getInitVal().isSigned());
1132 if (!SameWidth)
1133 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1134 return Success(Val, E);
1135 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001136 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001137
1138 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001139 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001140 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1141 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001142
1143 if (isa<ParmVarDecl>(D))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001144 return false;
Anders Carlssonf6b60252010-02-03 21:58:41 +00001145
Eli Friedman04309752009-11-24 05:28:59 +00001146 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001147 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001148 if (APValue *V = VD->getEvaluatedValue()) {
1149 if (V->isInt())
1150 return Success(V->getInt(), E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001151 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001152 }
1153
1154 if (VD->isEvaluatingValue())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001155 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001156
1157 VD->setEvaluatingValue();
1158
Eli Friedmana7dedf72010-09-06 00:10:32 +00001159 Expr::EvalResult EResult;
1160 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1161 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001162 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001163 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001164 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001165 return true;
1166 }
1167
Eli Friedmanc0131182009-12-03 20:31:57 +00001168 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001169 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001170 }
1171 }
1172
Chris Lattner4c4867e2008-07-12 00:38:25 +00001173 // Otherwise, random variable references are not constants.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001174 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00001175}
1176
Chris Lattnera4d55d82008-10-06 06:40:35 +00001177/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1178/// as GCC.
1179static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1180 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001181 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001182 enum gcc_type_class {
1183 no_type_class = -1,
1184 void_type_class, integer_type_class, char_type_class,
1185 enumeral_type_class, boolean_type_class,
1186 pointer_type_class, reference_type_class, offset_type_class,
1187 real_type_class, complex_type_class,
1188 function_type_class, method_type_class,
1189 record_type_class, union_type_class,
1190 array_type_class, string_type_class,
1191 lang_type_class
1192 };
Mike Stump1eb44332009-09-09 15:08:12 +00001193
1194 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001195 // ideal, however it is what gcc does.
1196 if (E->getNumArgs() == 0)
1197 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Chris Lattnera4d55d82008-10-06 06:40:35 +00001199 QualType ArgTy = E->getArg(0)->getType();
1200 if (ArgTy->isVoidType())
1201 return void_type_class;
1202 else if (ArgTy->isEnumeralType())
1203 return enumeral_type_class;
1204 else if (ArgTy->isBooleanType())
1205 return boolean_type_class;
1206 else if (ArgTy->isCharType())
1207 return string_type_class; // gcc doesn't appear to use char_type_class
1208 else if (ArgTy->isIntegerType())
1209 return integer_type_class;
1210 else if (ArgTy->isPointerType())
1211 return pointer_type_class;
1212 else if (ArgTy->isReferenceType())
1213 return reference_type_class;
1214 else if (ArgTy->isRealType())
1215 return real_type_class;
1216 else if (ArgTy->isComplexType())
1217 return complex_type_class;
1218 else if (ArgTy->isFunctionType())
1219 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001220 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001221 return record_type_class;
1222 else if (ArgTy->isUnionType())
1223 return union_type_class;
1224 else if (ArgTy->isArrayType())
1225 return array_type_class;
1226 else if (ArgTy->isUnionType())
1227 return union_type_class;
1228 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00001229 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00001230 return -1;
1231}
1232
John McCall42c8f872010-05-10 23:27:23 +00001233/// Retrieves the "underlying object type" of the given expression,
1234/// as used by __builtin_object_size.
1235QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1236 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1237 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1238 return VD->getType();
1239 } else if (isa<CompoundLiteralExpr>(E)) {
1240 return E->getType();
1241 }
1242
1243 return QualType();
1244}
1245
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001246bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00001247 // TODO: Perhaps we should let LLVM lower this?
1248 LValue Base;
1249 if (!EvaluatePointer(E->getArg(0), Base, Info))
1250 return false;
1251
1252 // If we can prove the base is null, lower to zero now.
1253 const Expr *LVBase = Base.getLValueBase();
1254 if (!LVBase) return Success(0, E);
1255
1256 QualType T = GetObjectType(LVBase);
1257 if (T.isNull() ||
1258 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001259 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001260 T->isVariablyModifiedType() ||
1261 T->isDependentType())
1262 return false;
1263
1264 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1265 CharUnits Offset = Base.getLValueOffset();
1266
1267 if (!Offset.isNegative() && Offset <= Size)
1268 Size -= Offset;
1269 else
1270 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001271 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001272}
1273
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001274bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001275 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001276 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001277 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001278
1279 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001280 if (TryEvaluateBuiltinObjectSize(E))
1281 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001282
Eric Christopherb2aaf512010-01-19 22:58:35 +00001283 // If evaluating the argument has side-effects we can't determine
1284 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001285 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001286 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001287 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001288 return Success(0, E);
1289 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001290
Mike Stump64eda9e2009-10-26 18:35:08 +00001291 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1292 }
1293
Chris Lattner019f4e82008-10-06 05:28:25 +00001294 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001295 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001297 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001298 // __builtin_constant_p always has one operand: it returns true if that
1299 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001300 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001301
1302 case Builtin::BI__builtin_eh_return_data_regno: {
1303 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001304 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001305 return Success(Operand, E);
1306 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001307
1308 case Builtin::BI__builtin_expect:
1309 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001310
1311 case Builtin::BIstrlen:
1312 case Builtin::BI__builtin_strlen:
1313 // As an extension, we support strlen() and __builtin_strlen() as constant
1314 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001315 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00001316 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1317 // The string literal may have embedded null characters. Find the first
1318 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001319 StringRef Str = S->getString();
1320 StringRef::size_type Pos = Str.find(0);
1321 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00001322 Str = Str.substr(0, Pos);
1323
1324 return Success(Str.size(), E);
1325 }
1326
1327 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001328 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001329}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001330
Chris Lattnerb542afe2008-07-11 19:10:17 +00001331bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001332 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001333 if (!Visit(E->getRHS()))
1334 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001335
Eli Friedman33ef1452009-02-26 10:19:36 +00001336 // If we can't evaluate the LHS, it might have side effects;
1337 // conservatively mark it.
1338 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1339 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001340
Anders Carlsson027f62e2008-12-01 02:07:06 +00001341 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001342 }
1343
1344 if (E->isLogicalOp()) {
1345 // These need to be handled specially because the operands aren't
1346 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001347 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001349 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001350 // We were able to evaluate the LHS, see if we can get away with not
1351 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001352 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001353 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001354
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001355 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001356 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001357 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001358 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001359 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001360 }
1361 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001362 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001363 // We can't evaluate the LHS; however, sometimes the result
1364 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001365 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1366 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001367 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001368 // must have had side effects.
1369 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001370
1371 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001372 }
1373 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001374 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001375
Eli Friedmana6afa762008-11-13 06:09:17 +00001376 return false;
1377 }
1378
Anders Carlsson286f85e2008-11-16 07:17:21 +00001379 QualType LHSTy = E->getLHS()->getType();
1380 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001381
1382 if (LHSTy->isAnyComplexType()) {
1383 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001384 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001385
1386 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1387 return false;
1388
1389 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1390 return false;
1391
1392 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001393 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001394 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001395 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001396 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1397
John McCall2de56d12010-08-25 11:45:40 +00001398 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001399 return Success((CR_r == APFloat::cmpEqual &&
1400 CR_i == APFloat::cmpEqual), E);
1401 else {
John McCall2de56d12010-08-25 11:45:40 +00001402 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001403 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001404 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001405 CR_r == APFloat::cmpLessThan ||
1406 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001407 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001408 CR_i == APFloat::cmpLessThan ||
1409 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001410 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001411 } else {
John McCall2de56d12010-08-25 11:45:40 +00001412 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001413 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1414 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1415 else {
John McCall2de56d12010-08-25 11:45:40 +00001416 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001417 "Invalid compex comparison.");
1418 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1419 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1420 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001421 }
1422 }
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Anders Carlsson286f85e2008-11-16 07:17:21 +00001424 if (LHSTy->isRealFloatingType() &&
1425 RHSTy->isRealFloatingType()) {
1426 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Anders Carlsson286f85e2008-11-16 07:17:21 +00001428 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1429 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Anders Carlsson286f85e2008-11-16 07:17:21 +00001431 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1432 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Anders Carlsson286f85e2008-11-16 07:17:21 +00001434 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001435
Anders Carlsson286f85e2008-11-16 07:17:21 +00001436 switch (E->getOpcode()) {
1437 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001438 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001439 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001440 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001441 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001442 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001443 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001444 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001445 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001446 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001447 E);
John McCall2de56d12010-08-25 11:45:40 +00001448 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001449 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001450 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001451 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001452 || CR == APFloat::cmpLessThan
1453 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001454 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001455 }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001457 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001458 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001459 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001460 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1461 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001462
John McCallefdb83e2010-05-07 21:00:08 +00001463 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001464 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1465 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001466
Eli Friedman5bc86102009-06-14 02:17:33 +00001467 // Reject any bases from the normal codepath; we special-case comparisons
1468 // to null.
1469 if (LHSValue.getLValueBase()) {
1470 if (!E->isEqualityOp())
1471 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001472 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001473 return false;
1474 bool bres;
1475 if (!EvalPointerValueAsBool(LHSValue, bres))
1476 return false;
John McCall2de56d12010-08-25 11:45:40 +00001477 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001478 } else if (RHSValue.getLValueBase()) {
1479 if (!E->isEqualityOp())
1480 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001481 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001482 return false;
1483 bool bres;
1484 if (!EvalPointerValueAsBool(RHSValue, bres))
1485 return false;
John McCall2de56d12010-08-25 11:45:40 +00001486 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001487 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001488
John McCall2de56d12010-08-25 11:45:40 +00001489 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001490 QualType Type = E->getLHS()->getType();
1491 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001492
Ken Dycka7305832010-01-15 12:37:54 +00001493 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001494 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001495 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001496
Ken Dycka7305832010-01-15 12:37:54 +00001497 CharUnits Diff = LHSValue.getLValueOffset() -
1498 RHSValue.getLValueOffset();
1499 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001500 }
1501 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001502 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001503 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001504 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001505 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1506 }
1507 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001508 }
1509 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001510 if (!LHSTy->isIntegralOrEnumerationType() ||
1511 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001512 // We can't continue from here for non-integral types, and they
1513 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001514 return false;
1515 }
1516
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001517 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001518 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001519 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001520
Eli Friedman42edd0d2009-03-24 01:14:50 +00001521 APValue RHSVal;
1522 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001523 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001524
1525 // Handle cases like (unsigned long)&a + 4.
1526 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001527 CharUnits Offset = Result.getLValueOffset();
1528 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1529 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001530 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001531 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001532 else
Ken Dycka7305832010-01-15 12:37:54 +00001533 Offset -= AdditionalOffset;
1534 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001535 return true;
1536 }
1537
1538 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001539 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001540 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001541 CharUnits Offset = RHSVal.getLValueOffset();
1542 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1543 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001544 return true;
1545 }
1546
1547 // All the following cases expect both operands to be an integer
1548 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001549 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001550
Eli Friedman42edd0d2009-03-24 01:14:50 +00001551 APSInt& RHS = RHSVal.getInt();
1552
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001553 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001554 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001555 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001556 case BO_Mul: return Success(Result.getInt() * RHS, E);
1557 case BO_Add: return Success(Result.getInt() + RHS, E);
1558 case BO_Sub: return Success(Result.getInt() - RHS, E);
1559 case BO_And: return Success(Result.getInt() & RHS, E);
1560 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1561 case BO_Or: return Success(Result.getInt() | RHS, E);
1562 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001563 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001564 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001565 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001566 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001567 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001568 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001569 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001570 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001571 // During constant-folding, a negative shift is an opposite shift.
1572 if (RHS.isSigned() && RHS.isNegative()) {
1573 RHS = -RHS;
1574 goto shift_right;
1575 }
1576
1577 shift_left:
1578 unsigned SA
1579 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001580 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001581 }
John McCall2de56d12010-08-25 11:45:40 +00001582 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001583 // During constant-folding, a negative shift is an opposite shift.
1584 if (RHS.isSigned() && RHS.isNegative()) {
1585 RHS = -RHS;
1586 goto shift_left;
1587 }
1588
1589 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001590 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001591 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1592 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001593 }
Mike Stump1eb44332009-09-09 15:08:12 +00001594
John McCall2de56d12010-08-25 11:45:40 +00001595 case BO_LT: return Success(Result.getInt() < RHS, E);
1596 case BO_GT: return Success(Result.getInt() > RHS, E);
1597 case BO_LE: return Success(Result.getInt() <= RHS, E);
1598 case BO_GE: return Success(Result.getInt() >= RHS, E);
1599 case BO_EQ: return Success(Result.getInt() == RHS, E);
1600 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001601 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001602}
1603
Ken Dyck8b752f12010-01-27 17:10:57 +00001604CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001605 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1606 // the result is the size of the referenced type."
1607 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1608 // result shall be the alignment of the referenced type."
1609 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1610 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00001611
1612 // __alignof is defined to return the preferred alignment.
1613 return Info.Ctx.toCharUnitsFromBits(
1614 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001615}
1616
Ken Dyck8b752f12010-01-27 17:10:57 +00001617CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001618 E = E->IgnoreParens();
1619
1620 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001621 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001622 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001623 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1624 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001625
Chris Lattneraf707ab2009-01-24 21:53:27 +00001626 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001627 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1628 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001629
Chris Lattnere9feb472009-01-24 21:09:06 +00001630 return GetAlignOfType(E->getType());
1631}
1632
1633
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001634/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1635/// a result as the expression's type.
1636bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1637 const UnaryExprOrTypeTraitExpr *E) {
1638 switch(E->getKind()) {
1639 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001640 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001641 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001642 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001643 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001644 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001645
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001646 case UETT_VecStep: {
1647 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001648
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001649 if (Ty->isVectorType()) {
1650 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001651
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001652 // The vec_step built-in functions that take a 3-component
1653 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1654 if (n == 3)
1655 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001656
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001657 return Success(n, E);
1658 } else
1659 return Success(1, E);
1660 }
1661
1662 case UETT_SizeOf: {
1663 QualType SrcTy = E->getTypeOfArgument();
1664 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1665 // the result is the size of the referenced type."
1666 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1667 // result shall be the alignment of the referenced type."
1668 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1669 SrcTy = Ref->getPointeeType();
1670
1671 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1672 // extension.
1673 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1674 return Success(1, E);
1675
1676 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1677 if (!SrcTy->isConstantSizeType())
1678 return false;
1679
1680 // Get information about the size.
1681 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1682 }
1683 }
1684
1685 llvm_unreachable("unknown expr/type trait");
1686 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001687}
1688
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001689bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001690 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001691 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001692 if (n == 0)
1693 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001694 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001695 for (unsigned i = 0; i != n; ++i) {
1696 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1697 switch (ON.getKind()) {
1698 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001699 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001700 APSInt IdxResult;
1701 if (!EvaluateInteger(Idx, IdxResult, Info))
1702 return false;
1703 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1704 if (!AT)
1705 return false;
1706 CurrentType = AT->getElementType();
1707 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1708 Result += IdxResult.getSExtValue() * ElementSize;
1709 break;
1710 }
1711
1712 case OffsetOfExpr::OffsetOfNode::Field: {
1713 FieldDecl *MemberDecl = ON.getField();
1714 const RecordType *RT = CurrentType->getAs<RecordType>();
1715 if (!RT)
1716 return false;
1717 RecordDecl *RD = RT->getDecl();
1718 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001719 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001720 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001721 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001722 CurrentType = MemberDecl->getType().getNonReferenceType();
1723 break;
1724 }
1725
1726 case OffsetOfExpr::OffsetOfNode::Identifier:
1727 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001728 return false;
1729
1730 case OffsetOfExpr::OffsetOfNode::Base: {
1731 CXXBaseSpecifier *BaseSpec = ON.getBase();
1732 if (BaseSpec->isVirtual())
1733 return false;
1734
1735 // Find the layout of the class whose base we are looking into.
1736 const RecordType *RT = CurrentType->getAs<RecordType>();
1737 if (!RT)
1738 return false;
1739 RecordDecl *RD = RT->getDecl();
1740 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1741
1742 // Find the base class itself.
1743 CurrentType = BaseSpec->getType();
1744 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1745 if (!BaseRT)
1746 return false;
1747
1748 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001749 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001750 break;
1751 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001752 }
1753 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001754 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001755}
1756
Chris Lattnerb542afe2008-07-11 19:10:17 +00001757bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001758 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001759 // LNot's operand isn't necessarily an integer, so we handle it specially.
1760 bool bres;
1761 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1762 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001763 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001764 }
1765
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001766 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001767 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001768 return false;
1769
Chris Lattner87eae5e2008-07-11 22:52:41 +00001770 // Get the operand value into 'Result'.
1771 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001772 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001773
Chris Lattner75a48812008-07-11 22:15:16 +00001774 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001775 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001776 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1777 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001778 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001779 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001780 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1781 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001782 return true;
John McCall2de56d12010-08-25 11:45:40 +00001783 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001784 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001785 return true;
John McCall2de56d12010-08-25 11:45:40 +00001786 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001787 if (!Result.isInt()) return false;
1788 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001789 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001790 if (!Result.isInt()) return false;
1791 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001792 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001793}
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Chris Lattner732b2232008-07-12 01:15:53 +00001795/// HandleCast - This is used to evaluate implicit or explicit casts where the
1796/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001797bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1798 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00001799 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001800 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001801
Eli Friedman46a52322011-03-25 00:43:55 +00001802 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001803 case CK_BaseToDerived:
1804 case CK_DerivedToBase:
1805 case CK_UncheckedDerivedToBase:
1806 case CK_Dynamic:
1807 case CK_ToUnion:
1808 case CK_ArrayToPointerDecay:
1809 case CK_FunctionToPointerDecay:
1810 case CK_NullToPointer:
1811 case CK_NullToMemberPointer:
1812 case CK_BaseToDerivedMemberPointer:
1813 case CK_DerivedToBaseMemberPointer:
1814 case CK_ConstructorConversion:
1815 case CK_IntegralToPointer:
1816 case CK_ToVoid:
1817 case CK_VectorSplat:
1818 case CK_IntegralToFloating:
1819 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001820 case CK_CPointerToObjCPointerCast:
1821 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001822 case CK_AnyPointerToBlockPointerCast:
1823 case CK_ObjCObjectLValueCast:
1824 case CK_FloatingRealToComplex:
1825 case CK_FloatingComplexToReal:
1826 case CK_FloatingComplexCast:
1827 case CK_FloatingComplexToIntegralComplex:
1828 case CK_IntegralRealToComplex:
1829 case CK_IntegralComplexCast:
1830 case CK_IntegralComplexToFloatingComplex:
1831 llvm_unreachable("invalid cast kind for integral value");
1832
Eli Friedmane50c2972011-03-25 19:07:11 +00001833 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001834 case CK_Dependent:
1835 case CK_GetObjCProperty:
1836 case CK_LValueBitCast:
1837 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00001838 case CK_ARCProduceObject:
1839 case CK_ARCConsumeObject:
1840 case CK_ARCReclaimReturnedObject:
1841 case CK_ARCExtendBlockObject:
Eli Friedman46a52322011-03-25 00:43:55 +00001842 return false;
1843
1844 case CK_LValueToRValue:
1845 case CK_NoOp:
1846 return Visit(E->getSubExpr());
1847
1848 case CK_MemberPointerToBoolean:
1849 case CK_PointerToBoolean:
1850 case CK_IntegralToBoolean:
1851 case CK_FloatingToBoolean:
1852 case CK_FloatingComplexToBoolean:
1853 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001854 bool BoolResult;
1855 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1856 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001857 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001858 }
1859
Eli Friedman46a52322011-03-25 00:43:55 +00001860 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001861 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001862 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001863
Eli Friedmanbe265702009-02-20 01:15:07 +00001864 if (!Result.isInt()) {
1865 // Only allow casts of lvalues if they are lossless.
1866 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1867 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001868
Daniel Dunbardd211642009-02-19 22:24:01 +00001869 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001870 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001871 }
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Eli Friedman46a52322011-03-25 00:43:55 +00001873 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001874 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001875 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001876 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001877
Daniel Dunbardd211642009-02-19 22:24:01 +00001878 if (LV.getLValueBase()) {
1879 // Only allow based lvalue casts if they are lossless.
1880 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1881 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001882
John McCallefdb83e2010-05-07 21:00:08 +00001883 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001884 return true;
1885 }
1886
Ken Dycka7305832010-01-15 12:37:54 +00001887 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1888 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001889 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001890 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001891
Eli Friedman46a52322011-03-25 00:43:55 +00001892 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001893 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001894 if (!EvaluateComplex(SubExpr, C, Info))
1895 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001896 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001897 }
Eli Friedman2217c872009-02-22 11:46:18 +00001898
Eli Friedman46a52322011-03-25 00:43:55 +00001899 case CK_FloatingToIntegral: {
1900 APFloat F(0.0);
1901 if (!EvaluateFloat(SubExpr, F, Info))
1902 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001903
Eli Friedman46a52322011-03-25 00:43:55 +00001904 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1905 }
1906 }
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Eli Friedman46a52322011-03-25 00:43:55 +00001908 llvm_unreachable("unknown cast resulting in integral value");
1909 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001910}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001911
Eli Friedman722c7172009-02-28 03:59:05 +00001912bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1913 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001914 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001915 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1916 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1917 return Success(LV.getComplexIntReal(), E);
1918 }
1919
1920 return Visit(E->getSubExpr());
1921}
1922
Eli Friedman664a1042009-02-27 04:45:43 +00001923bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001924 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001925 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001926 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1927 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1928 return Success(LV.getComplexIntImag(), E);
1929 }
1930
Eli Friedman664a1042009-02-27 04:45:43 +00001931 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1932 Info.EvalResult.HasSideEffects = true;
1933 return Success(0, E);
1934}
1935
Douglas Gregoree8aff02011-01-04 17:33:58 +00001936bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1937 return Success(E->getPackLength(), E);
1938}
1939
Sebastian Redl295995c2010-09-10 20:55:47 +00001940bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1941 return Success(E->getValue(), E);
1942}
1943
Sebastian Redlcea8d962011-09-24 17:48:14 +00001944bool IntExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
1945 if (!Info.Ctx.getLangOptions().CPlusPlus0x)
1946 return Error(E);
1947
1948 if (E->getNumInits() == 0)
1949 return Success(0, E);
1950
1951 assert(E->getNumInits() == 1 && "Excess initializers for integer in C++11.");
1952 return Visit(E->getInit(0));
1953}
1954
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001955//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001956// Float Evaluation
1957//===----------------------------------------------------------------------===//
1958
1959namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001960class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001961 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001962 APFloat &Result;
1963public:
1964 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001965 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001966
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001967 bool Success(const APValue &V, const Expr *e) {
1968 Result = V.getFloat();
1969 return true;
1970 }
1971 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001972 return false;
1973 }
1974
Chris Lattner019f4e82008-10-06 05:28:25 +00001975 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001976
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001977 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001978 bool VisitBinaryOperator(const BinaryOperator *E);
1979 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001980 bool VisitCastExpr(const CastExpr *E);
1981 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001982
John McCallabd3a852010-05-07 22:08:54 +00001983 bool VisitUnaryReal(const UnaryOperator *E);
1984 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001985
John McCall189d6ef2010-10-09 01:34:31 +00001986 bool VisitDeclRefExpr(const DeclRefExpr *E);
1987
Sebastian Redlcea8d962011-09-24 17:48:14 +00001988 bool VisitInitListExpr(const InitListExpr *E);
1989
John McCallabd3a852010-05-07 22:08:54 +00001990 // FIXME: Missing: array subscript of vector, member of vector,
1991 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001992};
1993} // end anonymous namespace
1994
1995static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001996 assert(E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001997 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001998}
1999
Jay Foad4ba2a172011-01-12 09:06:06 +00002000static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00002001 QualType ResultTy,
2002 const Expr *Arg,
2003 bool SNaN,
2004 llvm::APFloat &Result) {
2005 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2006 if (!S) return false;
2007
2008 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2009
2010 llvm::APInt fill;
2011
2012 // Treat empty strings as if they were zero.
2013 if (S->getString().empty())
2014 fill = llvm::APInt(32, 0);
2015 else if (S->getString().getAsInteger(0, fill))
2016 return false;
2017
2018 if (SNaN)
2019 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2020 else
2021 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2022 return true;
2023}
2024
Chris Lattner019f4e82008-10-06 05:28:25 +00002025bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00002026 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002027 default:
2028 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2029
Chris Lattner019f4e82008-10-06 05:28:25 +00002030 case Builtin::BI__builtin_huge_val:
2031 case Builtin::BI__builtin_huge_valf:
2032 case Builtin::BI__builtin_huge_vall:
2033 case Builtin::BI__builtin_inf:
2034 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002035 case Builtin::BI__builtin_infl: {
2036 const llvm::fltSemantics &Sem =
2037 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002038 Result = llvm::APFloat::getInf(Sem);
2039 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002040 }
Mike Stump1eb44332009-09-09 15:08:12 +00002041
John McCalldb7b72a2010-02-28 13:00:19 +00002042 case Builtin::BI__builtin_nans:
2043 case Builtin::BI__builtin_nansf:
2044 case Builtin::BI__builtin_nansl:
2045 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2046 true, Result);
2047
Chris Lattner9e621712008-10-06 06:31:58 +00002048 case Builtin::BI__builtin_nan:
2049 case Builtin::BI__builtin_nanf:
2050 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002051 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002052 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002053 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2054 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002055
2056 case Builtin::BI__builtin_fabs:
2057 case Builtin::BI__builtin_fabsf:
2058 case Builtin::BI__builtin_fabsl:
2059 if (!EvaluateFloat(E->getArg(0), Result, Info))
2060 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002062 if (Result.isNegative())
2063 Result.changeSign();
2064 return true;
2065
Mike Stump1eb44332009-09-09 15:08:12 +00002066 case Builtin::BI__builtin_copysign:
2067 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002068 case Builtin::BI__builtin_copysignl: {
2069 APFloat RHS(0.);
2070 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2071 !EvaluateFloat(E->getArg(1), RHS, Info))
2072 return false;
2073 Result.copySign(RHS);
2074 return true;
2075 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002076 }
2077}
2078
John McCall189d6ef2010-10-09 01:34:31 +00002079bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002080 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2081 return true;
2082
John McCall189d6ef2010-10-09 01:34:31 +00002083 const Decl *D = E->getDecl();
2084 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2085 const VarDecl *VD = cast<VarDecl>(D);
2086
2087 // Require the qualifiers to be const and not volatile.
2088 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2089 if (!T.isConstQualified() || T.isVolatileQualified())
2090 return false;
2091
2092 const Expr *Init = VD->getAnyInitializer();
2093 if (!Init) return false;
2094
2095 if (APValue *V = VD->getEvaluatedValue()) {
2096 if (V->isFloat()) {
2097 Result = V->getFloat();
2098 return true;
2099 }
2100 return false;
2101 }
2102
2103 if (VD->isEvaluatingValue())
2104 return false;
2105
2106 VD->setEvaluatingValue();
2107
2108 Expr::EvalResult InitResult;
2109 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2110 InitResult.Val.isFloat()) {
2111 // Cache the evaluated value in the variable declaration.
2112 Result = InitResult.Val.getFloat();
2113 VD->setEvaluatedValue(InitResult.Val);
2114 return true;
2115 }
2116
2117 VD->setEvaluatedValue(APValue());
2118 return false;
2119}
2120
John McCallabd3a852010-05-07 22:08:54 +00002121bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002122 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2123 ComplexValue CV;
2124 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2125 return false;
2126 Result = CV.FloatReal;
2127 return true;
2128 }
2129
2130 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002131}
2132
2133bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002134 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2135 ComplexValue CV;
2136 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2137 return false;
2138 Result = CV.FloatImag;
2139 return true;
2140 }
2141
2142 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2143 Info.EvalResult.HasSideEffects = true;
2144 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2145 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002146 return true;
2147}
2148
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002149bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002150 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002151 return false;
2152
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002153 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2154 return false;
2155
2156 switch (E->getOpcode()) {
2157 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002158 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002159 return true;
John McCall2de56d12010-08-25 11:45:40 +00002160 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002161 Result.changeSign();
2162 return true;
2163 }
2164}
Chris Lattner019f4e82008-10-06 05:28:25 +00002165
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002166bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002167 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002168 if (!EvaluateFloat(E->getRHS(), Result, Info))
2169 return false;
2170
2171 // If we can't evaluate the LHS, it might have side effects;
2172 // conservatively mark it.
2173 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2174 Info.EvalResult.HasSideEffects = true;
2175
2176 return true;
2177 }
2178
Anders Carlsson96e93662010-10-31 01:21:47 +00002179 // We can't evaluate pointer-to-member operations.
2180 if (E->isPtrMemOp())
2181 return false;
2182
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002183 // FIXME: Diagnostics? I really don't understand how the warnings
2184 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002185 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002186 if (!EvaluateFloat(E->getLHS(), Result, Info))
2187 return false;
2188 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2189 return false;
2190
2191 switch (E->getOpcode()) {
2192 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002193 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002194 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2195 return true;
John McCall2de56d12010-08-25 11:45:40 +00002196 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002197 Result.add(RHS, APFloat::rmNearestTiesToEven);
2198 return true;
John McCall2de56d12010-08-25 11:45:40 +00002199 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002200 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2201 return true;
John McCall2de56d12010-08-25 11:45:40 +00002202 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002203 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2204 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002205 }
2206}
2207
2208bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2209 Result = E->getValue();
2210 return true;
2211}
2212
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002213bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2214 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Eli Friedman2a523ee2011-03-25 00:54:52 +00002216 switch (E->getCastKind()) {
2217 default:
2218 return false;
2219
2220 case CK_LValueToRValue:
2221 case CK_NoOp:
2222 return Visit(SubExpr);
2223
2224 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002225 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002226 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002227 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002228 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002229 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002230 return true;
2231 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002232
2233 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002234 if (!Visit(SubExpr))
2235 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002236 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2237 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002238 return true;
2239 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002240
Eli Friedman2a523ee2011-03-25 00:54:52 +00002241 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002242 ComplexValue V;
2243 if (!EvaluateComplex(SubExpr, V, Info))
2244 return false;
2245 Result = V.getComplexFloatReal();
2246 return true;
2247 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002248 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002249
2250 return false;
2251}
2252
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002253bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002254 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2255 return true;
2256}
2257
Sebastian Redlcea8d962011-09-24 17:48:14 +00002258bool FloatExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2259 if (!Info.Ctx.getLangOptions().CPlusPlus0x)
2260 return Error(E);
2261
2262 if (E->getNumInits() == 0) {
2263 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2264 return true;
2265 }
2266
2267 assert(E->getNumInits() == 1 && "Excess initializers for integer in C++11.");
2268 return Visit(E->getInit(0));
2269}
2270
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002271//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002272// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002273//===----------------------------------------------------------------------===//
2274
2275namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002276class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002277 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00002278 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002280public:
John McCallf4cf1a12010-05-07 17:22:02 +00002281 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002282 : ExprEvaluatorBaseTy(info), Result(Result) {}
2283
2284 bool Success(const APValue &V, const Expr *e) {
2285 Result.setFrom(V);
2286 return true;
2287 }
2288 bool Error(const Expr *E) {
2289 return false;
2290 }
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002292 //===--------------------------------------------------------------------===//
2293 // Visitor Methods
2294 //===--------------------------------------------------------------------===//
2295
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002296 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002298 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002299
John McCallf4cf1a12010-05-07 17:22:02 +00002300 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002301 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00002302 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002303};
2304} // end anonymous namespace
2305
John McCallf4cf1a12010-05-07 17:22:02 +00002306static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2307 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002308 assert(E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002309 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002310}
2311
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002312bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2313 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002314
2315 if (SubExpr->getType()->isRealFloatingType()) {
2316 Result.makeComplexFloat();
2317 APFloat &Imag = Result.FloatImag;
2318 if (!EvaluateFloat(SubExpr, Imag, Info))
2319 return false;
2320
2321 Result.FloatReal = APFloat(Imag.getSemantics());
2322 return true;
2323 } else {
2324 assert(SubExpr->getType()->isIntegerType() &&
2325 "Unexpected imaginary literal.");
2326
2327 Result.makeComplexInt();
2328 APSInt &Imag = Result.IntImag;
2329 if (!EvaluateInteger(SubExpr, Imag, Info))
2330 return false;
2331
2332 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2333 return true;
2334 }
2335}
2336
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002337bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002338
John McCall8786da72010-12-14 17:51:41 +00002339 switch (E->getCastKind()) {
2340 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002341 case CK_BaseToDerived:
2342 case CK_DerivedToBase:
2343 case CK_UncheckedDerivedToBase:
2344 case CK_Dynamic:
2345 case CK_ToUnion:
2346 case CK_ArrayToPointerDecay:
2347 case CK_FunctionToPointerDecay:
2348 case CK_NullToPointer:
2349 case CK_NullToMemberPointer:
2350 case CK_BaseToDerivedMemberPointer:
2351 case CK_DerivedToBaseMemberPointer:
2352 case CK_MemberPointerToBoolean:
2353 case CK_ConstructorConversion:
2354 case CK_IntegralToPointer:
2355 case CK_PointerToIntegral:
2356 case CK_PointerToBoolean:
2357 case CK_ToVoid:
2358 case CK_VectorSplat:
2359 case CK_IntegralCast:
2360 case CK_IntegralToBoolean:
2361 case CK_IntegralToFloating:
2362 case CK_FloatingToIntegral:
2363 case CK_FloatingToBoolean:
2364 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002365 case CK_CPointerToObjCPointerCast:
2366 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00002367 case CK_AnyPointerToBlockPointerCast:
2368 case CK_ObjCObjectLValueCast:
2369 case CK_FloatingComplexToReal:
2370 case CK_FloatingComplexToBoolean:
2371 case CK_IntegralComplexToReal:
2372 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00002373 case CK_ARCProduceObject:
2374 case CK_ARCConsumeObject:
2375 case CK_ARCReclaimReturnedObject:
2376 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00002377 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002378
John McCall8786da72010-12-14 17:51:41 +00002379 case CK_LValueToRValue:
2380 case CK_NoOp:
2381 return Visit(E->getSubExpr());
2382
2383 case CK_Dependent:
2384 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002385 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002386 case CK_UserDefinedConversion:
2387 return false;
2388
2389 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002390 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002391 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002392 return false;
2393
John McCall8786da72010-12-14 17:51:41 +00002394 Result.makeComplexFloat();
2395 Result.FloatImag = APFloat(Real.getSemantics());
2396 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002397 }
2398
John McCall8786da72010-12-14 17:51:41 +00002399 case CK_FloatingComplexCast: {
2400 if (!Visit(E->getSubExpr()))
2401 return false;
2402
2403 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2404 QualType From
2405 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2406
2407 Result.FloatReal
2408 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2409 Result.FloatImag
2410 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2411 return true;
2412 }
2413
2414 case CK_FloatingComplexToIntegralComplex: {
2415 if (!Visit(E->getSubExpr()))
2416 return false;
2417
2418 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2419 QualType From
2420 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2421 Result.makeComplexInt();
2422 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2423 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2424 return true;
2425 }
2426
2427 case CK_IntegralRealToComplex: {
2428 APSInt &Real = Result.IntReal;
2429 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2430 return false;
2431
2432 Result.makeComplexInt();
2433 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2434 return true;
2435 }
2436
2437 case CK_IntegralComplexCast: {
2438 if (!Visit(E->getSubExpr()))
2439 return false;
2440
2441 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2442 QualType From
2443 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2444
2445 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2446 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2447 return true;
2448 }
2449
2450 case CK_IntegralComplexToFloatingComplex: {
2451 if (!Visit(E->getSubExpr()))
2452 return false;
2453
2454 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2455 QualType From
2456 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2457 Result.makeComplexFloat();
2458 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2459 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2460 return true;
2461 }
2462 }
2463
2464 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002465 return false;
2466}
2467
John McCallf4cf1a12010-05-07 17:22:02 +00002468bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002469 if (E->getOpcode() == BO_Comma) {
2470 if (!Visit(E->getRHS()))
2471 return false;
2472
2473 // If we can't evaluate the LHS, it might have side effects;
2474 // conservatively mark it.
2475 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2476 Info.EvalResult.HasSideEffects = true;
2477
2478 return true;
2479 }
John McCallf4cf1a12010-05-07 17:22:02 +00002480 if (!Visit(E->getLHS()))
2481 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002482
John McCallf4cf1a12010-05-07 17:22:02 +00002483 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002484 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002485 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002486
Daniel Dunbar3f279872009-01-29 01:32:56 +00002487 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2488 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002489 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002490 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002491 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002492 if (Result.isComplexFloat()) {
2493 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2494 APFloat::rmNearestTiesToEven);
2495 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2496 APFloat::rmNearestTiesToEven);
2497 } else {
2498 Result.getComplexIntReal() += RHS.getComplexIntReal();
2499 Result.getComplexIntImag() += RHS.getComplexIntImag();
2500 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002501 break;
John McCall2de56d12010-08-25 11:45:40 +00002502 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002503 if (Result.isComplexFloat()) {
2504 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2505 APFloat::rmNearestTiesToEven);
2506 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2507 APFloat::rmNearestTiesToEven);
2508 } else {
2509 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2510 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2511 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002512 break;
John McCall2de56d12010-08-25 11:45:40 +00002513 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002514 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002515 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002516 APFloat &LHS_r = LHS.getComplexFloatReal();
2517 APFloat &LHS_i = LHS.getComplexFloatImag();
2518 APFloat &RHS_r = RHS.getComplexFloatReal();
2519 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002520
Daniel Dunbar3f279872009-01-29 01:32:56 +00002521 APFloat Tmp = LHS_r;
2522 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2523 Result.getComplexFloatReal() = Tmp;
2524 Tmp = LHS_i;
2525 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2526 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2527
2528 Tmp = LHS_r;
2529 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2530 Result.getComplexFloatImag() = Tmp;
2531 Tmp = LHS_i;
2532 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2533 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2534 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002535 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002536 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002537 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2538 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002539 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002540 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2541 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2542 }
2543 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002544 case BO_Div:
2545 if (Result.isComplexFloat()) {
2546 ComplexValue LHS = Result;
2547 APFloat &LHS_r = LHS.getComplexFloatReal();
2548 APFloat &LHS_i = LHS.getComplexFloatImag();
2549 APFloat &RHS_r = RHS.getComplexFloatReal();
2550 APFloat &RHS_i = RHS.getComplexFloatImag();
2551 APFloat &Res_r = Result.getComplexFloatReal();
2552 APFloat &Res_i = Result.getComplexFloatImag();
2553
2554 APFloat Den = RHS_r;
2555 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2556 APFloat Tmp = RHS_i;
2557 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2558 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2559
2560 Res_r = LHS_r;
2561 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2562 Tmp = LHS_i;
2563 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2564 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2565 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2566
2567 Res_i = LHS_i;
2568 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2569 Tmp = LHS_r;
2570 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2571 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2572 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2573 } else {
2574 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2575 // FIXME: what about diagnostics?
2576 return false;
2577 }
2578 ComplexValue LHS = Result;
2579 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2580 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2581 Result.getComplexIntReal() =
2582 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2583 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2584 Result.getComplexIntImag() =
2585 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2586 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2587 }
2588 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002589 }
2590
John McCallf4cf1a12010-05-07 17:22:02 +00002591 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002592}
2593
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002594bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2595 // Get the operand value into 'Result'.
2596 if (!Visit(E->getSubExpr()))
2597 return false;
2598
2599 switch (E->getOpcode()) {
2600 default:
2601 // FIXME: what about diagnostics?
2602 return false;
2603 case UO_Extension:
2604 return true;
2605 case UO_Plus:
2606 // The result is always just the subexpr.
2607 return true;
2608 case UO_Minus:
2609 if (Result.isComplexFloat()) {
2610 Result.getComplexFloatReal().changeSign();
2611 Result.getComplexFloatImag().changeSign();
2612 }
2613 else {
2614 Result.getComplexIntReal() = -Result.getComplexIntReal();
2615 Result.getComplexIntImag() = -Result.getComplexIntImag();
2616 }
2617 return true;
2618 case UO_Not:
2619 if (Result.isComplexFloat())
2620 Result.getComplexFloatImag().changeSign();
2621 else
2622 Result.getComplexIntImag() = -Result.getComplexIntImag();
2623 return true;
2624 }
2625}
2626
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002627//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002628// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002629//===----------------------------------------------------------------------===//
2630
John McCall56ca35d2011-02-17 10:25:35 +00002631static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002632 if (E->getType()->isVectorType()) {
2633 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002634 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00002635 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002636 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002637 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002638 if (Info.EvalResult.Val.isLValue() &&
2639 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002640 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002641 } else if (E->getType()->hasPointerRepresentation()) {
2642 LValue LV;
2643 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002644 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002645 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002646 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002647 LV.moveInto(Info.EvalResult.Val);
2648 } else if (E->getType()->isRealFloatingType()) {
2649 llvm::APFloat F(0.0);
2650 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002651 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002652
John McCallefdb83e2010-05-07 21:00:08 +00002653 Info.EvalResult.Val = APValue(F);
2654 } else if (E->getType()->isAnyComplexType()) {
2655 ComplexValue C;
2656 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002657 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002658 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002659 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002660 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002661
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002662 return true;
2663}
2664
John McCall56ca35d2011-02-17 10:25:35 +00002665/// Evaluate - Return true if this is a constant which we can fold using
2666/// any crazy technique (that has nothing to do with language standards) that
2667/// we want to. If this function returns true, it returns the folded constant
2668/// in Result.
2669bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2670 EvalInfo Info(Ctx, Result);
2671 return ::Evaluate(Info, this);
2672}
2673
Jay Foad4ba2a172011-01-12 09:06:06 +00002674bool Expr::EvaluateAsBooleanCondition(bool &Result,
2675 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002676 EvalResult Scratch;
2677 EvalInfo Info(Ctx, Scratch);
2678
2679 return HandleConversionToBool(this, Result, Info);
2680}
2681
Jay Foad4ba2a172011-01-12 09:06:06 +00002682bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002683 EvalInfo Info(Ctx, Result);
2684
John McCallefdb83e2010-05-07 21:00:08 +00002685 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002686 if (EvaluateLValue(this, LV, Info) &&
2687 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002688 IsGlobalLValue(LV.Base)) {
2689 LV.moveInto(Result.Val);
2690 return true;
2691 }
2692 return false;
2693}
2694
Jay Foad4ba2a172011-01-12 09:06:06 +00002695bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2696 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002697 EvalInfo Info(Ctx, Result);
2698
2699 LValue LV;
2700 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002701 LV.moveInto(Result.Val);
2702 return true;
2703 }
2704 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002705}
2706
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002707/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002708/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002709bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002710 EvalResult Result;
2711 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002712}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002713
Jay Foad4ba2a172011-01-12 09:06:06 +00002714bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002715 Expr::EvalResult Result;
2716 EvalInfo Info(Ctx, Result);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002717 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002718}
2719
Jay Foad4ba2a172011-01-12 09:06:06 +00002720APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002721 EvalResult EvalResult;
2722 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002723 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002724 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002725 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002726
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002727 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002728}
John McCalld905f5a2010-05-07 05:32:02 +00002729
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002730 bool Expr::EvalResult::isGlobalLValue() const {
2731 assert(Val.isLValue());
2732 return IsGlobalLValue(Val.getLValueBase());
2733 }
2734
2735
John McCalld905f5a2010-05-07 05:32:02 +00002736/// isIntegerConstantExpr - this recursive routine will test if an expression is
2737/// an integer constant expression.
2738
2739/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2740/// comma, etc
2741///
2742/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2743/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2744/// cast+dereference.
2745
2746// CheckICE - This function does the fundamental ICE checking: the returned
2747// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2748// Note that to reduce code duplication, this helper does no evaluation
2749// itself; the caller checks whether the expression is evaluatable, and
2750// in the rare cases where CheckICE actually cares about the evaluated
2751// value, it calls into Evalute.
2752//
2753// Meanings of Val:
2754// 0: This expression is an ICE if it can be evaluated by Evaluate.
2755// 1: This expression is not an ICE, but if it isn't evaluated, it's
2756// a legal subexpression for an ICE. This return value is used to handle
2757// the comma operator in C99 mode.
2758// 2: This expression is not an ICE, and is not a legal subexpression for one.
2759
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002760namespace {
2761
John McCalld905f5a2010-05-07 05:32:02 +00002762struct ICEDiag {
2763 unsigned Val;
2764 SourceLocation Loc;
2765
2766 public:
2767 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2768 ICEDiag() : Val(0) {}
2769};
2770
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002771}
2772
2773static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002774
2775static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2776 Expr::EvalResult EVResult;
2777 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2778 !EVResult.Val.isInt()) {
2779 return ICEDiag(2, E->getLocStart());
2780 }
2781 return NoDiag();
2782}
2783
2784static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2785 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002786 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002787 return ICEDiag(2, E->getLocStart());
2788 }
2789
2790 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002791#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002792#define STMT(Node, Base) case Expr::Node##Class:
2793#define EXPR(Node, Base)
2794#include "clang/AST/StmtNodes.inc"
2795 case Expr::PredefinedExprClass:
2796 case Expr::FloatingLiteralClass:
2797 case Expr::ImaginaryLiteralClass:
2798 case Expr::StringLiteralClass:
2799 case Expr::ArraySubscriptExprClass:
2800 case Expr::MemberExprClass:
2801 case Expr::CompoundAssignOperatorClass:
2802 case Expr::CompoundLiteralExprClass:
2803 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002804 case Expr::DesignatedInitExprClass:
2805 case Expr::ImplicitValueInitExprClass:
2806 case Expr::ParenListExprClass:
2807 case Expr::VAArgExprClass:
2808 case Expr::AddrLabelExprClass:
2809 case Expr::StmtExprClass:
2810 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002811 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002812 case Expr::CXXDynamicCastExprClass:
2813 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002814 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002815 case Expr::CXXNullPtrLiteralExprClass:
2816 case Expr::CXXThisExprClass:
2817 case Expr::CXXThrowExprClass:
2818 case Expr::CXXNewExprClass:
2819 case Expr::CXXDeleteExprClass:
2820 case Expr::CXXPseudoDestructorExprClass:
2821 case Expr::UnresolvedLookupExprClass:
2822 case Expr::DependentScopeDeclRefExprClass:
2823 case Expr::CXXConstructExprClass:
2824 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002825 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002826 case Expr::CXXTemporaryObjectExprClass:
2827 case Expr::CXXUnresolvedConstructExprClass:
2828 case Expr::CXXDependentScopeMemberExprClass:
2829 case Expr::UnresolvedMemberExprClass:
2830 case Expr::ObjCStringLiteralClass:
2831 case Expr::ObjCEncodeExprClass:
2832 case Expr::ObjCMessageExprClass:
2833 case Expr::ObjCSelectorExprClass:
2834 case Expr::ObjCProtocolExprClass:
2835 case Expr::ObjCIvarRefExprClass:
2836 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002837 case Expr::ObjCIsaExprClass:
2838 case Expr::ShuffleVectorExprClass:
2839 case Expr::BlockExprClass:
2840 case Expr::BlockDeclRefExprClass:
2841 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002842 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002843 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002844 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002845 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002846 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00002847 case Expr::MaterializeTemporaryExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002848 return ICEDiag(2, E->getLocStart());
2849
Sebastian Redlcea8d962011-09-24 17:48:14 +00002850 case Expr::InitListExprClass:
2851 if (Ctx.getLangOptions().CPlusPlus0x) {
2852 const InitListExpr *ILE = cast<InitListExpr>(E);
2853 if (ILE->getNumInits() == 0)
2854 return NoDiag();
2855 if (ILE->getNumInits() == 1)
2856 return CheckICE(ILE->getInit(0), Ctx);
2857 // Fall through for more than 1 expression.
2858 }
2859 return ICEDiag(2, E->getLocStart());
2860
Douglas Gregoree8aff02011-01-04 17:33:58 +00002861 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002862 case Expr::GNUNullExprClass:
2863 // GCC considers the GNU __null value to be an integral constant expression.
2864 return NoDiag();
2865
John McCall91a57552011-07-15 05:09:51 +00002866 case Expr::SubstNonTypeTemplateParmExprClass:
2867 return
2868 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2869
John McCalld905f5a2010-05-07 05:32:02 +00002870 case Expr::ParenExprClass:
2871 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002872 case Expr::GenericSelectionExprClass:
2873 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002874 case Expr::IntegerLiteralClass:
2875 case Expr::CharacterLiteralClass:
2876 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002877 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002878 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002879 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00002880 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00002881 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002882 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002883 return NoDiag();
2884 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002885 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002886 const CallExpr *CE = cast<CallExpr>(E);
2887 if (CE->isBuiltinCall(Ctx))
2888 return CheckEvalInICE(E, Ctx);
2889 return ICEDiag(2, E->getLocStart());
2890 }
2891 case Expr::DeclRefExprClass:
2892 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2893 return NoDiag();
2894 if (Ctx.getLangOptions().CPlusPlus &&
2895 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2896 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2897
2898 // Parameter variables are never constants. Without this check,
2899 // getAnyInitializer() can find a default argument, which leads
2900 // to chaos.
2901 if (isa<ParmVarDecl>(D))
2902 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2903
2904 // C++ 7.1.5.1p2
2905 // A variable of non-volatile const-qualified integral or enumeration
2906 // type initialized by an ICE can be used in ICEs.
2907 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2908 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2909 if (Quals.hasVolatile() || !Quals.hasConst())
2910 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2911
2912 // Look for a declaration of this variable that has an initializer.
2913 const VarDecl *ID = 0;
2914 const Expr *Init = Dcl->getAnyInitializer(ID);
2915 if (Init) {
2916 if (ID->isInitKnownICE()) {
2917 // We have already checked whether this subexpression is an
2918 // integral constant expression.
2919 if (ID->isInitICE())
2920 return NoDiag();
2921 else
2922 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2923 }
2924
2925 // It's an ICE whether or not the definition we found is
2926 // out-of-line. See DR 721 and the discussion in Clang PR
2927 // 6206 for details.
2928
2929 if (Dcl->isCheckingICE()) {
2930 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2931 }
2932
2933 Dcl->setCheckingICE();
2934 ICEDiag Result = CheckICE(Init, Ctx);
2935 // Cache the result of the ICE test.
2936 Dcl->setInitKnownICE(Result.Val == 0);
2937 return Result;
2938 }
2939 }
2940 }
2941 return ICEDiag(2, E->getLocStart());
2942 case Expr::UnaryOperatorClass: {
2943 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2944 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002945 case UO_PostInc:
2946 case UO_PostDec:
2947 case UO_PreInc:
2948 case UO_PreDec:
2949 case UO_AddrOf:
2950 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002951 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002952 case UO_Extension:
2953 case UO_LNot:
2954 case UO_Plus:
2955 case UO_Minus:
2956 case UO_Not:
2957 case UO_Real:
2958 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002959 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002960 }
2961
2962 // OffsetOf falls through here.
2963 }
2964 case Expr::OffsetOfExprClass: {
2965 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2966 // Evaluate matches the proposed gcc behavior for cases like
2967 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2968 // compliance: we should warn earlier for offsetof expressions with
2969 // array subscripts that aren't ICEs, and if the array subscripts
2970 // are ICEs, the value of the offsetof must be an integer constant.
2971 return CheckEvalInICE(E, Ctx);
2972 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002973 case Expr::UnaryExprOrTypeTraitExprClass: {
2974 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2975 if ((Exp->getKind() == UETT_SizeOf) &&
2976 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002977 return ICEDiag(2, E->getLocStart());
2978 return NoDiag();
2979 }
2980 case Expr::BinaryOperatorClass: {
2981 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2982 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002983 case BO_PtrMemD:
2984 case BO_PtrMemI:
2985 case BO_Assign:
2986 case BO_MulAssign:
2987 case BO_DivAssign:
2988 case BO_RemAssign:
2989 case BO_AddAssign:
2990 case BO_SubAssign:
2991 case BO_ShlAssign:
2992 case BO_ShrAssign:
2993 case BO_AndAssign:
2994 case BO_XorAssign:
2995 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002996 return ICEDiag(2, E->getLocStart());
2997
John McCall2de56d12010-08-25 11:45:40 +00002998 case BO_Mul:
2999 case BO_Div:
3000 case BO_Rem:
3001 case BO_Add:
3002 case BO_Sub:
3003 case BO_Shl:
3004 case BO_Shr:
3005 case BO_LT:
3006 case BO_GT:
3007 case BO_LE:
3008 case BO_GE:
3009 case BO_EQ:
3010 case BO_NE:
3011 case BO_And:
3012 case BO_Xor:
3013 case BO_Or:
3014 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00003015 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3016 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00003017 if (Exp->getOpcode() == BO_Div ||
3018 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00003019 // Evaluate gives an error for undefined Div/Rem, so make sure
3020 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00003021 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00003022 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
3023 if (REval == 0)
3024 return ICEDiag(1, E->getLocStart());
3025 if (REval.isSigned() && REval.isAllOnesValue()) {
3026 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
3027 if (LEval.isMinSignedValue())
3028 return ICEDiag(1, E->getLocStart());
3029 }
3030 }
3031 }
John McCall2de56d12010-08-25 11:45:40 +00003032 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00003033 if (Ctx.getLangOptions().C99) {
3034 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3035 // if it isn't evaluated.
3036 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3037 return ICEDiag(1, E->getLocStart());
3038 } else {
3039 // In both C89 and C++, commas in ICEs are illegal.
3040 return ICEDiag(2, E->getLocStart());
3041 }
3042 }
3043 if (LHSResult.Val >= RHSResult.Val)
3044 return LHSResult;
3045 return RHSResult;
3046 }
John McCall2de56d12010-08-25 11:45:40 +00003047 case BO_LAnd:
3048 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00003049 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00003050
3051 // C++0x [expr.const]p2:
3052 // [...] subexpressions of logical AND (5.14), logical OR
3053 // (5.15), and condi- tional (5.16) operations that are not
3054 // evaluated are not considered.
3055 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3056 if (Exp->getOpcode() == BO_LAnd &&
3057 Exp->getLHS()->EvaluateAsInt(Ctx) == 0)
3058 return LHSResult;
3059
3060 if (Exp->getOpcode() == BO_LOr &&
3061 Exp->getLHS()->EvaluateAsInt(Ctx) != 0)
3062 return LHSResult;
3063 }
3064
John McCalld905f5a2010-05-07 05:32:02 +00003065 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3066 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3067 // Rare case where the RHS has a comma "side-effect"; we need
3068 // to actually check the condition to see whether the side
3069 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003070 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00003071 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3072 return RHSResult;
3073 return NoDiag();
3074 }
3075
3076 if (LHSResult.Val >= RHSResult.Val)
3077 return LHSResult;
3078 return RHSResult;
3079 }
3080 }
3081 }
3082 case Expr::ImplicitCastExprClass:
3083 case Expr::CStyleCastExprClass:
3084 case Expr::CXXFunctionalCastExprClass:
3085 case Expr::CXXStaticCastExprClass:
3086 case Expr::CXXReinterpretCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003087 case Expr::CXXConstCastExprClass:
3088 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00003089 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003090 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003091 return CheckICE(SubExpr, Ctx);
3092 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3093 return NoDiag();
3094 return ICEDiag(2, E->getLocStart());
3095 }
John McCall56ca35d2011-02-17 10:25:35 +00003096 case Expr::BinaryConditionalOperatorClass: {
3097 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3098 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3099 if (CommonResult.Val == 2) return CommonResult;
3100 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3101 if (FalseResult.Val == 2) return FalseResult;
3102 if (CommonResult.Val == 1) return CommonResult;
3103 if (FalseResult.Val == 1 &&
3104 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3105 return FalseResult;
3106 }
John McCalld905f5a2010-05-07 05:32:02 +00003107 case Expr::ConditionalOperatorClass: {
3108 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3109 // If the condition (ignoring parens) is a __builtin_constant_p call,
3110 // then only the true side is actually considered in an integer constant
3111 // expression, and it is fully evaluated. This is an important GNU
3112 // extension. See GCC PR38377 for discussion.
3113 if (const CallExpr *CallCE
3114 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3115 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3116 Expr::EvalResult EVResult;
3117 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3118 !EVResult.Val.isInt()) {
3119 return ICEDiag(2, E->getLocStart());
3120 }
3121 return NoDiag();
3122 }
3123 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003124 if (CondResult.Val == 2)
3125 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00003126
3127 // C++0x [expr.const]p2:
3128 // subexpressions of [...] conditional (5.16) operations that
3129 // are not evaluated are not considered
3130 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
3131 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0
3132 : false;
3133 ICEDiag TrueResult = NoDiag();
3134 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3135 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3136 ICEDiag FalseResult = NoDiag();
3137 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3138 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3139
John McCalld905f5a2010-05-07 05:32:02 +00003140 if (TrueResult.Val == 2)
3141 return TrueResult;
3142 if (FalseResult.Val == 2)
3143 return FalseResult;
3144 if (CondResult.Val == 1)
3145 return CondResult;
3146 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3147 return NoDiag();
3148 // Rare case where the diagnostics depend on which side is evaluated
3149 // Note that if we get here, CondResult is 0, and at least one of
3150 // TrueResult and FalseResult is non-zero.
3151 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3152 return FalseResult;
3153 }
3154 return TrueResult;
3155 }
3156 case Expr::CXXDefaultArgExprClass:
3157 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3158 case Expr::ChooseExprClass: {
3159 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3160 }
3161 }
3162
3163 // Silence a GCC warning
3164 return ICEDiag(2, E->getLocStart());
3165}
3166
3167bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3168 SourceLocation *Loc, bool isEvaluated) const {
3169 ICEDiag d = CheckICE(this, Ctx);
3170 if (d.Val != 0) {
3171 if (Loc) *Loc = d.Loc;
3172 return false;
3173 }
3174 EvalResult EvalResult;
3175 if (!Evaluate(EvalResult, Ctx))
3176 llvm_unreachable("ICE cannot be evaluated!");
3177 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3178 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3179 Result = EvalResult.Val.getInt();
3180 return true;
3181}