blob: eb35dd7c989f168eba45372532de2de7514469b4 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-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 Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-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 McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Benjamin Kramer024e6192011-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 McCall93d91dc2010-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 McCallc07a0c72011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCallc07a0c72011-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 McCall93d91dc2010-05-07 17:22:02 +0000102 };
John McCall45d55e42010-05-07 21:00:08 +0000103
104 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000105 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000106 CharUnits Offset;
107
Peter Collingbournee9200682011-05-13 03:29:01 +0000108 const Expr *getLValueBase() { return Base; }
John McCall45d55e42010-05-07 21:00:08 +0000109 CharUnits getLValueOffset() { return Offset; }
110
John McCallc07a0c72011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCall45d55e42010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCallc07a0c72011-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 McCall45d55e42010-05-07 21:00:08 +0000119 };
John McCall93d91dc2010-05-07 17:22:02 +0000120}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000121
John McCallc07a0c72011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCall45d55e42010-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 Lattnercdf34e72008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattner6c4d2552009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-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 McCall45d55e42010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000154
John McCalleb3e4f32010-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 Espindolaa1f9cc12010-05-07 15:18:43 +0000161
John McCall95007602010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000164
John McCalleb3e4f32010-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 McCalleb3e4f32010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCalleb3e4f32010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman334046a2009-06-14 02:17:33 +0000181 return true;
182}
183
John McCall1be1c632010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman9a156e52008-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 Friedman64004332009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman9a156e52008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman334046a2009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedman64004332009-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 Friedman9a156e52008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump11289f42009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000224 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000225
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000227 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000228 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000229 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
230 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000231}
232
Mike Stump11289f42009-09-09 15:08:12 +0000233static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000234 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000235 bool ignored;
236 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000237 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000238 APFloat::rmNearestTiesToEven, &ignored);
239 return Result;
240}
241
Mike Stump11289f42009-09-09 15:08:12 +0000242static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000243 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-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 Foad6d4db0c2010-12-07 08:25:34 +0000248 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000249 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000250 return Result;
251}
252
Mike Stump11289f42009-09-09 15:08:12 +0000253static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000254 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-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 Stump876387b2009-10-27 22:09:17 +0000262namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000263class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000264 : public ConstStmtVisitor<HasSideEffect, bool> {
Mike Stump876387b2009-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 Collingbournee9200682011-05-13 03:29:01 +0000271 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000272 return true;
273 }
274
Peter Collingbournee9200682011-05-13 03:29:01 +0000275 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
276 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000277 return Visit(E->getResultExpr());
278 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000279 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000280 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000281 return true;
282 return false;
283 }
John McCall31168b02011-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 Stump876387b2009-10-27 22:09:17 +0000295 // We don't want to evaluate BlockExprs multiple times, as they generate
296 // a ton of code.
Peter Collingbournee9200682011-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 Stump876387b2009-10-27 22:09:17 +0000300 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-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 Collingbournee190dee2011-03-11 19:24:49 +0000307 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000308 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000309 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000310 bool VisitChooseExpr(const ChooseExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000311 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Peter Collingbournee9200682011-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 Stumpfa502902009-10-29 20:48:09 +0000316 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-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 Stump53f9ded2009-11-03 23:25:48 +0000322 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000323 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000324 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000325 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000326 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000327
328 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000329 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-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 Collingbournee9200682011-05-13 03:29:01 +0000332 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000333 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000334 return false;
335 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000336
Peter Collingbournee9200682011-05-13 03:29:01 +0000337 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000338};
339
John McCallc07a0c72011-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 Stump876387b2009-10-27 22:09:17 +0000364} // end anonymous namespace
365
Eli Friedman9a156e52008-11-12 09:44:48 +0000366//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-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 *) {
391 assert(0 && "Expression evaluator should not be called on stmts");
392 return DerivedError(0);
393 }
394 RetTy VisitExpr(const Expr *E) {
395 return DerivedError(E);
396 }
397
398 RetTy VisitParenExpr(const ParenExpr *E)
399 { return StmtVisitorTy::Visit(E->getSubExpr()); }
400 RetTy VisitUnaryExtension(const UnaryOperator *E)
401 { return StmtVisitorTy::Visit(E->getSubExpr()); }
402 RetTy VisitUnaryPlus(const UnaryOperator *E)
403 { return StmtVisitorTy::Visit(E->getSubExpr()); }
404 RetTy VisitChooseExpr(const ChooseExpr *E)
405 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
406 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
407 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000408 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
409 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000410
411 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
412 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
413 if (opaque.hasError())
414 return DerivedError(E);
415
416 bool cond;
417 if (!HandleConversionToBool(E->getCond(), cond, Info))
418 return DerivedError(E);
419
420 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
421 }
422
423 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
424 bool BoolResult;
425 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
426 return DerivedError(E);
427
428 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
429 return StmtVisitorTy::Visit(EvalExpr);
430 }
431
432 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
433 const APValue *value = Info.getOpaqueValue(E);
434 if (!value)
435 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
436 : DerivedError(E));
437 return DerivedSuccess(*value, E);
438 }
439};
440
441}
442
443//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000444// LValue Evaluation
445//===----------------------------------------------------------------------===//
446namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000447class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000448 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000449 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000450 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000451
Peter Collingbournee9200682011-05-13 03:29:01 +0000452 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000453 Result.Base = E;
454 Result.Offset = CharUnits::Zero();
455 return true;
456 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000457public:
Mike Stump11289f42009-09-09 15:08:12 +0000458
John McCall45d55e42010-05-07 21:00:08 +0000459 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000460 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000461
Peter Collingbournee9200682011-05-13 03:29:01 +0000462 bool Success(const APValue &V, const Expr *E) {
463 Result.setFrom(V);
464 return true;
465 }
466 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000467 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000468 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000469
Peter Collingbournee9200682011-05-13 03:29:01 +0000470 bool VisitDeclRefExpr(const DeclRefExpr *E);
471 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
472 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
473 bool VisitMemberExpr(const MemberExpr *E);
474 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
475 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
476 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
477 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000478
Peter Collingbournee9200682011-05-13 03:29:01 +0000479 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000480 switch (E->getCastKind()) {
481 default:
John McCall45d55e42010-05-07 21:00:08 +0000482 return false;
Anders Carlssonde55f642009-10-03 16:30:22 +0000483
John McCalle3027922010-08-25 11:45:40 +0000484 case CK_NoOp:
Anders Carlssonde55f642009-10-03 16:30:22 +0000485 return Visit(E->getSubExpr());
486 }
487 }
Eli Friedman449fe542009-03-23 04:56:01 +0000488 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000489
Eli Friedman9a156e52008-11-12 09:44:48 +0000490};
491} // end anonymous namespace
492
John McCall45d55e42010-05-07 21:00:08 +0000493static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000494 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000495}
496
Peter Collingbournee9200682011-05-13 03:29:01 +0000497bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000498 if (isa<FunctionDecl>(E->getDecl())) {
John McCall45d55e42010-05-07 21:00:08 +0000499 return Success(E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000500 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000501 if (!VD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000502 return Success(E);
Chandler Carruthe299ba62010-05-16 09:32:51 +0000503 // Reference parameters can refer to anything even if they have an
504 // "initializer" in the form of a default argument.
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000505 if (!isa<ParmVarDecl>(VD)) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000506 // FIXME: Check whether VD might be overridden!
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000507
508 // Check for recursive initializers of references.
509 if (PrevDecl == VD)
510 return Error(E);
511 PrevDecl = VD;
Peter Collingbournee9200682011-05-13 03:29:01 +0000512 if (const Expr *Init = VD->getAnyInitializer())
513 return Visit(Init);
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000514 }
Eli Friedman751aa72b72009-05-27 06:04:58 +0000515 }
516
Peter Collingbournee9200682011-05-13 03:29:01 +0000517 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000518}
519
Peter Collingbournee9200682011-05-13 03:29:01 +0000520bool
521LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000522 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000523}
524
Peter Collingbournee9200682011-05-13 03:29:01 +0000525bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000526 QualType Ty;
527 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000528 if (!EvaluatePointer(E->getBase(), Result, Info))
529 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000530 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000531 } else {
John McCall45d55e42010-05-07 21:00:08 +0000532 if (!Visit(E->getBase()))
533 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000534 Ty = E->getBase()->getType();
535 }
536
Peter Collingbournee9200682011-05-13 03:29:01 +0000537 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000538 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000539
Peter Collingbournee9200682011-05-13 03:29:01 +0000540 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000541 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000542 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000543
544 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000545 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000546
Eli Friedmana3c122d2011-07-07 01:54:01 +0000547 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000548 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000549 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000550}
551
Peter Collingbournee9200682011-05-13 03:29:01 +0000552bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000553 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000554 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000555
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000556 APSInt Index;
557 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000558 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000559
Ken Dyck40775002010-01-11 17:06:35 +0000560 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000561 Result.Offset += Index.getSExtValue() * ElementSize;
562 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000563}
Eli Friedman9a156e52008-11-12 09:44:48 +0000564
Peter Collingbournee9200682011-05-13 03:29:01 +0000565bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +0000566 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000567}
568
Eli Friedman9a156e52008-11-12 09:44:48 +0000569//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000570// Pointer Evaluation
571//===----------------------------------------------------------------------===//
572
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000573namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000574class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000575 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000576 LValue &Result;
577
Peter Collingbournee9200682011-05-13 03:29:01 +0000578 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000579 Result.Base = E;
580 Result.Offset = CharUnits::Zero();
581 return true;
582 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000583public:
Mike Stump11289f42009-09-09 15:08:12 +0000584
John McCall45d55e42010-05-07 21:00:08 +0000585 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000586 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000587
Peter Collingbournee9200682011-05-13 03:29:01 +0000588 bool Success(const APValue &V, const Expr *E) {
589 Result.setFrom(V);
590 return true;
591 }
592 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +0000593 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000594 }
595
John McCall45d55e42010-05-07 21:00:08 +0000596 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000597 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +0000598 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000599 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +0000600 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000601 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000602 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000603 bool VisitCallExpr(const CallExpr *E);
604 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +0000605 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000606 return Success(E);
607 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000608 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000609 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000610 { return Success((Expr*)0); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000611 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000612 { return Success((Expr*)0); }
John McCallc07a0c72011-02-17 10:25:35 +0000613
Eli Friedman449fe542009-03-23 04:56:01 +0000614 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000615};
Chris Lattner05706e882008-07-11 18:11:29 +0000616} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000617
John McCall45d55e42010-05-07 21:00:08 +0000618static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000619 assert(E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +0000620 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +0000621}
622
John McCall45d55e42010-05-07 21:00:08 +0000623bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000624 if (E->getOpcode() != BO_Add &&
625 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +0000626 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000627
Chris Lattner05706e882008-07-11 18:11:29 +0000628 const Expr *PExp = E->getLHS();
629 const Expr *IExp = E->getRHS();
630 if (IExp->getType()->isPointerType())
631 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000632
John McCall45d55e42010-05-07 21:00:08 +0000633 if (!EvaluatePointer(PExp, Result, Info))
634 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000635
John McCall45d55e42010-05-07 21:00:08 +0000636 llvm::APSInt Offset;
637 if (!EvaluateInteger(IExp, Offset, Info))
638 return false;
639 int64_t AdditionalOffset
640 = Offset.isSigned() ? Offset.getSExtValue()
641 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +0000642
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000643 // Compute the new offset in the appropriate width.
644
645 QualType PointeeType =
646 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +0000647 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +0000648
Anders Carlssonef56fba2009-02-19 04:55:58 +0000649 // Explicitly handle GNU void* and function pointer arithmetic extensions.
650 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +0000651 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +0000652 else
John McCall45d55e42010-05-07 21:00:08 +0000653 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +0000654
John McCalle3027922010-08-25 11:45:40 +0000655 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +0000656 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000657 else
John McCall45d55e42010-05-07 21:00:08 +0000658 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000659
John McCall45d55e42010-05-07 21:00:08 +0000660 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000661}
Eli Friedman9a156e52008-11-12 09:44:48 +0000662
John McCall45d55e42010-05-07 21:00:08 +0000663bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
664 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000665}
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattner05706e882008-07-11 18:11:29 +0000667
Peter Collingbournee9200682011-05-13 03:29:01 +0000668bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
669 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000670
Eli Friedman847a2bc2009-12-27 05:43:15 +0000671 switch (E->getCastKind()) {
672 default:
673 break;
674
John McCalle3027922010-08-25 11:45:40 +0000675 case CK_NoOp:
676 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +0000677 case CK_CPointerToObjCPointerCast:
678 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +0000679 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +0000680 return Visit(SubExpr);
681
Anders Carlsson18275092010-10-31 20:41:46 +0000682 case CK_DerivedToBase:
683 case CK_UncheckedDerivedToBase: {
684 LValue BaseLV;
685 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
686 return false;
687
688 // Now figure out the necessary offset to add to the baseLV to get from
689 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +0000690 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +0000691
692 QualType Ty = E->getSubExpr()->getType();
693 const CXXRecordDecl *DerivedDecl =
694 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
695
696 for (CastExpr::path_const_iterator PathI = E->path_begin(),
697 PathE = E->path_end(); PathI != PathE; ++PathI) {
698 const CXXBaseSpecifier *Base = *PathI;
699
700 // FIXME: If the base is virtual, we'd need to determine the type of the
701 // most derived class and we don't support that right now.
702 if (Base->isVirtual())
703 return false;
704
705 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
706 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
707
Ken Dyck02155cb2011-01-26 02:17:08 +0000708 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +0000709 DerivedDecl = BaseDecl;
710 }
711
712 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +0000713 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +0000714 return true;
715 }
716
John McCalle84af4e2010-11-13 01:35:44 +0000717 case CK_NullToPointer: {
718 Result.Base = 0;
719 Result.Offset = CharUnits::Zero();
720 return true;
721 }
722
John McCalle3027922010-08-25 11:45:40 +0000723 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +0000724 APValue Value;
725 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000726 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000727
John McCall45d55e42010-05-07 21:00:08 +0000728 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000729 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-05-07 21:00:08 +0000730 Result.Base = 0;
731 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
732 return true;
733 } else {
734 // Cast is of an lvalue, no need to change value.
735 Result.Base = Value.getLValueBase();
736 Result.Offset = Value.getLValueOffset();
737 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000738 }
739 }
John McCalle3027922010-08-25 11:45:40 +0000740 case CK_ArrayToPointerDecay:
741 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +0000742 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000743 }
744
John McCall45d55e42010-05-07 21:00:08 +0000745 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000746}
Chris Lattner05706e882008-07-11 18:11:29 +0000747
Peter Collingbournee9200682011-05-13 03:29:01 +0000748bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000749 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000750 Builtin::BI__builtin___CFStringMakeConstantString ||
751 E->isBuiltinCall(Info.Ctx) ==
752 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +0000753 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000754
Peter Collingbournee9200682011-05-13 03:29:01 +0000755 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000756}
Chris Lattner05706e882008-07-11 18:11:29 +0000757
758//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000759// Vector Evaluation
760//===----------------------------------------------------------------------===//
761
762namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000763 class VectorExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000764 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman3ae59112009-02-23 04:23:56 +0000765 APValue GetZeroVector(QualType VecType);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000766 public:
Mike Stump11289f42009-09-09 15:08:12 +0000767
Peter Collingbournee9200682011-05-13 03:29:01 +0000768 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump11289f42009-09-09 15:08:12 +0000769
Peter Collingbournee9200682011-05-13 03:29:01 +0000770 APValue Success(const APValue &V, const Expr *E) { return V; }
771 APValue Error(const Expr *E) { return APValue(); }
Mike Stump11289f42009-09-09 15:08:12 +0000772
Eli Friedman3ae59112009-02-23 04:23:56 +0000773 APValue VisitUnaryReal(const UnaryOperator *E)
774 { return Visit(E->getSubExpr()); }
775 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
776 { return GetZeroVector(E->getType()); }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000777 APValue VisitCastExpr(const CastExpr* E);
778 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
779 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000780 APValue VisitUnaryImag(const UnaryOperator *E);
781 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000782 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000783 // shufflevector, ExtVectorElementExpr
784 // (Note that these require implementing conversions
785 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000786 };
787} // end anonymous namespace
788
789static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
790 if (!E->getType()->isVectorType())
791 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +0000792 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000793 return !Result.isUninit();
794}
795
796APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall9dd450b2009-09-21 23:43:11 +0000797 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000798 QualType EltTy = VTy->getElementType();
799 unsigned NElts = VTy->getNumElements();
800 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000801
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000802 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000803 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000804
Eli Friedmanc757de22011-03-25 00:43:55 +0000805 switch (E->getCastKind()) {
806 case CK_VectorSplat: {
807 APValue Result = APValue();
808 if (SETy->isIntegerType()) {
809 APSInt IntResult;
810 if (!EvaluateInteger(SE, IntResult, Info))
811 return APValue();
812 Result = APValue(IntResult);
813 } else if (SETy->isRealFloatingType()) {
814 APFloat F(0.0);
815 if (!EvaluateFloat(SE, F, Info))
816 return APValue();
817 Result = APValue(F);
818 } else {
Anders Carlsson6fc22042011-03-25 11:22:47 +0000819 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000820 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000821
822 // Splat and create vector APValue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000823 SmallVector<APValue, 4> Elts(NElts, Result);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000824 return APValue(&Elts[0], Elts.size());
Nate Begeman2ffd3842009-06-26 18:22:18 +0000825 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000826 case CK_BitCast: {
827 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +0000828 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000829
Eli Friedmanc757de22011-03-25 00:43:55 +0000830 if (!SETy->isIntegerType())
Anders Carlsson6fc22042011-03-25 11:22:47 +0000831 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000832
Eli Friedmanc757de22011-03-25 00:43:55 +0000833 APSInt Init;
834 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000835 return APValue();
836
Eli Friedmanc757de22011-03-25 00:43:55 +0000837 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
838 "Vectors must be composed of ints or floats");
839
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000840 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +0000841 for (unsigned i = 0; i != NElts; ++i) {
842 APSInt Tmp = Init.extOrTrunc(EltWidth);
843
844 if (EltTy->isIntegerType())
845 Elts.push_back(APValue(Tmp));
846 else
847 Elts.push_back(APValue(APFloat(Tmp)));
848
849 Init >>= EltWidth;
850 }
851 return APValue(&Elts[0], Elts.size());
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000852 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000853 case CK_LValueToRValue:
854 case CK_NoOp:
Peter Collingbournee9200682011-05-13 03:29:01 +0000855 return Visit(SE);
Eli Friedmanc757de22011-03-25 00:43:55 +0000856 default:
Anders Carlsson6fc22042011-03-25 11:22:47 +0000857 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000858 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000859}
860
Mike Stump11289f42009-09-09 15:08:12 +0000861APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000862VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000863 return this->Visit(E->getInitializer());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000864}
865
Mike Stump11289f42009-09-09 15:08:12 +0000866APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000867VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall9dd450b2009-09-21 23:43:11 +0000868 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000869 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000870 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000871
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000872 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000873 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000874
John McCall875679e2010-06-11 17:54:15 +0000875 // If a vector is initialized with a single element, that value
876 // becomes every element of the vector, not just the first.
877 // This is the behavior described in the IBM AltiVec documentation.
878 if (NumInits == 1) {
Tanya Lattner5ac257d2011-04-15 22:42:59 +0000879
880 // Handle the case where the vector is initialized by a another
881 // vector (OpenCL 6.1.6).
882 if (E->getInit(0)->getType()->isVectorType())
883 return this->Visit(const_cast<Expr*>(E->getInit(0)));
884
John McCall875679e2010-06-11 17:54:15 +0000885 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000886 if (EltTy->isIntegerType()) {
887 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +0000888 if (!EvaluateInteger(E->getInit(0), sInt, Info))
889 return APValue();
890 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000891 } else {
892 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +0000893 if (!EvaluateFloat(E->getInit(0), f, Info))
894 return APValue();
895 InitValue = APValue(f);
896 }
897 for (unsigned i = 0; i < NumElements; i++) {
898 Elements.push_back(InitValue);
899 }
900 } else {
901 for (unsigned i = 0; i < NumElements; i++) {
902 if (EltTy->isIntegerType()) {
903 llvm::APSInt sInt(32);
904 if (i < NumInits) {
905 if (!EvaluateInteger(E->getInit(i), sInt, Info))
906 return APValue();
907 } else {
908 sInt = Info.Ctx.MakeIntValue(0, EltTy);
909 }
910 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +0000911 } else {
John McCall875679e2010-06-11 17:54:15 +0000912 llvm::APFloat f(0.0);
913 if (i < NumInits) {
914 if (!EvaluateFloat(E->getInit(i), f, Info))
915 return APValue();
916 } else {
917 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
918 }
919 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +0000920 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000921 }
922 }
923 return APValue(&Elements[0], Elements.size());
924}
925
Mike Stump11289f42009-09-09 15:08:12 +0000926APValue
Eli Friedman3ae59112009-02-23 04:23:56 +0000927VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +0000928 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +0000929 QualType EltTy = VT->getElementType();
930 APValue ZeroElement;
931 if (EltTy->isIntegerType())
932 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
933 else
934 ZeroElement =
935 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
936
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000937 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Eli Friedman3ae59112009-02-23 04:23:56 +0000938 return APValue(&Elements[0], Elements.size());
939}
940
Eli Friedman3ae59112009-02-23 04:23:56 +0000941APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
942 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
943 Info.EvalResult.HasSideEffects = true;
944 return GetZeroVector(E->getType());
945}
946
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000947//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000948// Integer Evaluation
949//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000950
951namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000952class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000953 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000954 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000955public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000956 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000957 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000958
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000959 bool Success(const llvm::APSInt &SI, const Expr *E) {
960 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +0000961 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000962 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000963 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000964 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000965 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000966 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000967 return true;
968 }
969
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000970 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000971 assert(E->getType()->isIntegralOrEnumerationType() &&
972 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000973 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000974 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000975 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000976 Result.getInt().setIsUnsigned(
977 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000978 return true;
979 }
980
981 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000982 assert(E->getType()->isIntegralOrEnumerationType() &&
983 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000984 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000985 return true;
986 }
987
Ken Dyckdbc01912011-03-11 02:13:43 +0000988 bool Success(CharUnits Size, const Expr *E) {
989 return Success(Size.getQuantity(), E);
990 }
991
992
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000993 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000994 // Take the first error.
Anders Carlssonbd1df8e2008-11-30 16:38:33 +0000995 if (Info.EvalResult.Diag == 0) {
996 Info.EvalResult.DiagLoc = L;
997 Info.EvalResult.Diag = D;
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000998 Info.EvalResult.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000999 }
Chris Lattner99415702008-07-12 00:14:42 +00001000 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001001 }
Mike Stump11289f42009-09-09 15:08:12 +00001002
Peter Collingbournee9200682011-05-13 03:29:01 +00001003 bool Success(const APValue &V, const Expr *E) {
1004 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001005 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001006 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001007 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001008 }
Mike Stump11289f42009-09-09 15:08:12 +00001009
Peter Collingbournee9200682011-05-13 03:29:01 +00001010 //===--------------------------------------------------------------------===//
1011 // Visitor Methods
1012 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001013
Chris Lattner7174bf32008-07-12 00:38:25 +00001014 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001015 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001016 }
1017 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001018 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001019 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001020
1021 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1022 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001023 if (CheckReferencedDecl(E, E->getDecl()))
1024 return true;
1025
1026 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001027 }
1028 bool VisitMemberExpr(const MemberExpr *E) {
1029 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1030 // Conservatively assume a MemberExpr will have side-effects
1031 Info.EvalResult.HasSideEffects = true;
1032 return true;
1033 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001034
1035 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001036 }
1037
Peter Collingbournee9200682011-05-13 03:29:01 +00001038 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001039 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001040 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001041 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001042
Peter Collingbournee9200682011-05-13 03:29:01 +00001043 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001044 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001045
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001046 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001047 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001048 }
Mike Stump11289f42009-09-09 15:08:12 +00001049
Anders Carlsson39def3a2008-12-21 22:39:40 +00001050 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001051 return Success(0, E);
Anders Carlsson39def3a2008-12-21 22:39:40 +00001052 }
Mike Stump11289f42009-09-09 15:08:12 +00001053
Douglas Gregor747eb782010-07-08 06:14:04 +00001054 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001055 return Success(0, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001056 }
1057
Eli Friedman4e7a2412009-02-27 04:45:43 +00001058 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1059 return Success(0, E);
1060 }
1061
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001062 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001063 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001064 }
1065
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001066 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1067 return Success(E->getValue(), E);
1068 }
1069
John Wiegley6242b6a2011-04-28 00:16:57 +00001070 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1071 return Success(E->getValue(), E);
1072 }
1073
John Wiegleyf9f65842011-04-25 06:54:41 +00001074 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1075 return Success(E->getValue(), E);
1076 }
1077
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001078 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001079 bool VisitUnaryImag(const UnaryOperator *E);
1080
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001081 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001082 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1083
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001084private:
Ken Dyck160146e2010-01-27 17:10:57 +00001085 CharUnits GetAlignOfExpr(const Expr *E);
1086 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001087 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001088 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001089 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001090};
Chris Lattner05706e882008-07-11 18:11:29 +00001091} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001092
Daniel Dunbarce399542009-02-20 18:22:23 +00001093static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001094 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001095 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001096}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001097
Daniel Dunbarce399542009-02-20 18:22:23 +00001098static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001099 assert(E->getType()->isIntegralOrEnumerationType());
John McCallf0c4f352010-05-07 05:46:35 +00001100
Daniel Dunbarce399542009-02-20 18:22:23 +00001101 APValue Val;
1102 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1103 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001104 Result = Val.getInt();
1105 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001106}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001107
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001108bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001109 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001110 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001111 // Check for signedness/width mismatches between E type and ECD value.
1112 bool SameSign = (ECD->getInitVal().isSigned()
1113 == E->getType()->isSignedIntegerOrEnumerationType());
1114 bool SameWidth = (ECD->getInitVal().getBitWidth()
1115 == Info.Ctx.getIntWidth(E->getType()));
1116 if (SameSign && SameWidth)
1117 return Success(ECD->getInitVal(), E);
1118 else {
1119 // Get rid of mismatch (otherwise Success assertions will fail)
1120 // by computing a new value matching the type of E.
1121 llvm::APSInt Val = ECD->getInitVal();
1122 if (!SameSign)
1123 Val.setIsSigned(!ECD->getInitVal().isSigned());
1124 if (!SameWidth)
1125 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1126 return Success(Val, E);
1127 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001128 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001129
1130 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +00001131 // In C, they can also be folded, although they are not ICEs.
Douglas Gregor0840cc02009-11-01 20:32:48 +00001132 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1133 == Qualifiers::Const) {
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001134
1135 if (isa<ParmVarDecl>(D))
Peter Collingbournee9200682011-05-13 03:29:01 +00001136 return false;
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001137
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001138 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001139 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedman1d6fb162009-12-03 20:31:57 +00001140 if (APValue *V = VD->getEvaluatedValue()) {
1141 if (V->isInt())
1142 return Success(V->getInt(), E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001143 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001144 }
1145
1146 if (VD->isEvaluatingValue())
Peter Collingbournee9200682011-05-13 03:29:01 +00001147 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001148
1149 VD->setEvaluatingValue();
1150
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001151 Expr::EvalResult EResult;
1152 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1153 EResult.Val.isInt()) {
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001154 // Cache the evaluated value in the variable declaration.
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001155 Result = EResult.Val;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001156 VD->setEvaluatedValue(Result);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001157 return true;
1158 }
1159
Eli Friedman1d6fb162009-12-03 20:31:57 +00001160 VD->setEvaluatedValue(APValue());
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001161 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001162 }
1163 }
1164
Chris Lattner7174bf32008-07-12 00:38:25 +00001165 // Otherwise, random variable references are not constants.
Peter Collingbournee9200682011-05-13 03:29:01 +00001166 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001167}
1168
Chris Lattner86ee2862008-10-06 06:40:35 +00001169/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1170/// as GCC.
1171static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1172 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001173 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001174 enum gcc_type_class {
1175 no_type_class = -1,
1176 void_type_class, integer_type_class, char_type_class,
1177 enumeral_type_class, boolean_type_class,
1178 pointer_type_class, reference_type_class, offset_type_class,
1179 real_type_class, complex_type_class,
1180 function_type_class, method_type_class,
1181 record_type_class, union_type_class,
1182 array_type_class, string_type_class,
1183 lang_type_class
1184 };
Mike Stump11289f42009-09-09 15:08:12 +00001185
1186 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001187 // ideal, however it is what gcc does.
1188 if (E->getNumArgs() == 0)
1189 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001190
Chris Lattner86ee2862008-10-06 06:40:35 +00001191 QualType ArgTy = E->getArg(0)->getType();
1192 if (ArgTy->isVoidType())
1193 return void_type_class;
1194 else if (ArgTy->isEnumeralType())
1195 return enumeral_type_class;
1196 else if (ArgTy->isBooleanType())
1197 return boolean_type_class;
1198 else if (ArgTy->isCharType())
1199 return string_type_class; // gcc doesn't appear to use char_type_class
1200 else if (ArgTy->isIntegerType())
1201 return integer_type_class;
1202 else if (ArgTy->isPointerType())
1203 return pointer_type_class;
1204 else if (ArgTy->isReferenceType())
1205 return reference_type_class;
1206 else if (ArgTy->isRealType())
1207 return real_type_class;
1208 else if (ArgTy->isComplexType())
1209 return complex_type_class;
1210 else if (ArgTy->isFunctionType())
1211 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001212 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001213 return record_type_class;
1214 else if (ArgTy->isUnionType())
1215 return union_type_class;
1216 else if (ArgTy->isArrayType())
1217 return array_type_class;
1218 else if (ArgTy->isUnionType())
1219 return union_type_class;
1220 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1221 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1222 return -1;
1223}
1224
John McCall95007602010-05-10 23:27:23 +00001225/// Retrieves the "underlying object type" of the given expression,
1226/// as used by __builtin_object_size.
1227QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1228 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1229 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1230 return VD->getType();
1231 } else if (isa<CompoundLiteralExpr>(E)) {
1232 return E->getType();
1233 }
1234
1235 return QualType();
1236}
1237
Peter Collingbournee9200682011-05-13 03:29:01 +00001238bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001239 // TODO: Perhaps we should let LLVM lower this?
1240 LValue Base;
1241 if (!EvaluatePointer(E->getArg(0), Base, Info))
1242 return false;
1243
1244 // If we can prove the base is null, lower to zero now.
1245 const Expr *LVBase = Base.getLValueBase();
1246 if (!LVBase) return Success(0, E);
1247
1248 QualType T = GetObjectType(LVBase);
1249 if (T.isNull() ||
1250 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001251 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001252 T->isVariablyModifiedType() ||
1253 T->isDependentType())
1254 return false;
1255
1256 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1257 CharUnits Offset = Base.getLValueOffset();
1258
1259 if (!Offset.isNegative() && Offset <= Size)
1260 Size -= Offset;
1261 else
1262 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001263 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001264}
1265
Peter Collingbournee9200682011-05-13 03:29:01 +00001266bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001267 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001268 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001269 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001270
1271 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001272 if (TryEvaluateBuiltinObjectSize(E))
1273 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001274
Eric Christopher99469702010-01-19 22:58:35 +00001275 // If evaluating the argument has side-effects we can't determine
1276 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001277 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer0128f662010-01-03 18:18:37 +00001278 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001279 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001280 return Success(0, E);
1281 }
Mike Stump876387b2009-10-27 22:09:17 +00001282
Mike Stump722cedf2009-10-26 18:35:08 +00001283 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1284 }
1285
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001286 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001287 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001288
Anders Carlsson4c76e932008-11-24 04:21:33 +00001289 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001290 // __builtin_constant_p always has one operand: it returns true if that
1291 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001292 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001293
1294 case Builtin::BI__builtin_eh_return_data_regno: {
1295 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001296 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001297 return Success(Operand, E);
1298 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001299
1300 case Builtin::BI__builtin_expect:
1301 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001302
1303 case Builtin::BIstrlen:
1304 case Builtin::BI__builtin_strlen:
1305 // As an extension, we support strlen() and __builtin_strlen() as constant
1306 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001307 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001308 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1309 // The string literal may have embedded null characters. Find the first
1310 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001311 StringRef Str = S->getString();
1312 StringRef::size_type Pos = Str.find(0);
1313 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001314 Str = Str.substr(0, Pos);
1315
1316 return Success(Str.size(), E);
1317 }
1318
1319 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001320 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001321}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001322
Chris Lattnere13042c2008-07-11 19:10:17 +00001323bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001324 if (E->getOpcode() == BO_Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001325 if (!Visit(E->getRHS()))
1326 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001327
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001328 // If we can't evaluate the LHS, it might have side effects;
1329 // conservatively mark it.
1330 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1331 Info.EvalResult.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001332
Anders Carlsson564730a2008-12-01 02:07:06 +00001333 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001334 }
1335
1336 if (E->isLogicalOp()) {
1337 // These need to be handled specially because the operands aren't
1338 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001339 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001340
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001341 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001342 // We were able to evaluate the LHS, see if we can get away with not
1343 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001344 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001345 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001346
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001347 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001348 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001349 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001350 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001351 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001352 }
1353 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001354 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001355 // We can't evaluate the LHS; however, sometimes the result
1356 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001357 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1358 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001359 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001360 // must have had side effects.
1361 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001362
1363 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001364 }
1365 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001366 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001367
Eli Friedman5a332ea2008-11-13 06:09:17 +00001368 return false;
1369 }
1370
Anders Carlssonacc79812008-11-16 07:17:21 +00001371 QualType LHSTy = E->getLHS()->getType();
1372 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001373
1374 if (LHSTy->isAnyComplexType()) {
1375 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001376 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001377
1378 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1379 return false;
1380
1381 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1382 return false;
1383
1384 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001385 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001386 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001387 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001388 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1389
John McCalle3027922010-08-25 11:45:40 +00001390 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001391 return Success((CR_r == APFloat::cmpEqual &&
1392 CR_i == APFloat::cmpEqual), E);
1393 else {
John McCalle3027922010-08-25 11:45:40 +00001394 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001395 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001396 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001397 CR_r == APFloat::cmpLessThan ||
1398 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001399 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001400 CR_i == APFloat::cmpLessThan ||
1401 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001402 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001403 } else {
John McCalle3027922010-08-25 11:45:40 +00001404 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001405 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1406 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1407 else {
John McCalle3027922010-08-25 11:45:40 +00001408 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001409 "Invalid compex comparison.");
1410 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1411 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1412 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001413 }
1414 }
Mike Stump11289f42009-09-09 15:08:12 +00001415
Anders Carlssonacc79812008-11-16 07:17:21 +00001416 if (LHSTy->isRealFloatingType() &&
1417 RHSTy->isRealFloatingType()) {
1418 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001419
Anders Carlssonacc79812008-11-16 07:17:21 +00001420 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1421 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001422
Anders Carlssonacc79812008-11-16 07:17:21 +00001423 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1424 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001425
Anders Carlssonacc79812008-11-16 07:17:21 +00001426 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001427
Anders Carlssonacc79812008-11-16 07:17:21 +00001428 switch (E->getOpcode()) {
1429 default:
1430 assert(0 && "Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001431 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001432 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001433 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001434 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001435 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001436 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001437 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001438 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001439 E);
John McCalle3027922010-08-25 11:45:40 +00001440 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001441 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001442 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001443 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001444 || CR == APFloat::cmpLessThan
1445 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001446 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001447 }
Mike Stump11289f42009-09-09 15:08:12 +00001448
Eli Friedmana38da572009-04-28 19:17:36 +00001449 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001450 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001451 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001452 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1453 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001454
John McCall45d55e42010-05-07 21:00:08 +00001455 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001456 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1457 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001458
Eli Friedman334046a2009-06-14 02:17:33 +00001459 // Reject any bases from the normal codepath; we special-case comparisons
1460 // to null.
1461 if (LHSValue.getLValueBase()) {
1462 if (!E->isEqualityOp())
1463 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001464 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001465 return false;
1466 bool bres;
1467 if (!EvalPointerValueAsBool(LHSValue, bres))
1468 return false;
John McCalle3027922010-08-25 11:45:40 +00001469 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001470 } else if (RHSValue.getLValueBase()) {
1471 if (!E->isEqualityOp())
1472 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001473 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001474 return false;
1475 bool bres;
1476 if (!EvalPointerValueAsBool(RHSValue, bres))
1477 return false;
John McCalle3027922010-08-25 11:45:40 +00001478 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001479 }
Eli Friedman64004332009-03-23 04:38:34 +00001480
John McCalle3027922010-08-25 11:45:40 +00001481 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001482 QualType Type = E->getLHS()->getType();
1483 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001484
Ken Dyck02990832010-01-15 12:37:54 +00001485 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001486 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001487 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001488
Ken Dyck02990832010-01-15 12:37:54 +00001489 CharUnits Diff = LHSValue.getLValueOffset() -
1490 RHSValue.getLValueOffset();
1491 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001492 }
1493 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001494 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001495 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001496 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001497 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1498 }
1499 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001500 }
1501 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001502 if (!LHSTy->isIntegralOrEnumerationType() ||
1503 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001504 // We can't continue from here for non-integral types, and they
1505 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001506 return false;
1507 }
1508
Anders Carlsson9c181652008-07-08 14:35:21 +00001509 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001510 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001511 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001512
Eli Friedman94c25c62009-03-24 01:14:50 +00001513 APValue RHSVal;
1514 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001515 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001516
1517 // Handle cases like (unsigned long)&a + 4.
1518 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001519 CharUnits Offset = Result.getLValueOffset();
1520 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1521 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001522 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001523 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001524 else
Ken Dyck02990832010-01-15 12:37:54 +00001525 Offset -= AdditionalOffset;
1526 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001527 return true;
1528 }
1529
1530 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001531 if (E->getOpcode() == BO_Add &&
Eli Friedman94c25c62009-03-24 01:14:50 +00001532 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001533 CharUnits Offset = RHSVal.getLValueOffset();
1534 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1535 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001536 return true;
1537 }
1538
1539 // All the following cases expect both operands to be an integer
1540 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001541 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001542
Eli Friedman94c25c62009-03-24 01:14:50 +00001543 APSInt& RHS = RHSVal.getInt();
1544
Anders Carlsson9c181652008-07-08 14:35:21 +00001545 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001546 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001547 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001548 case BO_Mul: return Success(Result.getInt() * RHS, E);
1549 case BO_Add: return Success(Result.getInt() + RHS, E);
1550 case BO_Sub: return Success(Result.getInt() - RHS, E);
1551 case BO_And: return Success(Result.getInt() & RHS, E);
1552 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1553 case BO_Or: return Success(Result.getInt() | RHS, E);
1554 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001555 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001556 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001557 return Success(Result.getInt() / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001558 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001559 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001560 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001561 return Success(Result.getInt() % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001562 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001563 // During constant-folding, a negative shift is an opposite shift.
1564 if (RHS.isSigned() && RHS.isNegative()) {
1565 RHS = -RHS;
1566 goto shift_right;
1567 }
1568
1569 shift_left:
1570 unsigned SA
1571 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001572 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001573 }
John McCalle3027922010-08-25 11:45:40 +00001574 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001575 // During constant-folding, a negative shift is an opposite shift.
1576 if (RHS.isSigned() && RHS.isNegative()) {
1577 RHS = -RHS;
1578 goto shift_left;
1579 }
1580
1581 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001582 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001583 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1584 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
John McCalle3027922010-08-25 11:45:40 +00001587 case BO_LT: return Success(Result.getInt() < RHS, E);
1588 case BO_GT: return Success(Result.getInt() > RHS, E);
1589 case BO_LE: return Success(Result.getInt() <= RHS, E);
1590 case BO_GE: return Success(Result.getInt() >= RHS, E);
1591 case BO_EQ: return Success(Result.getInt() == RHS, E);
1592 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001593 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001594}
1595
Ken Dyck160146e2010-01-27 17:10:57 +00001596CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001597 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1598 // the result is the size of the referenced type."
1599 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1600 // result shall be the alignment of the referenced type."
1601 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1602 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00001603
1604 // __alignof is defined to return the preferred alignment.
1605 return Info.Ctx.toCharUnitsFromBits(
1606 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001607}
1608
Ken Dyck160146e2010-01-27 17:10:57 +00001609CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001610 E = E->IgnoreParens();
1611
1612 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001613 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001614 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001615 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1616 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001617
Chris Lattner68061312009-01-24 21:53:27 +00001618 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001619 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1620 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001621
Chris Lattner24aeeab2009-01-24 21:09:06 +00001622 return GetAlignOfType(E->getType());
1623}
1624
1625
Peter Collingbournee190dee2011-03-11 19:24:49 +00001626/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1627/// a result as the expression's type.
1628bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1629 const UnaryExprOrTypeTraitExpr *E) {
1630 switch(E->getKind()) {
1631 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001632 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00001633 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001634 else
Ken Dyckdbc01912011-03-11 02:13:43 +00001635 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001636 }
Eli Friedman64004332009-03-23 04:38:34 +00001637
Peter Collingbournee190dee2011-03-11 19:24:49 +00001638 case UETT_VecStep: {
1639 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00001640
Peter Collingbournee190dee2011-03-11 19:24:49 +00001641 if (Ty->isVectorType()) {
1642 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00001643
Peter Collingbournee190dee2011-03-11 19:24:49 +00001644 // The vec_step built-in functions that take a 3-component
1645 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1646 if (n == 3)
1647 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001648
Peter Collingbournee190dee2011-03-11 19:24:49 +00001649 return Success(n, E);
1650 } else
1651 return Success(1, E);
1652 }
1653
1654 case UETT_SizeOf: {
1655 QualType SrcTy = E->getTypeOfArgument();
1656 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1657 // the result is the size of the referenced type."
1658 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1659 // result shall be the alignment of the referenced type."
1660 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1661 SrcTy = Ref->getPointeeType();
1662
1663 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1664 // extension.
1665 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1666 return Success(1, E);
1667
1668 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1669 if (!SrcTy->isConstantSizeType())
1670 return false;
1671
1672 // Get information about the size.
1673 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1674 }
1675 }
1676
1677 llvm_unreachable("unknown expr/type trait");
1678 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001679}
1680
Peter Collingbournee9200682011-05-13 03:29:01 +00001681bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00001682 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00001683 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00001684 if (n == 0)
1685 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001686 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00001687 for (unsigned i = 0; i != n; ++i) {
1688 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1689 switch (ON.getKind()) {
1690 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00001691 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00001692 APSInt IdxResult;
1693 if (!EvaluateInteger(Idx, IdxResult, Info))
1694 return false;
1695 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1696 if (!AT)
1697 return false;
1698 CurrentType = AT->getElementType();
1699 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1700 Result += IdxResult.getSExtValue() * ElementSize;
1701 break;
1702 }
1703
1704 case OffsetOfExpr::OffsetOfNode::Field: {
1705 FieldDecl *MemberDecl = ON.getField();
1706 const RecordType *RT = CurrentType->getAs<RecordType>();
1707 if (!RT)
1708 return false;
1709 RecordDecl *RD = RT->getDecl();
1710 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00001711 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00001712 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001713 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00001714 CurrentType = MemberDecl->getType().getNonReferenceType();
1715 break;
1716 }
1717
1718 case OffsetOfExpr::OffsetOfNode::Identifier:
1719 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001720 return false;
1721
1722 case OffsetOfExpr::OffsetOfNode::Base: {
1723 CXXBaseSpecifier *BaseSpec = ON.getBase();
1724 if (BaseSpec->isVirtual())
1725 return false;
1726
1727 // Find the layout of the class whose base we are looking into.
1728 const RecordType *RT = CurrentType->getAs<RecordType>();
1729 if (!RT)
1730 return false;
1731 RecordDecl *RD = RT->getDecl();
1732 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1733
1734 // Find the base class itself.
1735 CurrentType = BaseSpec->getType();
1736 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1737 if (!BaseRT)
1738 return false;
1739
1740 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00001741 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00001742 break;
1743 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001744 }
1745 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001746 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00001747}
1748
Chris Lattnere13042c2008-07-11 19:10:17 +00001749bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001750 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001751 // LNot's operand isn't necessarily an integer, so we handle it specially.
1752 bool bres;
1753 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1754 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001755 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001756 }
1757
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001758 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00001759 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001760 return false;
1761
Chris Lattnercdf34e72008-07-11 22:52:41 +00001762 // Get the operand value into 'Result'.
1763 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001764 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001765
Chris Lattnerf09ad162008-07-11 22:15:16 +00001766 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001767 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001768 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1769 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001770 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001771 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001772 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1773 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001774 return true;
John McCalle3027922010-08-25 11:45:40 +00001775 case UO_Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001776 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001777 return true;
John McCalle3027922010-08-25 11:45:40 +00001778 case UO_Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001779 if (!Result.isInt()) return false;
1780 return Success(-Result.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00001781 case UO_Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001782 if (!Result.isInt()) return false;
1783 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001784 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001785}
Mike Stump11289f42009-09-09 15:08:12 +00001786
Chris Lattner477c4be2008-07-12 01:15:53 +00001787/// HandleCast - This is used to evaluate implicit or explicit casts where the
1788/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00001789bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1790 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001791 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001792 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001793
Eli Friedmanc757de22011-03-25 00:43:55 +00001794 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00001795 case CK_BaseToDerived:
1796 case CK_DerivedToBase:
1797 case CK_UncheckedDerivedToBase:
1798 case CK_Dynamic:
1799 case CK_ToUnion:
1800 case CK_ArrayToPointerDecay:
1801 case CK_FunctionToPointerDecay:
1802 case CK_NullToPointer:
1803 case CK_NullToMemberPointer:
1804 case CK_BaseToDerivedMemberPointer:
1805 case CK_DerivedToBaseMemberPointer:
1806 case CK_ConstructorConversion:
1807 case CK_IntegralToPointer:
1808 case CK_ToVoid:
1809 case CK_VectorSplat:
1810 case CK_IntegralToFloating:
1811 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00001812 case CK_CPointerToObjCPointerCast:
1813 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001814 case CK_AnyPointerToBlockPointerCast:
1815 case CK_ObjCObjectLValueCast:
1816 case CK_FloatingRealToComplex:
1817 case CK_FloatingComplexToReal:
1818 case CK_FloatingComplexCast:
1819 case CK_FloatingComplexToIntegralComplex:
1820 case CK_IntegralRealToComplex:
1821 case CK_IntegralComplexCast:
1822 case CK_IntegralComplexToFloatingComplex:
1823 llvm_unreachable("invalid cast kind for integral value");
1824
Eli Friedman9faf2f92011-03-25 19:07:11 +00001825 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001826 case CK_Dependent:
1827 case CK_GetObjCProperty:
1828 case CK_LValueBitCast:
1829 case CK_UserDefinedConversion:
John McCall31168b02011-06-15 23:02:42 +00001830 case CK_ObjCProduceObject:
1831 case CK_ObjCConsumeObject:
John McCall4db5c3c2011-07-07 06:58:02 +00001832 case CK_ObjCReclaimReturnedObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00001833 return false;
1834
1835 case CK_LValueToRValue:
1836 case CK_NoOp:
1837 return Visit(E->getSubExpr());
1838
1839 case CK_MemberPointerToBoolean:
1840 case CK_PointerToBoolean:
1841 case CK_IntegralToBoolean:
1842 case CK_FloatingToBoolean:
1843 case CK_FloatingComplexToBoolean:
1844 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00001845 bool BoolResult;
1846 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1847 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001848 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001849 }
1850
Eli Friedmanc757de22011-03-25 00:43:55 +00001851 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00001852 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001853 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001854
Eli Friedman742421e2009-02-20 01:15:07 +00001855 if (!Result.isInt()) {
1856 // Only allow casts of lvalues if they are lossless.
1857 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1858 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001859
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001860 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001861 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001862 }
Mike Stump11289f42009-09-09 15:08:12 +00001863
Eli Friedmanc757de22011-03-25 00:43:55 +00001864 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00001865 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001866 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001867 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001868
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001869 if (LV.getLValueBase()) {
1870 // Only allow based lvalue casts if they are lossless.
1871 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1872 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001873
John McCall45d55e42010-05-07 21:00:08 +00001874 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001875 return true;
1876 }
1877
Ken Dyck02990832010-01-15 12:37:54 +00001878 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1879 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001880 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001881 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001882
Eli Friedmanc757de22011-03-25 00:43:55 +00001883 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00001884 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001885 if (!EvaluateComplex(SubExpr, C, Info))
1886 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00001887 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001888 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001889
Eli Friedmanc757de22011-03-25 00:43:55 +00001890 case CK_FloatingToIntegral: {
1891 APFloat F(0.0);
1892 if (!EvaluateFloat(SubExpr, F, Info))
1893 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00001894
Eli Friedmanc757de22011-03-25 00:43:55 +00001895 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1896 }
1897 }
Mike Stump11289f42009-09-09 15:08:12 +00001898
Eli Friedmanc757de22011-03-25 00:43:55 +00001899 llvm_unreachable("unknown cast resulting in integral value");
1900 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001901}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001902
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001903bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1904 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001905 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001906 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1907 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1908 return Success(LV.getComplexIntReal(), E);
1909 }
1910
1911 return Visit(E->getSubExpr());
1912}
1913
Eli Friedman4e7a2412009-02-27 04:45:43 +00001914bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001915 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001916 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001917 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1918 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1919 return Success(LV.getComplexIntImag(), E);
1920 }
1921
Eli Friedman4e7a2412009-02-27 04:45:43 +00001922 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1923 Info.EvalResult.HasSideEffects = true;
1924 return Success(0, E);
1925}
1926
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001927bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1928 return Success(E->getPackLength(), E);
1929}
1930
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001931bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1932 return Success(E->getValue(), E);
1933}
1934
Chris Lattner05706e882008-07-11 18:11:29 +00001935//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00001936// Float Evaluation
1937//===----------------------------------------------------------------------===//
1938
1939namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001940class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001941 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00001942 APFloat &Result;
1943public:
1944 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001945 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00001946
Peter Collingbournee9200682011-05-13 03:29:01 +00001947 bool Success(const APValue &V, const Expr *e) {
1948 Result = V.getFloat();
1949 return true;
1950 }
1951 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00001952 return false;
1953 }
1954
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001955 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001956
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001957 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001958 bool VisitBinaryOperator(const BinaryOperator *E);
1959 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001960 bool VisitCastExpr(const CastExpr *E);
1961 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00001962
John McCallb1fb0d32010-05-07 22:08:54 +00001963 bool VisitUnaryReal(const UnaryOperator *E);
1964 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00001965
John McCalla2fabff2010-10-09 01:34:31 +00001966 bool VisitDeclRefExpr(const DeclRefExpr *E);
1967
John McCallb1fb0d32010-05-07 22:08:54 +00001968 // FIXME: Missing: array subscript of vector, member of vector,
1969 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00001970};
1971} // end anonymous namespace
1972
1973static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00001974 assert(E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001975 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00001976}
1977
Jay Foad39c79802011-01-12 09:06:06 +00001978static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00001979 QualType ResultTy,
1980 const Expr *Arg,
1981 bool SNaN,
1982 llvm::APFloat &Result) {
1983 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1984 if (!S) return false;
1985
1986 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1987
1988 llvm::APInt fill;
1989
1990 // Treat empty strings as if they were zero.
1991 if (S->getString().empty())
1992 fill = llvm::APInt(32, 0);
1993 else if (S->getString().getAsInteger(0, fill))
1994 return false;
1995
1996 if (SNaN)
1997 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1998 else
1999 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2000 return true;
2001}
2002
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002003bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002004 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002005 default:
2006 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2007
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002008 case Builtin::BI__builtin_huge_val:
2009 case Builtin::BI__builtin_huge_valf:
2010 case Builtin::BI__builtin_huge_vall:
2011 case Builtin::BI__builtin_inf:
2012 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002013 case Builtin::BI__builtin_infl: {
2014 const llvm::fltSemantics &Sem =
2015 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002016 Result = llvm::APFloat::getInf(Sem);
2017 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002018 }
Mike Stump11289f42009-09-09 15:08:12 +00002019
John McCall16291492010-02-28 13:00:19 +00002020 case Builtin::BI__builtin_nans:
2021 case Builtin::BI__builtin_nansf:
2022 case Builtin::BI__builtin_nansl:
2023 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2024 true, Result);
2025
Chris Lattner0b7282e2008-10-06 06:31:58 +00002026 case Builtin::BI__builtin_nan:
2027 case Builtin::BI__builtin_nanf:
2028 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002029 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002030 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002031 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2032 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002033
2034 case Builtin::BI__builtin_fabs:
2035 case Builtin::BI__builtin_fabsf:
2036 case Builtin::BI__builtin_fabsl:
2037 if (!EvaluateFloat(E->getArg(0), Result, Info))
2038 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002039
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002040 if (Result.isNegative())
2041 Result.changeSign();
2042 return true;
2043
Mike Stump11289f42009-09-09 15:08:12 +00002044 case Builtin::BI__builtin_copysign:
2045 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002046 case Builtin::BI__builtin_copysignl: {
2047 APFloat RHS(0.);
2048 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2049 !EvaluateFloat(E->getArg(1), RHS, Info))
2050 return false;
2051 Result.copySign(RHS);
2052 return true;
2053 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002054 }
2055}
2056
John McCalla2fabff2010-10-09 01:34:31 +00002057bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002058 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2059 return true;
2060
John McCalla2fabff2010-10-09 01:34:31 +00002061 const Decl *D = E->getDecl();
2062 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2063 const VarDecl *VD = cast<VarDecl>(D);
2064
2065 // Require the qualifiers to be const and not volatile.
2066 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2067 if (!T.isConstQualified() || T.isVolatileQualified())
2068 return false;
2069
2070 const Expr *Init = VD->getAnyInitializer();
2071 if (!Init) return false;
2072
2073 if (APValue *V = VD->getEvaluatedValue()) {
2074 if (V->isFloat()) {
2075 Result = V->getFloat();
2076 return true;
2077 }
2078 return false;
2079 }
2080
2081 if (VD->isEvaluatingValue())
2082 return false;
2083
2084 VD->setEvaluatingValue();
2085
2086 Expr::EvalResult InitResult;
2087 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2088 InitResult.Val.isFloat()) {
2089 // Cache the evaluated value in the variable declaration.
2090 Result = InitResult.Val.getFloat();
2091 VD->setEvaluatedValue(InitResult.Val);
2092 return true;
2093 }
2094
2095 VD->setEvaluatedValue(APValue());
2096 return false;
2097}
2098
John McCallb1fb0d32010-05-07 22:08:54 +00002099bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002100 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2101 ComplexValue CV;
2102 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2103 return false;
2104 Result = CV.FloatReal;
2105 return true;
2106 }
2107
2108 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002109}
2110
2111bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002112 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2113 ComplexValue CV;
2114 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2115 return false;
2116 Result = CV.FloatImag;
2117 return true;
2118 }
2119
2120 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2121 Info.EvalResult.HasSideEffects = true;
2122 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2123 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002124 return true;
2125}
2126
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002127bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002128 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002129 return false;
2130
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002131 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2132 return false;
2133
2134 switch (E->getOpcode()) {
2135 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002136 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002137 return true;
John McCalle3027922010-08-25 11:45:40 +00002138 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002139 Result.changeSign();
2140 return true;
2141 }
2142}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002143
Eli Friedman24c01542008-08-22 00:06:13 +00002144bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002145 if (E->getOpcode() == BO_Comma) {
Eli Friedman141fbf32009-11-16 04:25:37 +00002146 if (!EvaluateFloat(E->getRHS(), Result, Info))
2147 return false;
2148
2149 // If we can't evaluate the LHS, it might have side effects;
2150 // conservatively mark it.
2151 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2152 Info.EvalResult.HasSideEffects = true;
2153
2154 return true;
2155 }
2156
Anders Carlssona5df61a2010-10-31 01:21:47 +00002157 // We can't evaluate pointer-to-member operations.
2158 if (E->isPtrMemOp())
2159 return false;
2160
Eli Friedman24c01542008-08-22 00:06:13 +00002161 // FIXME: Diagnostics? I really don't understand how the warnings
2162 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002163 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002164 if (!EvaluateFloat(E->getLHS(), Result, Info))
2165 return false;
2166 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2167 return false;
2168
2169 switch (E->getOpcode()) {
2170 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002171 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002172 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2173 return true;
John McCalle3027922010-08-25 11:45:40 +00002174 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002175 Result.add(RHS, APFloat::rmNearestTiesToEven);
2176 return true;
John McCalle3027922010-08-25 11:45:40 +00002177 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002178 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2179 return true;
John McCalle3027922010-08-25 11:45:40 +00002180 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002181 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2182 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002183 }
2184}
2185
2186bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2187 Result = E->getValue();
2188 return true;
2189}
2190
Peter Collingbournee9200682011-05-13 03:29:01 +00002191bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2192 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002193
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002194 switch (E->getCastKind()) {
2195 default:
2196 return false;
2197
2198 case CK_LValueToRValue:
2199 case CK_NoOp:
2200 return Visit(SubExpr);
2201
2202 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002203 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002204 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002205 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002206 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002207 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002208 return true;
2209 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002210
2211 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002212 if (!Visit(SubExpr))
2213 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002214 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2215 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002216 return true;
2217 }
John McCalld7646252010-11-14 08:17:51 +00002218
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002219 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002220 ComplexValue V;
2221 if (!EvaluateComplex(SubExpr, V, Info))
2222 return false;
2223 Result = V.getComplexFloatReal();
2224 return true;
2225 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002226 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002227
2228 return false;
2229}
2230
Peter Collingbournee9200682011-05-13 03:29:01 +00002231bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +00002232 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2233 return true;
2234}
2235
Eli Friedman24c01542008-08-22 00:06:13 +00002236//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002237// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002238//===----------------------------------------------------------------------===//
2239
2240namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002241class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002242 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002243 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002244
Anders Carlsson537969c2008-11-16 20:27:53 +00002245public:
John McCall93d91dc2010-05-07 17:22:02 +00002246 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002247 : ExprEvaluatorBaseTy(info), Result(Result) {}
2248
2249 bool Success(const APValue &V, const Expr *e) {
2250 Result.setFrom(V);
2251 return true;
2252 }
2253 bool Error(const Expr *E) {
2254 return false;
2255 }
Mike Stump11289f42009-09-09 15:08:12 +00002256
Anders Carlsson537969c2008-11-16 20:27:53 +00002257 //===--------------------------------------------------------------------===//
2258 // Visitor Methods
2259 //===--------------------------------------------------------------------===//
2260
Peter Collingbournee9200682011-05-13 03:29:01 +00002261 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002262
Peter Collingbournee9200682011-05-13 03:29:01 +00002263 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002264
John McCall93d91dc2010-05-07 17:22:02 +00002265 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002266 bool VisitUnaryOperator(const UnaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002267 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002268};
2269} // end anonymous namespace
2270
John McCall93d91dc2010-05-07 17:22:02 +00002271static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2272 EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002273 assert(E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002274 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002275}
2276
Peter Collingbournee9200682011-05-13 03:29:01 +00002277bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2278 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002279
2280 if (SubExpr->getType()->isRealFloatingType()) {
2281 Result.makeComplexFloat();
2282 APFloat &Imag = Result.FloatImag;
2283 if (!EvaluateFloat(SubExpr, Imag, Info))
2284 return false;
2285
2286 Result.FloatReal = APFloat(Imag.getSemantics());
2287 return true;
2288 } else {
2289 assert(SubExpr->getType()->isIntegerType() &&
2290 "Unexpected imaginary literal.");
2291
2292 Result.makeComplexInt();
2293 APSInt &Imag = Result.IntImag;
2294 if (!EvaluateInteger(SubExpr, Imag, Info))
2295 return false;
2296
2297 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2298 return true;
2299 }
2300}
2301
Peter Collingbournee9200682011-05-13 03:29:01 +00002302bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002303
John McCallfcef3cf2010-12-14 17:51:41 +00002304 switch (E->getCastKind()) {
2305 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002306 case CK_BaseToDerived:
2307 case CK_DerivedToBase:
2308 case CK_UncheckedDerivedToBase:
2309 case CK_Dynamic:
2310 case CK_ToUnion:
2311 case CK_ArrayToPointerDecay:
2312 case CK_FunctionToPointerDecay:
2313 case CK_NullToPointer:
2314 case CK_NullToMemberPointer:
2315 case CK_BaseToDerivedMemberPointer:
2316 case CK_DerivedToBaseMemberPointer:
2317 case CK_MemberPointerToBoolean:
2318 case CK_ConstructorConversion:
2319 case CK_IntegralToPointer:
2320 case CK_PointerToIntegral:
2321 case CK_PointerToBoolean:
2322 case CK_ToVoid:
2323 case CK_VectorSplat:
2324 case CK_IntegralCast:
2325 case CK_IntegralToBoolean:
2326 case CK_IntegralToFloating:
2327 case CK_FloatingToIntegral:
2328 case CK_FloatingToBoolean:
2329 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002330 case CK_CPointerToObjCPointerCast:
2331 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002332 case CK_AnyPointerToBlockPointerCast:
2333 case CK_ObjCObjectLValueCast:
2334 case CK_FloatingComplexToReal:
2335 case CK_FloatingComplexToBoolean:
2336 case CK_IntegralComplexToReal:
2337 case CK_IntegralComplexToBoolean:
John McCall31168b02011-06-15 23:02:42 +00002338 case CK_ObjCProduceObject:
2339 case CK_ObjCConsumeObject:
John McCall4db5c3c2011-07-07 06:58:02 +00002340 case CK_ObjCReclaimReturnedObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002341 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002342
John McCallfcef3cf2010-12-14 17:51:41 +00002343 case CK_LValueToRValue:
2344 case CK_NoOp:
2345 return Visit(E->getSubExpr());
2346
2347 case CK_Dependent:
2348 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002349 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002350 case CK_UserDefinedConversion:
2351 return false;
2352
2353 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002354 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002355 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002356 return false;
2357
John McCallfcef3cf2010-12-14 17:51:41 +00002358 Result.makeComplexFloat();
2359 Result.FloatImag = APFloat(Real.getSemantics());
2360 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002361 }
2362
John McCallfcef3cf2010-12-14 17:51:41 +00002363 case CK_FloatingComplexCast: {
2364 if (!Visit(E->getSubExpr()))
2365 return false;
2366
2367 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2368 QualType From
2369 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2370
2371 Result.FloatReal
2372 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2373 Result.FloatImag
2374 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2375 return true;
2376 }
2377
2378 case CK_FloatingComplexToIntegralComplex: {
2379 if (!Visit(E->getSubExpr()))
2380 return false;
2381
2382 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2383 QualType From
2384 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2385 Result.makeComplexInt();
2386 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2387 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2388 return true;
2389 }
2390
2391 case CK_IntegralRealToComplex: {
2392 APSInt &Real = Result.IntReal;
2393 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2394 return false;
2395
2396 Result.makeComplexInt();
2397 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2398 return true;
2399 }
2400
2401 case CK_IntegralComplexCast: {
2402 if (!Visit(E->getSubExpr()))
2403 return false;
2404
2405 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2406 QualType From
2407 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2408
2409 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2410 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2411 return true;
2412 }
2413
2414 case CK_IntegralComplexToFloatingComplex: {
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.makeComplexFloat();
2422 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2423 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2424 return true;
2425 }
2426 }
2427
2428 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002429 return false;
2430}
2431
John McCall93d91dc2010-05-07 17:22:02 +00002432bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002433 if (E->getOpcode() == BO_Comma) {
2434 if (!Visit(E->getRHS()))
2435 return false;
2436
2437 // If we can't evaluate the LHS, it might have side effects;
2438 // conservatively mark it.
2439 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2440 Info.EvalResult.HasSideEffects = true;
2441
2442 return true;
2443 }
John McCall93d91dc2010-05-07 17:22:02 +00002444 if (!Visit(E->getLHS()))
2445 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002446
John McCall93d91dc2010-05-07 17:22:02 +00002447 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002448 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002449 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002450
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002451 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2452 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002453 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002454 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002455 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002456 if (Result.isComplexFloat()) {
2457 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2458 APFloat::rmNearestTiesToEven);
2459 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2460 APFloat::rmNearestTiesToEven);
2461 } else {
2462 Result.getComplexIntReal() += RHS.getComplexIntReal();
2463 Result.getComplexIntImag() += RHS.getComplexIntImag();
2464 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002465 break;
John McCalle3027922010-08-25 11:45:40 +00002466 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002467 if (Result.isComplexFloat()) {
2468 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2469 APFloat::rmNearestTiesToEven);
2470 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2471 APFloat::rmNearestTiesToEven);
2472 } else {
2473 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2474 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2475 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002476 break;
John McCalle3027922010-08-25 11:45:40 +00002477 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002478 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002479 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002480 APFloat &LHS_r = LHS.getComplexFloatReal();
2481 APFloat &LHS_i = LHS.getComplexFloatImag();
2482 APFloat &RHS_r = RHS.getComplexFloatReal();
2483 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002484
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002485 APFloat Tmp = LHS_r;
2486 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2487 Result.getComplexFloatReal() = Tmp;
2488 Tmp = LHS_i;
2489 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2490 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2491
2492 Tmp = LHS_r;
2493 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2494 Result.getComplexFloatImag() = Tmp;
2495 Tmp = LHS_i;
2496 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2497 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2498 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002499 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002500 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002501 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2502 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002503 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002504 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2505 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2506 }
2507 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002508 case BO_Div:
2509 if (Result.isComplexFloat()) {
2510 ComplexValue LHS = Result;
2511 APFloat &LHS_r = LHS.getComplexFloatReal();
2512 APFloat &LHS_i = LHS.getComplexFloatImag();
2513 APFloat &RHS_r = RHS.getComplexFloatReal();
2514 APFloat &RHS_i = RHS.getComplexFloatImag();
2515 APFloat &Res_r = Result.getComplexFloatReal();
2516 APFloat &Res_i = Result.getComplexFloatImag();
2517
2518 APFloat Den = RHS_r;
2519 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2520 APFloat Tmp = RHS_i;
2521 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2522 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2523
2524 Res_r = LHS_r;
2525 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2526 Tmp = LHS_i;
2527 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2528 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2529 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2530
2531 Res_i = LHS_i;
2532 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2533 Tmp = LHS_r;
2534 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2535 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2536 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2537 } else {
2538 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2539 // FIXME: what about diagnostics?
2540 return false;
2541 }
2542 ComplexValue LHS = Result;
2543 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2544 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2545 Result.getComplexIntReal() =
2546 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2547 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2548 Result.getComplexIntImag() =
2549 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2550 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2551 }
2552 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002553 }
2554
John McCall93d91dc2010-05-07 17:22:02 +00002555 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002556}
2557
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002558bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2559 // Get the operand value into 'Result'.
2560 if (!Visit(E->getSubExpr()))
2561 return false;
2562
2563 switch (E->getOpcode()) {
2564 default:
2565 // FIXME: what about diagnostics?
2566 return false;
2567 case UO_Extension:
2568 return true;
2569 case UO_Plus:
2570 // The result is always just the subexpr.
2571 return true;
2572 case UO_Minus:
2573 if (Result.isComplexFloat()) {
2574 Result.getComplexFloatReal().changeSign();
2575 Result.getComplexFloatImag().changeSign();
2576 }
2577 else {
2578 Result.getComplexIntReal() = -Result.getComplexIntReal();
2579 Result.getComplexIntImag() = -Result.getComplexIntImag();
2580 }
2581 return true;
2582 case UO_Not:
2583 if (Result.isComplexFloat())
2584 Result.getComplexFloatImag().changeSign();
2585 else
2586 Result.getComplexIntImag() = -Result.getComplexIntImag();
2587 return true;
2588 }
2589}
2590
Anders Carlsson537969c2008-11-16 20:27:53 +00002591//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002592// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002593//===----------------------------------------------------------------------===//
2594
John McCallc07a0c72011-02-17 10:25:35 +00002595static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00002596 if (E->getType()->isVectorType()) {
2597 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002598 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002599 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002600 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002601 return false;
John McCallc07a0c72011-02-17 10:25:35 +00002602 if (Info.EvalResult.Val.isLValue() &&
2603 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall11086fc2010-07-07 05:08:32 +00002604 return false;
John McCall45d55e42010-05-07 21:00:08 +00002605 } else if (E->getType()->hasPointerRepresentation()) {
2606 LValue LV;
2607 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002608 return false;
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002609 if (!IsGlobalLValue(LV.Base))
John McCall95007602010-05-10 23:27:23 +00002610 return false;
John McCall45d55e42010-05-07 21:00:08 +00002611 LV.moveInto(Info.EvalResult.Val);
2612 } else if (E->getType()->isRealFloatingType()) {
2613 llvm::APFloat F(0.0);
2614 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002615 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002616
John McCall45d55e42010-05-07 21:00:08 +00002617 Info.EvalResult.Val = APValue(F);
2618 } else if (E->getType()->isAnyComplexType()) {
2619 ComplexValue C;
2620 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002621 return false;
John McCall45d55e42010-05-07 21:00:08 +00002622 C.moveInto(Info.EvalResult.Val);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002623 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002624 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002625
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002626 return true;
2627}
2628
John McCallc07a0c72011-02-17 10:25:35 +00002629/// Evaluate - Return true if this is a constant which we can fold using
2630/// any crazy technique (that has nothing to do with language standards) that
2631/// we want to. If this function returns true, it returns the folded constant
2632/// in Result.
2633bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2634 EvalInfo Info(Ctx, Result);
2635 return ::Evaluate(Info, this);
2636}
2637
Jay Foad39c79802011-01-12 09:06:06 +00002638bool Expr::EvaluateAsBooleanCondition(bool &Result,
2639 const ASTContext &Ctx) const {
John McCall1be1c632010-01-05 23:42:56 +00002640 EvalResult Scratch;
2641 EvalInfo Info(Ctx, Scratch);
2642
2643 return HandleConversionToBool(this, Result, Info);
2644}
2645
Jay Foad39c79802011-01-12 09:06:06 +00002646bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002647 EvalInfo Info(Ctx, Result);
2648
John McCall45d55e42010-05-07 21:00:08 +00002649 LValue LV;
John McCall95007602010-05-10 23:27:23 +00002650 if (EvaluateLValue(this, LV, Info) &&
2651 !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002652 IsGlobalLValue(LV.Base)) {
2653 LV.moveInto(Result.Val);
2654 return true;
2655 }
2656 return false;
2657}
2658
Jay Foad39c79802011-01-12 09:06:06 +00002659bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2660 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002661 EvalInfo Info(Ctx, Result);
2662
2663 LValue LV;
2664 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00002665 LV.moveInto(Result.Val);
2666 return true;
2667 }
2668 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00002669}
2670
Chris Lattner67d7b922008-11-16 21:24:15 +00002671/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002672/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00002673bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002674 EvalResult Result;
2675 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002676}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002677
Jay Foad39c79802011-01-12 09:06:06 +00002678bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002679 Expr::EvalResult Result;
2680 EvalInfo Info(Ctx, Result);
Peter Collingbournee9200682011-05-13 03:29:01 +00002681 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002682}
2683
Jay Foad39c79802011-01-12 09:06:06 +00002684APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002685 EvalResult EvalResult;
2686 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002687 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002688 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002689 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002690
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002691 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002692}
John McCall864e3962010-05-07 05:32:02 +00002693
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002694 bool Expr::EvalResult::isGlobalLValue() const {
2695 assert(Val.isLValue());
2696 return IsGlobalLValue(Val.getLValueBase());
2697 }
2698
2699
John McCall864e3962010-05-07 05:32:02 +00002700/// isIntegerConstantExpr - this recursive routine will test if an expression is
2701/// an integer constant expression.
2702
2703/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2704/// comma, etc
2705///
2706/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2707/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2708/// cast+dereference.
2709
2710// CheckICE - This function does the fundamental ICE checking: the returned
2711// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2712// Note that to reduce code duplication, this helper does no evaluation
2713// itself; the caller checks whether the expression is evaluatable, and
2714// in the rare cases where CheckICE actually cares about the evaluated
2715// value, it calls into Evalute.
2716//
2717// Meanings of Val:
2718// 0: This expression is an ICE if it can be evaluated by Evaluate.
2719// 1: This expression is not an ICE, but if it isn't evaluated, it's
2720// a legal subexpression for an ICE. This return value is used to handle
2721// the comma operator in C99 mode.
2722// 2: This expression is not an ICE, and is not a legal subexpression for one.
2723
Dan Gohman28ade552010-07-26 21:25:24 +00002724namespace {
2725
John McCall864e3962010-05-07 05:32:02 +00002726struct ICEDiag {
2727 unsigned Val;
2728 SourceLocation Loc;
2729
2730 public:
2731 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2732 ICEDiag() : Val(0) {}
2733};
2734
Dan Gohman28ade552010-07-26 21:25:24 +00002735}
2736
2737static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00002738
2739static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2740 Expr::EvalResult EVResult;
2741 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2742 !EVResult.Val.isInt()) {
2743 return ICEDiag(2, E->getLocStart());
2744 }
2745 return NoDiag();
2746}
2747
2748static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2749 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00002750 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00002751 return ICEDiag(2, E->getLocStart());
2752 }
2753
2754 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00002755#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00002756#define STMT(Node, Base) case Expr::Node##Class:
2757#define EXPR(Node, Base)
2758#include "clang/AST/StmtNodes.inc"
2759 case Expr::PredefinedExprClass:
2760 case Expr::FloatingLiteralClass:
2761 case Expr::ImaginaryLiteralClass:
2762 case Expr::StringLiteralClass:
2763 case Expr::ArraySubscriptExprClass:
2764 case Expr::MemberExprClass:
2765 case Expr::CompoundAssignOperatorClass:
2766 case Expr::CompoundLiteralExprClass:
2767 case Expr::ExtVectorElementExprClass:
2768 case Expr::InitListExprClass:
2769 case Expr::DesignatedInitExprClass:
2770 case Expr::ImplicitValueInitExprClass:
2771 case Expr::ParenListExprClass:
2772 case Expr::VAArgExprClass:
2773 case Expr::AddrLabelExprClass:
2774 case Expr::StmtExprClass:
2775 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00002776 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00002777 case Expr::CXXDynamicCastExprClass:
2778 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00002779 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00002780 case Expr::CXXNullPtrLiteralExprClass:
2781 case Expr::CXXThisExprClass:
2782 case Expr::CXXThrowExprClass:
2783 case Expr::CXXNewExprClass:
2784 case Expr::CXXDeleteExprClass:
2785 case Expr::CXXPseudoDestructorExprClass:
2786 case Expr::UnresolvedLookupExprClass:
2787 case Expr::DependentScopeDeclRefExprClass:
2788 case Expr::CXXConstructExprClass:
2789 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00002790 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00002791 case Expr::CXXTemporaryObjectExprClass:
2792 case Expr::CXXUnresolvedConstructExprClass:
2793 case Expr::CXXDependentScopeMemberExprClass:
2794 case Expr::UnresolvedMemberExprClass:
2795 case Expr::ObjCStringLiteralClass:
2796 case Expr::ObjCEncodeExprClass:
2797 case Expr::ObjCMessageExprClass:
2798 case Expr::ObjCSelectorExprClass:
2799 case Expr::ObjCProtocolExprClass:
2800 case Expr::ObjCIvarRefExprClass:
2801 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00002802 case Expr::ObjCIsaExprClass:
2803 case Expr::ShuffleVectorExprClass:
2804 case Expr::BlockExprClass:
2805 case Expr::BlockDeclRefExprClass:
2806 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00002807 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00002808 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00002809 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00002810 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00002811 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00002812 case Expr::MaterializeTemporaryExprClass:
John McCall864e3962010-05-07 05:32:02 +00002813 return ICEDiag(2, E->getLocStart());
2814
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002815 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00002816 case Expr::GNUNullExprClass:
2817 // GCC considers the GNU __null value to be an integral constant expression.
2818 return NoDiag();
2819
John McCall7c454bb2011-07-15 05:09:51 +00002820 case Expr::SubstNonTypeTemplateParmExprClass:
2821 return
2822 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2823
John McCall864e3962010-05-07 05:32:02 +00002824 case Expr::ParenExprClass:
2825 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002826 case Expr::GenericSelectionExprClass:
2827 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002828 case Expr::IntegerLiteralClass:
2829 case Expr::CharacterLiteralClass:
2830 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00002831 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00002832 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002833 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00002834 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00002835 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00002836 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00002837 return NoDiag();
2838 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00002839 case Expr::CXXOperatorCallExprClass: {
John McCall864e3962010-05-07 05:32:02 +00002840 const CallExpr *CE = cast<CallExpr>(E);
2841 if (CE->isBuiltinCall(Ctx))
2842 return CheckEvalInICE(E, Ctx);
2843 return ICEDiag(2, E->getLocStart());
2844 }
2845 case Expr::DeclRefExprClass:
2846 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2847 return NoDiag();
2848 if (Ctx.getLangOptions().CPlusPlus &&
2849 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2850 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2851
2852 // Parameter variables are never constants. Without this check,
2853 // getAnyInitializer() can find a default argument, which leads
2854 // to chaos.
2855 if (isa<ParmVarDecl>(D))
2856 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2857
2858 // C++ 7.1.5.1p2
2859 // A variable of non-volatile const-qualified integral or enumeration
2860 // type initialized by an ICE can be used in ICEs.
2861 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2862 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2863 if (Quals.hasVolatile() || !Quals.hasConst())
2864 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2865
2866 // Look for a declaration of this variable that has an initializer.
2867 const VarDecl *ID = 0;
2868 const Expr *Init = Dcl->getAnyInitializer(ID);
2869 if (Init) {
2870 if (ID->isInitKnownICE()) {
2871 // We have already checked whether this subexpression is an
2872 // integral constant expression.
2873 if (ID->isInitICE())
2874 return NoDiag();
2875 else
2876 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2877 }
2878
2879 // It's an ICE whether or not the definition we found is
2880 // out-of-line. See DR 721 and the discussion in Clang PR
2881 // 6206 for details.
2882
2883 if (Dcl->isCheckingICE()) {
2884 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2885 }
2886
2887 Dcl->setCheckingICE();
2888 ICEDiag Result = CheckICE(Init, Ctx);
2889 // Cache the result of the ICE test.
2890 Dcl->setInitKnownICE(Result.Val == 0);
2891 return Result;
2892 }
2893 }
2894 }
2895 return ICEDiag(2, E->getLocStart());
2896 case Expr::UnaryOperatorClass: {
2897 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2898 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002899 case UO_PostInc:
2900 case UO_PostDec:
2901 case UO_PreInc:
2902 case UO_PreDec:
2903 case UO_AddrOf:
2904 case UO_Deref:
John McCall864e3962010-05-07 05:32:02 +00002905 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00002906 case UO_Extension:
2907 case UO_LNot:
2908 case UO_Plus:
2909 case UO_Minus:
2910 case UO_Not:
2911 case UO_Real:
2912 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00002913 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002914 }
2915
2916 // OffsetOf falls through here.
2917 }
2918 case Expr::OffsetOfExprClass: {
2919 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2920 // Evaluate matches the proposed gcc behavior for cases like
2921 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2922 // compliance: we should warn earlier for offsetof expressions with
2923 // array subscripts that aren't ICEs, and if the array subscripts
2924 // are ICEs, the value of the offsetof must be an integer constant.
2925 return CheckEvalInICE(E, Ctx);
2926 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002927 case Expr::UnaryExprOrTypeTraitExprClass: {
2928 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2929 if ((Exp->getKind() == UETT_SizeOf) &&
2930 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00002931 return ICEDiag(2, E->getLocStart());
2932 return NoDiag();
2933 }
2934 case Expr::BinaryOperatorClass: {
2935 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2936 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002937 case BO_PtrMemD:
2938 case BO_PtrMemI:
2939 case BO_Assign:
2940 case BO_MulAssign:
2941 case BO_DivAssign:
2942 case BO_RemAssign:
2943 case BO_AddAssign:
2944 case BO_SubAssign:
2945 case BO_ShlAssign:
2946 case BO_ShrAssign:
2947 case BO_AndAssign:
2948 case BO_XorAssign:
2949 case BO_OrAssign:
John McCall864e3962010-05-07 05:32:02 +00002950 return ICEDiag(2, E->getLocStart());
2951
John McCalle3027922010-08-25 11:45:40 +00002952 case BO_Mul:
2953 case BO_Div:
2954 case BO_Rem:
2955 case BO_Add:
2956 case BO_Sub:
2957 case BO_Shl:
2958 case BO_Shr:
2959 case BO_LT:
2960 case BO_GT:
2961 case BO_LE:
2962 case BO_GE:
2963 case BO_EQ:
2964 case BO_NE:
2965 case BO_And:
2966 case BO_Xor:
2967 case BO_Or:
2968 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00002969 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2970 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00002971 if (Exp->getOpcode() == BO_Div ||
2972 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00002973 // Evaluate gives an error for undefined Div/Rem, so make sure
2974 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00002975 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCall864e3962010-05-07 05:32:02 +00002976 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2977 if (REval == 0)
2978 return ICEDiag(1, E->getLocStart());
2979 if (REval.isSigned() && REval.isAllOnesValue()) {
2980 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2981 if (LEval.isMinSignedValue())
2982 return ICEDiag(1, E->getLocStart());
2983 }
2984 }
2985 }
John McCalle3027922010-08-25 11:45:40 +00002986 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00002987 if (Ctx.getLangOptions().C99) {
2988 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2989 // if it isn't evaluated.
2990 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2991 return ICEDiag(1, E->getLocStart());
2992 } else {
2993 // In both C89 and C++, commas in ICEs are illegal.
2994 return ICEDiag(2, E->getLocStart());
2995 }
2996 }
2997 if (LHSResult.Val >= RHSResult.Val)
2998 return LHSResult;
2999 return RHSResult;
3000 }
John McCalle3027922010-08-25 11:45:40 +00003001 case BO_LAnd:
3002 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003003 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003004
3005 // C++0x [expr.const]p2:
3006 // [...] subexpressions of logical AND (5.14), logical OR
3007 // (5.15), and condi- tional (5.16) operations that are not
3008 // evaluated are not considered.
3009 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3010 if (Exp->getOpcode() == BO_LAnd &&
3011 Exp->getLHS()->EvaluateAsInt(Ctx) == 0)
3012 return LHSResult;
3013
3014 if (Exp->getOpcode() == BO_LOr &&
3015 Exp->getLHS()->EvaluateAsInt(Ctx) != 0)
3016 return LHSResult;
3017 }
3018
John McCall864e3962010-05-07 05:32:02 +00003019 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3020 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3021 // Rare case where the RHS has a comma "side-effect"; we need
3022 // to actually check the condition to see whether the side
3023 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003024 if ((Exp->getOpcode() == BO_LAnd) !=
John McCall864e3962010-05-07 05:32:02 +00003025 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3026 return RHSResult;
3027 return NoDiag();
3028 }
3029
3030 if (LHSResult.Val >= RHSResult.Val)
3031 return LHSResult;
3032 return RHSResult;
3033 }
3034 }
3035 }
3036 case Expr::ImplicitCastExprClass:
3037 case Expr::CStyleCastExprClass:
3038 case Expr::CXXFunctionalCastExprClass:
3039 case Expr::CXXStaticCastExprClass:
3040 case Expr::CXXReinterpretCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003041 case Expr::CXXConstCastExprClass:
3042 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003043 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregorb90df602010-06-16 00:17:44 +00003044 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCall864e3962010-05-07 05:32:02 +00003045 return CheckICE(SubExpr, Ctx);
3046 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3047 return NoDiag();
3048 return ICEDiag(2, E->getLocStart());
3049 }
John McCallc07a0c72011-02-17 10:25:35 +00003050 case Expr::BinaryConditionalOperatorClass: {
3051 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3052 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3053 if (CommonResult.Val == 2) return CommonResult;
3054 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3055 if (FalseResult.Val == 2) return FalseResult;
3056 if (CommonResult.Val == 1) return CommonResult;
3057 if (FalseResult.Val == 1 &&
3058 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3059 return FalseResult;
3060 }
John McCall864e3962010-05-07 05:32:02 +00003061 case Expr::ConditionalOperatorClass: {
3062 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3063 // If the condition (ignoring parens) is a __builtin_constant_p call,
3064 // then only the true side is actually considered in an integer constant
3065 // expression, and it is fully evaluated. This is an important GNU
3066 // extension. See GCC PR38377 for discussion.
3067 if (const CallExpr *CallCE
3068 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3069 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3070 Expr::EvalResult EVResult;
3071 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3072 !EVResult.Val.isInt()) {
3073 return ICEDiag(2, E->getLocStart());
3074 }
3075 return NoDiag();
3076 }
3077 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003078 if (CondResult.Val == 2)
3079 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003080
3081 // C++0x [expr.const]p2:
3082 // subexpressions of [...] conditional (5.16) operations that
3083 // are not evaluated are not considered
3084 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
3085 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0
3086 : false;
3087 ICEDiag TrueResult = NoDiag();
3088 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3089 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3090 ICEDiag FalseResult = NoDiag();
3091 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3092 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3093
John McCall864e3962010-05-07 05:32:02 +00003094 if (TrueResult.Val == 2)
3095 return TrueResult;
3096 if (FalseResult.Val == 2)
3097 return FalseResult;
3098 if (CondResult.Val == 1)
3099 return CondResult;
3100 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3101 return NoDiag();
3102 // Rare case where the diagnostics depend on which side is evaluated
3103 // Note that if we get here, CondResult is 0, and at least one of
3104 // TrueResult and FalseResult is non-zero.
3105 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3106 return FalseResult;
3107 }
3108 return TrueResult;
3109 }
3110 case Expr::CXXDefaultArgExprClass:
3111 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3112 case Expr::ChooseExprClass: {
3113 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3114 }
3115 }
3116
3117 // Silence a GCC warning
3118 return ICEDiag(2, E->getLocStart());
3119}
3120
3121bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3122 SourceLocation *Loc, bool isEvaluated) const {
3123 ICEDiag d = CheckICE(this, Ctx);
3124 if (d.Val != 0) {
3125 if (Loc) *Loc = d.Loc;
3126 return false;
3127 }
3128 EvalResult EvalResult;
3129 if (!Evaluate(EvalResult, Ctx))
3130 llvm_unreachable("ICE cannot be evaluated!");
3131 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3132 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3133 Result = EvalResult.Val.getInt();
3134 return true;
3135}