blob: 85cb40f9e08478dec0937d10586adc41e24c7dd1 [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 *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000391 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000392 }
393 RetTy VisitExpr(const Expr *E) {
394 return DerivedError(E);
395 }
396
397 RetTy VisitParenExpr(const ParenExpr *E)
398 { return StmtVisitorTy::Visit(E->getSubExpr()); }
399 RetTy VisitUnaryExtension(const UnaryOperator *E)
400 { return StmtVisitorTy::Visit(E->getSubExpr()); }
401 RetTy VisitUnaryPlus(const UnaryOperator *E)
402 { return StmtVisitorTy::Visit(E->getSubExpr()); }
403 RetTy VisitChooseExpr(const ChooseExpr *E)
404 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
405 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
406 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000407 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
408 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000409
410 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
411 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
412 if (opaque.hasError())
413 return DerivedError(E);
414
415 bool cond;
416 if (!HandleConversionToBool(E->getCond(), cond, Info))
417 return DerivedError(E);
418
419 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
420 }
421
422 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
423 bool BoolResult;
424 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
425 return DerivedError(E);
426
427 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
428 return StmtVisitorTy::Visit(EvalExpr);
429 }
430
431 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
432 const APValue *value = Info.getOpaqueValue(E);
433 if (!value)
434 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
435 : DerivedError(E));
436 return DerivedSuccess(*value, E);
437 }
438};
439
440}
441
442//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000443// LValue Evaluation
444//===----------------------------------------------------------------------===//
445namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000446class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000447 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000448 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000449 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000450
Peter Collingbournee9200682011-05-13 03:29:01 +0000451 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000452 Result.Base = E;
453 Result.Offset = CharUnits::Zero();
454 return true;
455 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000456public:
Mike Stump11289f42009-09-09 15:08:12 +0000457
John McCall45d55e42010-05-07 21:00:08 +0000458 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000459 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000460
Peter Collingbournee9200682011-05-13 03:29:01 +0000461 bool Success(const APValue &V, const Expr *E) {
462 Result.setFrom(V);
463 return true;
464 }
465 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000466 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000467 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000468
Peter Collingbournee9200682011-05-13 03:29:01 +0000469 bool VisitDeclRefExpr(const DeclRefExpr *E);
470 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
471 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
472 bool VisitMemberExpr(const MemberExpr *E);
473 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
474 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
475 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
476 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000477
Peter Collingbournee9200682011-05-13 03:29:01 +0000478 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000479 switch (E->getCastKind()) {
480 default:
John McCall45d55e42010-05-07 21:00:08 +0000481 return false;
Anders Carlssonde55f642009-10-03 16:30:22 +0000482
John McCalle3027922010-08-25 11:45:40 +0000483 case CK_NoOp:
Eli Friedmance3e02a2011-10-11 00:13:24 +0000484 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000485 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000486
487 // FIXME: Support CK_DerivedToBase and friends.
Anders Carlssonde55f642009-10-03 16:30:22 +0000488 }
489 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000490
491 bool VisitInitListExpr(const InitListExpr *E) {
492 if (Info.Ctx.getLangOptions().CPlusPlus0x && E->getNumInits() == 1)
493 return Visit(E->getInit(0));
494 return Error(E);
495 }
496
Eli Friedman449fe542009-03-23 04:56:01 +0000497 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000498
Eli Friedman9a156e52008-11-12 09:44:48 +0000499};
500} // end anonymous namespace
501
John McCall45d55e42010-05-07 21:00:08 +0000502static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000503 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000504}
505
Peter Collingbournee9200682011-05-13 03:29:01 +0000506bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000507 if (isa<FunctionDecl>(E->getDecl())) {
John McCall45d55e42010-05-07 21:00:08 +0000508 return Success(E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000509 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000510 if (!VD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000511 return Success(E);
Chandler Carruthe299ba62010-05-16 09:32:51 +0000512 // Reference parameters can refer to anything even if they have an
513 // "initializer" in the form of a default argument.
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000514 if (!isa<ParmVarDecl>(VD)) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000515 // FIXME: Check whether VD might be overridden!
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000516
517 // Check for recursive initializers of references.
518 if (PrevDecl == VD)
519 return Error(E);
520 PrevDecl = VD;
Peter Collingbournee9200682011-05-13 03:29:01 +0000521 if (const Expr *Init = VD->getAnyInitializer())
522 return Visit(Init);
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000523 }
Eli Friedman751aa72b72009-05-27 06:04:58 +0000524 }
525
Peter Collingbournee9200682011-05-13 03:29:01 +0000526 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000527}
528
Peter Collingbournee9200682011-05-13 03:29:01 +0000529bool
530LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000531 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000532}
533
Peter Collingbournee9200682011-05-13 03:29:01 +0000534bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000535 QualType Ty;
536 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000537 if (!EvaluatePointer(E->getBase(), Result, Info))
538 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000539 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000540 } else {
John McCall45d55e42010-05-07 21:00:08 +0000541 if (!Visit(E->getBase()))
542 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000543 Ty = E->getBase()->getType();
544 }
545
Peter Collingbournee9200682011-05-13 03:29:01 +0000546 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000547 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000548
Peter Collingbournee9200682011-05-13 03:29:01 +0000549 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000550 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000551 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000552
553 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000554 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000555
Eli Friedmana3c122d2011-07-07 01:54:01 +0000556 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000557 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000558 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000559}
560
Peter Collingbournee9200682011-05-13 03:29:01 +0000561bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000562 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000563 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000564
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000565 APSInt Index;
566 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000567 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000568
Ken Dyck40775002010-01-11 17:06:35 +0000569 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000570 Result.Offset += Index.getSExtValue() * ElementSize;
571 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000572}
Eli Friedman9a156e52008-11-12 09:44:48 +0000573
Peter Collingbournee9200682011-05-13 03:29:01 +0000574bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +0000575 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000576}
577
Eli Friedman9a156e52008-11-12 09:44:48 +0000578//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000579// Pointer Evaluation
580//===----------------------------------------------------------------------===//
581
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000582namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000583class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000584 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000585 LValue &Result;
586
Peter Collingbournee9200682011-05-13 03:29:01 +0000587 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000588 Result.Base = E;
589 Result.Offset = CharUnits::Zero();
590 return true;
591 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000592public:
Mike Stump11289f42009-09-09 15:08:12 +0000593
John McCall45d55e42010-05-07 21:00:08 +0000594 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000595 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000596
Peter Collingbournee9200682011-05-13 03:29:01 +0000597 bool Success(const APValue &V, const Expr *E) {
598 Result.setFrom(V);
599 return true;
600 }
601 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +0000602 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000603 }
604
John McCall45d55e42010-05-07 21:00:08 +0000605 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000606 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +0000607 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000608 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +0000609 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000610 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000611 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000612 bool VisitCallExpr(const CallExpr *E);
613 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +0000614 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000615 return Success(E);
616 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000617 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000618 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000619 { return Success((Expr*)0); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000620 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000621 { return Success((Expr*)0); }
Peter Collingbournefec95192011-09-27 17:33:05 +0000622 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E)
623 { return Success((Expr*)0); }
John McCallc07a0c72011-02-17 10:25:35 +0000624
Eli Friedman449fe542009-03-23 04:56:01 +0000625 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000626};
Chris Lattner05706e882008-07-11 18:11:29 +0000627} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000628
John McCall45d55e42010-05-07 21:00:08 +0000629static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000630 assert(E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +0000631 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +0000632}
633
John McCall45d55e42010-05-07 21:00:08 +0000634bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000635 if (E->getOpcode() != BO_Add &&
636 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +0000637 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000638
Chris Lattner05706e882008-07-11 18:11:29 +0000639 const Expr *PExp = E->getLHS();
640 const Expr *IExp = E->getRHS();
641 if (IExp->getType()->isPointerType())
642 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000643
John McCall45d55e42010-05-07 21:00:08 +0000644 if (!EvaluatePointer(PExp, Result, Info))
645 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000646
John McCall45d55e42010-05-07 21:00:08 +0000647 llvm::APSInt Offset;
648 if (!EvaluateInteger(IExp, Offset, Info))
649 return false;
650 int64_t AdditionalOffset
651 = Offset.isSigned() ? Offset.getSExtValue()
652 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +0000653
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000654 // Compute the new offset in the appropriate width.
655
656 QualType PointeeType =
657 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +0000658 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +0000659
Anders Carlssonef56fba2009-02-19 04:55:58 +0000660 // Explicitly handle GNU void* and function pointer arithmetic extensions.
661 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +0000662 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +0000663 else
John McCall45d55e42010-05-07 21:00:08 +0000664 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +0000665
John McCalle3027922010-08-25 11:45:40 +0000666 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +0000667 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000668 else
John McCall45d55e42010-05-07 21:00:08 +0000669 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000670
John McCall45d55e42010-05-07 21:00:08 +0000671 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000672}
Eli Friedman9a156e52008-11-12 09:44:48 +0000673
John McCall45d55e42010-05-07 21:00:08 +0000674bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
675 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000676}
Mike Stump11289f42009-09-09 15:08:12 +0000677
Chris Lattner05706e882008-07-11 18:11:29 +0000678
Peter Collingbournee9200682011-05-13 03:29:01 +0000679bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
680 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000681
Eli Friedman847a2bc2009-12-27 05:43:15 +0000682 switch (E->getCastKind()) {
683 default:
684 break;
685
John McCalle3027922010-08-25 11:45:40 +0000686 case CK_NoOp:
687 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +0000688 case CK_CPointerToObjCPointerCast:
689 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +0000690 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +0000691 return Visit(SubExpr);
692
Anders Carlsson18275092010-10-31 20:41:46 +0000693 case CK_DerivedToBase:
694 case CK_UncheckedDerivedToBase: {
695 LValue BaseLV;
696 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
697 return false;
698
699 // Now figure out the necessary offset to add to the baseLV to get from
700 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +0000701 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +0000702
703 QualType Ty = E->getSubExpr()->getType();
704 const CXXRecordDecl *DerivedDecl =
705 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
706
707 for (CastExpr::path_const_iterator PathI = E->path_begin(),
708 PathE = E->path_end(); PathI != PathE; ++PathI) {
709 const CXXBaseSpecifier *Base = *PathI;
710
711 // FIXME: If the base is virtual, we'd need to determine the type of the
712 // most derived class and we don't support that right now.
713 if (Base->isVirtual())
714 return false;
715
716 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
717 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
718
Ken Dyck02155cb2011-01-26 02:17:08 +0000719 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +0000720 DerivedDecl = BaseDecl;
721 }
722
723 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +0000724 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +0000725 return true;
726 }
727
John McCalle84af4e2010-11-13 01:35:44 +0000728 case CK_NullToPointer: {
729 Result.Base = 0;
730 Result.Offset = CharUnits::Zero();
731 return true;
732 }
733
John McCalle3027922010-08-25 11:45:40 +0000734 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +0000735 APValue Value;
736 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000737 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000738
John McCall45d55e42010-05-07 21:00:08 +0000739 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000740 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-05-07 21:00:08 +0000741 Result.Base = 0;
742 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
743 return true;
744 } else {
745 // Cast is of an lvalue, no need to change value.
746 Result.Base = Value.getLValueBase();
747 Result.Offset = Value.getLValueOffset();
748 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000749 }
750 }
John McCalle3027922010-08-25 11:45:40 +0000751 case CK_ArrayToPointerDecay:
752 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +0000753 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000754 }
755
John McCall45d55e42010-05-07 21:00:08 +0000756 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000757}
Chris Lattner05706e882008-07-11 18:11:29 +0000758
Peter Collingbournee9200682011-05-13 03:29:01 +0000759bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000760 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000761 Builtin::BI__builtin___CFStringMakeConstantString ||
762 E->isBuiltinCall(Info.Ctx) ==
763 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +0000764 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000765
Peter Collingbournee9200682011-05-13 03:29:01 +0000766 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000767}
Chris Lattner05706e882008-07-11 18:11:29 +0000768
769//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000770// Vector Evaluation
771//===----------------------------------------------------------------------===//
772
773namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000774 class VectorExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000775 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman3ae59112009-02-23 04:23:56 +0000776 APValue GetZeroVector(QualType VecType);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000777 public:
Mike Stump11289f42009-09-09 15:08:12 +0000778
Peter Collingbournee9200682011-05-13 03:29:01 +0000779 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump11289f42009-09-09 15:08:12 +0000780
Peter Collingbournee9200682011-05-13 03:29:01 +0000781 APValue Success(const APValue &V, const Expr *E) { return V; }
782 APValue Error(const Expr *E) { return APValue(); }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Eli Friedman3ae59112009-02-23 04:23:56 +0000784 APValue VisitUnaryReal(const UnaryOperator *E)
785 { return Visit(E->getSubExpr()); }
786 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
787 { return GetZeroVector(E->getType()); }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000788 APValue VisitCastExpr(const CastExpr* E);
789 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
790 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000791 APValue VisitUnaryImag(const UnaryOperator *E);
792 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000793 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000794 // shufflevector, ExtVectorElementExpr
795 // (Note that these require implementing conversions
796 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000797 };
798} // end anonymous namespace
799
800static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
801 if (!E->getType()->isVectorType())
802 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +0000803 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000804 return !Result.isUninit();
805}
806
807APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall9dd450b2009-09-21 23:43:11 +0000808 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000809 QualType EltTy = VTy->getElementType();
810 unsigned NElts = VTy->getNumElements();
811 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000812
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000813 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000814 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000815
Eli Friedmanc757de22011-03-25 00:43:55 +0000816 switch (E->getCastKind()) {
817 case CK_VectorSplat: {
818 APValue Result = APValue();
819 if (SETy->isIntegerType()) {
820 APSInt IntResult;
821 if (!EvaluateInteger(SE, IntResult, Info))
822 return APValue();
823 Result = APValue(IntResult);
824 } else if (SETy->isRealFloatingType()) {
825 APFloat F(0.0);
826 if (!EvaluateFloat(SE, F, Info))
827 return APValue();
828 Result = APValue(F);
829 } else {
Anders Carlsson6fc22042011-03-25 11:22:47 +0000830 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000831 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000832
833 // Splat and create vector APValue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000834 SmallVector<APValue, 4> Elts(NElts, Result);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000835 return APValue(&Elts[0], Elts.size());
Nate Begeman2ffd3842009-06-26 18:22:18 +0000836 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000837 case CK_BitCast: {
838 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +0000839 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000840
Eli Friedmanc757de22011-03-25 00:43:55 +0000841 if (!SETy->isIntegerType())
Anders Carlsson6fc22042011-03-25 11:22:47 +0000842 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000843
Eli Friedmanc757de22011-03-25 00:43:55 +0000844 APSInt Init;
845 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000846 return APValue();
847
Eli Friedmanc757de22011-03-25 00:43:55 +0000848 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
849 "Vectors must be composed of ints or floats");
850
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000851 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +0000852 for (unsigned i = 0; i != NElts; ++i) {
853 APSInt Tmp = Init.extOrTrunc(EltWidth);
854
855 if (EltTy->isIntegerType())
856 Elts.push_back(APValue(Tmp));
857 else
858 Elts.push_back(APValue(APFloat(Tmp)));
859
860 Init >>= EltWidth;
861 }
862 return APValue(&Elts[0], Elts.size());
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000863 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000864 case CK_LValueToRValue:
865 case CK_NoOp:
Peter Collingbournee9200682011-05-13 03:29:01 +0000866 return Visit(SE);
Eli Friedmanc757de22011-03-25 00:43:55 +0000867 default:
Anders Carlsson6fc22042011-03-25 11:22:47 +0000868 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000869 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000870}
871
Mike Stump11289f42009-09-09 15:08:12 +0000872APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000873VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000874 return this->Visit(E->getInitializer());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000875}
876
Mike Stump11289f42009-09-09 15:08:12 +0000877APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000878VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall9dd450b2009-09-21 23:43:11 +0000879 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000880 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000881 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000882
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000883 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000884 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000885
John McCall875679e2010-06-11 17:54:15 +0000886 // If a vector is initialized with a single element, that value
887 // becomes every element of the vector, not just the first.
888 // This is the behavior described in the IBM AltiVec documentation.
889 if (NumInits == 1) {
Tanya Lattner5ac257d2011-04-15 22:42:59 +0000890
891 // Handle the case where the vector is initialized by a another
892 // vector (OpenCL 6.1.6).
893 if (E->getInit(0)->getType()->isVectorType())
894 return this->Visit(const_cast<Expr*>(E->getInit(0)));
895
John McCall875679e2010-06-11 17:54:15 +0000896 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000897 if (EltTy->isIntegerType()) {
898 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +0000899 if (!EvaluateInteger(E->getInit(0), sInt, Info))
900 return APValue();
901 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000902 } else {
903 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +0000904 if (!EvaluateFloat(E->getInit(0), f, Info))
905 return APValue();
906 InitValue = APValue(f);
907 }
908 for (unsigned i = 0; i < NumElements; i++) {
909 Elements.push_back(InitValue);
910 }
911 } else {
912 for (unsigned i = 0; i < NumElements; i++) {
913 if (EltTy->isIntegerType()) {
914 llvm::APSInt sInt(32);
915 if (i < NumInits) {
916 if (!EvaluateInteger(E->getInit(i), sInt, Info))
917 return APValue();
918 } else {
919 sInt = Info.Ctx.MakeIntValue(0, EltTy);
920 }
921 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +0000922 } else {
John McCall875679e2010-06-11 17:54:15 +0000923 llvm::APFloat f(0.0);
924 if (i < NumInits) {
925 if (!EvaluateFloat(E->getInit(i), f, Info))
926 return APValue();
927 } else {
928 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
929 }
930 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +0000931 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000932 }
933 }
934 return APValue(&Elements[0], Elements.size());
935}
936
Mike Stump11289f42009-09-09 15:08:12 +0000937APValue
Eli Friedman3ae59112009-02-23 04:23:56 +0000938VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +0000939 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +0000940 QualType EltTy = VT->getElementType();
941 APValue ZeroElement;
942 if (EltTy->isIntegerType())
943 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
944 else
945 ZeroElement =
946 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
947
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000948 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Eli Friedman3ae59112009-02-23 04:23:56 +0000949 return APValue(&Elements[0], Elements.size());
950}
951
Eli Friedman3ae59112009-02-23 04:23:56 +0000952APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
953 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
954 Info.EvalResult.HasSideEffects = true;
955 return GetZeroVector(E->getType());
956}
957
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000958//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000959// Integer Evaluation
960//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000961
962namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000963class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000964 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000965 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000966public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000967 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000968 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000969
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000970 bool Success(const llvm::APSInt &SI, const Expr *E) {
971 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +0000972 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000973 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000974 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000975 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000976 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000977 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000978 return true;
979 }
980
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000981 bool Success(const llvm::APInt &I, 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 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000985 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000986 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000987 Result.getInt().setIsUnsigned(
988 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000989 return true;
990 }
991
992 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000993 assert(E->getType()->isIntegralOrEnumerationType() &&
994 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000995 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000996 return true;
997 }
998
Ken Dyckdbc01912011-03-11 02:13:43 +0000999 bool Success(CharUnits Size, const Expr *E) {
1000 return Success(Size.getQuantity(), E);
1001 }
1002
1003
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001004 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001005 // Take the first error.
Anders Carlssonbd1df8e2008-11-30 16:38:33 +00001006 if (Info.EvalResult.Diag == 0) {
1007 Info.EvalResult.DiagLoc = L;
1008 Info.EvalResult.Diag = D;
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001009 Info.EvalResult.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001010 }
Chris Lattner99415702008-07-12 00:14:42 +00001011 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001012 }
Mike Stump11289f42009-09-09 15:08:12 +00001013
Peter Collingbournee9200682011-05-13 03:29:01 +00001014 bool Success(const APValue &V, const Expr *E) {
1015 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001016 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001017 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001018 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001019 }
Mike Stump11289f42009-09-09 15:08:12 +00001020
Peter Collingbournee9200682011-05-13 03:29:01 +00001021 //===--------------------------------------------------------------------===//
1022 // Visitor Methods
1023 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001024
Chris Lattner7174bf32008-07-12 00:38:25 +00001025 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001026 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001027 }
1028 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001029 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001030 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001031
1032 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1033 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001034 if (CheckReferencedDecl(E, E->getDecl()))
1035 return true;
1036
1037 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001038 }
1039 bool VisitMemberExpr(const MemberExpr *E) {
1040 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1041 // Conservatively assume a MemberExpr will have side-effects
1042 Info.EvalResult.HasSideEffects = true;
1043 return true;
1044 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001045
1046 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001047 }
1048
Peter Collingbournee9200682011-05-13 03:29:01 +00001049 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001050 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001051 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001052 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001053
Peter Collingbournee9200682011-05-13 03:29:01 +00001054 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001055 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001056
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001057 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001058 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001059 }
Mike Stump11289f42009-09-09 15:08:12 +00001060
Anders Carlsson39def3a2008-12-21 22:39:40 +00001061 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001062 return Success(0, E);
Anders Carlsson39def3a2008-12-21 22:39:40 +00001063 }
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregor747eb782010-07-08 06:14:04 +00001065 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001066 return Success(0, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001067 }
1068
Eli Friedman4e7a2412009-02-27 04:45:43 +00001069 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1070 return Success(0, E);
1071 }
1072
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001073 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001074 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001075 }
1076
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001077 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1078 return Success(E->getValue(), E);
1079 }
1080
John Wiegley6242b6a2011-04-28 00:16:57 +00001081 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1082 return Success(E->getValue(), E);
1083 }
1084
John Wiegleyf9f65842011-04-25 06:54:41 +00001085 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1086 return Success(E->getValue(), E);
1087 }
1088
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001089 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001090 bool VisitUnaryImag(const UnaryOperator *E);
1091
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001092 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001093 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001094
1095 bool VisitInitListExpr(const InitListExpr *E);
1096
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001097private:
Ken Dyck160146e2010-01-27 17:10:57 +00001098 CharUnits GetAlignOfExpr(const Expr *E);
1099 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001100 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001101 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001102 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001103};
Chris Lattner05706e882008-07-11 18:11:29 +00001104} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001105
Daniel Dunbarce399542009-02-20 18:22:23 +00001106static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001107 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001108 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001109}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001110
Daniel Dunbarce399542009-02-20 18:22:23 +00001111static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001112 assert(E->getType()->isIntegralOrEnumerationType());
John McCallf0c4f352010-05-07 05:46:35 +00001113
Daniel Dunbarce399542009-02-20 18:22:23 +00001114 APValue Val;
1115 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1116 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001117 Result = Val.getInt();
1118 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001119}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001120
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001121bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001122 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001123 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001124 // Check for signedness/width mismatches between E type and ECD value.
1125 bool SameSign = (ECD->getInitVal().isSigned()
1126 == E->getType()->isSignedIntegerOrEnumerationType());
1127 bool SameWidth = (ECD->getInitVal().getBitWidth()
1128 == Info.Ctx.getIntWidth(E->getType()));
1129 if (SameSign && SameWidth)
1130 return Success(ECD->getInitVal(), E);
1131 else {
1132 // Get rid of mismatch (otherwise Success assertions will fail)
1133 // by computing a new value matching the type of E.
1134 llvm::APSInt Val = ECD->getInitVal();
1135 if (!SameSign)
1136 Val.setIsSigned(!ECD->getInitVal().isSigned());
1137 if (!SameWidth)
1138 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1139 return Success(Val, E);
1140 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001141 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001142
1143 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +00001144 // In C, they can also be folded, although they are not ICEs.
Douglas Gregor0840cc02009-11-01 20:32:48 +00001145 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1146 == Qualifiers::Const) {
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001147
1148 if (isa<ParmVarDecl>(D))
Peter Collingbournee9200682011-05-13 03:29:01 +00001149 return false;
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001150
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001151 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001152 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedman1d6fb162009-12-03 20:31:57 +00001153 if (APValue *V = VD->getEvaluatedValue()) {
1154 if (V->isInt())
1155 return Success(V->getInt(), E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001156 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001157 }
1158
1159 if (VD->isEvaluatingValue())
Peter Collingbournee9200682011-05-13 03:29:01 +00001160 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001161
1162 VD->setEvaluatingValue();
1163
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001164 Expr::EvalResult EResult;
1165 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1166 EResult.Val.isInt()) {
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001167 // Cache the evaluated value in the variable declaration.
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001168 Result = EResult.Val;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001169 VD->setEvaluatedValue(Result);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001170 return true;
1171 }
1172
Eli Friedman1d6fb162009-12-03 20:31:57 +00001173 VD->setEvaluatedValue(APValue());
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001174 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001175 }
1176 }
1177
Chris Lattner7174bf32008-07-12 00:38:25 +00001178 // Otherwise, random variable references are not constants.
Peter Collingbournee9200682011-05-13 03:29:01 +00001179 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001180}
1181
Chris Lattner86ee2862008-10-06 06:40:35 +00001182/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1183/// as GCC.
1184static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1185 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001186 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001187 enum gcc_type_class {
1188 no_type_class = -1,
1189 void_type_class, integer_type_class, char_type_class,
1190 enumeral_type_class, boolean_type_class,
1191 pointer_type_class, reference_type_class, offset_type_class,
1192 real_type_class, complex_type_class,
1193 function_type_class, method_type_class,
1194 record_type_class, union_type_class,
1195 array_type_class, string_type_class,
1196 lang_type_class
1197 };
Mike Stump11289f42009-09-09 15:08:12 +00001198
1199 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001200 // ideal, however it is what gcc does.
1201 if (E->getNumArgs() == 0)
1202 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001203
Chris Lattner86ee2862008-10-06 06:40:35 +00001204 QualType ArgTy = E->getArg(0)->getType();
1205 if (ArgTy->isVoidType())
1206 return void_type_class;
1207 else if (ArgTy->isEnumeralType())
1208 return enumeral_type_class;
1209 else if (ArgTy->isBooleanType())
1210 return boolean_type_class;
1211 else if (ArgTy->isCharType())
1212 return string_type_class; // gcc doesn't appear to use char_type_class
1213 else if (ArgTy->isIntegerType())
1214 return integer_type_class;
1215 else if (ArgTy->isPointerType())
1216 return pointer_type_class;
1217 else if (ArgTy->isReferenceType())
1218 return reference_type_class;
1219 else if (ArgTy->isRealType())
1220 return real_type_class;
1221 else if (ArgTy->isComplexType())
1222 return complex_type_class;
1223 else if (ArgTy->isFunctionType())
1224 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001225 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001226 return record_type_class;
1227 else if (ArgTy->isUnionType())
1228 return union_type_class;
1229 else if (ArgTy->isArrayType())
1230 return array_type_class;
1231 else if (ArgTy->isUnionType())
1232 return union_type_class;
1233 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001234 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001235 return -1;
1236}
1237
John McCall95007602010-05-10 23:27:23 +00001238/// Retrieves the "underlying object type" of the given expression,
1239/// as used by __builtin_object_size.
1240QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1241 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1242 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1243 return VD->getType();
1244 } else if (isa<CompoundLiteralExpr>(E)) {
1245 return E->getType();
1246 }
1247
1248 return QualType();
1249}
1250
Peter Collingbournee9200682011-05-13 03:29:01 +00001251bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001252 // TODO: Perhaps we should let LLVM lower this?
1253 LValue Base;
1254 if (!EvaluatePointer(E->getArg(0), Base, Info))
1255 return false;
1256
1257 // If we can prove the base is null, lower to zero now.
1258 const Expr *LVBase = Base.getLValueBase();
1259 if (!LVBase) return Success(0, E);
1260
1261 QualType T = GetObjectType(LVBase);
1262 if (T.isNull() ||
1263 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001264 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001265 T->isVariablyModifiedType() ||
1266 T->isDependentType())
1267 return false;
1268
1269 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1270 CharUnits Offset = Base.getLValueOffset();
1271
1272 if (!Offset.isNegative() && Offset <= Size)
1273 Size -= Offset;
1274 else
1275 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001276 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001277}
1278
Peter Collingbournee9200682011-05-13 03:29:01 +00001279bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001280 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001281 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001282 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001283
1284 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001285 if (TryEvaluateBuiltinObjectSize(E))
1286 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001287
Eric Christopher99469702010-01-19 22:58:35 +00001288 // If evaluating the argument has side-effects we can't determine
1289 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001290 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001291 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001292 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001293 return Success(0, E);
1294 }
Mike Stump876387b2009-10-27 22:09:17 +00001295
Mike Stump722cedf2009-10-26 18:35:08 +00001296 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1297 }
1298
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001299 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001300 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001301
Anders Carlsson4c76e932008-11-24 04:21:33 +00001302 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001303 // __builtin_constant_p always has one operand: it returns true if that
1304 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001305 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001306
1307 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001308 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001309 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001310 return Success(Operand, E);
1311 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001312
1313 case Builtin::BI__builtin_expect:
1314 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001315
1316 case Builtin::BIstrlen:
1317 case Builtin::BI__builtin_strlen:
1318 // As an extension, we support strlen() and __builtin_strlen() as constant
1319 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001320 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001321 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1322 // The string literal may have embedded null characters. Find the first
1323 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001324 StringRef Str = S->getString();
1325 StringRef::size_type Pos = Str.find(0);
1326 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001327 Str = Str.substr(0, Pos);
1328
1329 return Success(Str.size(), E);
1330 }
1331
1332 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001333 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001334}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001335
Chris Lattnere13042c2008-07-11 19:10:17 +00001336bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001337 if (E->getOpcode() == BO_Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001338 if (!Visit(E->getRHS()))
1339 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001340
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001341 // If we can't evaluate the LHS, it might have side effects;
1342 // conservatively mark it.
1343 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1344 Info.EvalResult.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001345
Anders Carlsson564730a2008-12-01 02:07:06 +00001346 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001347 }
1348
1349 if (E->isLogicalOp()) {
1350 // These need to be handled specially because the operands aren't
1351 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001352 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001353
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001354 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001355 // We were able to evaluate the LHS, see if we can get away with not
1356 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001357 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001358 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001359
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001360 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001361 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001362 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001363 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001364 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001365 }
1366 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001367 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001368 // We can't evaluate the LHS; however, sometimes the result
1369 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001370 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1371 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001372 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001373 // must have had side effects.
1374 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001375
1376 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001377 }
1378 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001379 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001380
Eli Friedman5a332ea2008-11-13 06:09:17 +00001381 return false;
1382 }
1383
Anders Carlssonacc79812008-11-16 07:17:21 +00001384 QualType LHSTy = E->getLHS()->getType();
1385 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001386
1387 if (LHSTy->isAnyComplexType()) {
1388 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001389 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001390
1391 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1392 return false;
1393
1394 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1395 return false;
1396
1397 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001398 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001399 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001400 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001401 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1402
John McCalle3027922010-08-25 11:45:40 +00001403 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001404 return Success((CR_r == APFloat::cmpEqual &&
1405 CR_i == APFloat::cmpEqual), E);
1406 else {
John McCalle3027922010-08-25 11:45:40 +00001407 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001408 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001409 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001410 CR_r == APFloat::cmpLessThan ||
1411 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001412 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001413 CR_i == APFloat::cmpLessThan ||
1414 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001415 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001416 } else {
John McCalle3027922010-08-25 11:45:40 +00001417 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001418 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1419 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1420 else {
John McCalle3027922010-08-25 11:45:40 +00001421 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001422 "Invalid compex comparison.");
1423 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1424 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1425 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001426 }
1427 }
Mike Stump11289f42009-09-09 15:08:12 +00001428
Anders Carlssonacc79812008-11-16 07:17:21 +00001429 if (LHSTy->isRealFloatingType() &&
1430 RHSTy->isRealFloatingType()) {
1431 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001432
Anders Carlssonacc79812008-11-16 07:17:21 +00001433 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1434 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001435
Anders Carlssonacc79812008-11-16 07:17:21 +00001436 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1437 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001438
Anders Carlssonacc79812008-11-16 07:17:21 +00001439 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001440
Anders Carlssonacc79812008-11-16 07:17:21 +00001441 switch (E->getOpcode()) {
1442 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001443 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001444 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001445 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001446 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001447 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001448 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001449 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001450 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001451 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001452 E);
John McCalle3027922010-08-25 11:45:40 +00001453 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001454 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001455 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001456 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001457 || CR == APFloat::cmpLessThan
1458 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001459 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001460 }
Mike Stump11289f42009-09-09 15:08:12 +00001461
Eli Friedmana38da572009-04-28 19:17:36 +00001462 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001463 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001464 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001465 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1466 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001467
John McCall45d55e42010-05-07 21:00:08 +00001468 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001469 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1470 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001471
Eli Friedman334046a2009-06-14 02:17:33 +00001472 // Reject any bases from the normal codepath; we special-case comparisons
1473 // to null.
1474 if (LHSValue.getLValueBase()) {
1475 if (!E->isEqualityOp())
1476 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001477 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001478 return false;
1479 bool bres;
1480 if (!EvalPointerValueAsBool(LHSValue, bres))
1481 return false;
John McCalle3027922010-08-25 11:45:40 +00001482 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001483 } else if (RHSValue.getLValueBase()) {
1484 if (!E->isEqualityOp())
1485 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001486 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001487 return false;
1488 bool bres;
1489 if (!EvalPointerValueAsBool(RHSValue, bres))
1490 return false;
John McCalle3027922010-08-25 11:45:40 +00001491 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001492 }
Eli Friedman64004332009-03-23 04:38:34 +00001493
John McCalle3027922010-08-25 11:45:40 +00001494 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001495 QualType Type = E->getLHS()->getType();
1496 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001497
Ken Dyck02990832010-01-15 12:37:54 +00001498 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001499 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001500 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001501
Ken Dyck02990832010-01-15 12:37:54 +00001502 CharUnits Diff = LHSValue.getLValueOffset() -
1503 RHSValue.getLValueOffset();
1504 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001505 }
1506 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001507 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001508 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001509 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001510 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1511 }
1512 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001513 }
1514 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001515 if (!LHSTy->isIntegralOrEnumerationType() ||
1516 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001517 // We can't continue from here for non-integral types, and they
1518 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001519 return false;
1520 }
1521
Anders Carlsson9c181652008-07-08 14:35:21 +00001522 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001523 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001524 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001525
Eli Friedman94c25c62009-03-24 01:14:50 +00001526 APValue RHSVal;
1527 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001528 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001529
1530 // Handle cases like (unsigned long)&a + 4.
1531 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001532 CharUnits Offset = Result.getLValueOffset();
1533 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1534 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001535 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001536 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001537 else
Ken Dyck02990832010-01-15 12:37:54 +00001538 Offset -= AdditionalOffset;
1539 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001540 return true;
1541 }
1542
1543 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001544 if (E->getOpcode() == BO_Add &&
Eli Friedman94c25c62009-03-24 01:14:50 +00001545 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001546 CharUnits Offset = RHSVal.getLValueOffset();
1547 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1548 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001549 return true;
1550 }
1551
1552 // All the following cases expect both operands to be an integer
1553 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001554 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001555
Eli Friedman94c25c62009-03-24 01:14:50 +00001556 APSInt& RHS = RHSVal.getInt();
1557
Anders Carlsson9c181652008-07-08 14:35:21 +00001558 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001559 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001560 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001561 case BO_Mul: return Success(Result.getInt() * RHS, E);
1562 case BO_Add: return Success(Result.getInt() + RHS, E);
1563 case BO_Sub: return Success(Result.getInt() - RHS, E);
1564 case BO_And: return Success(Result.getInt() & RHS, E);
1565 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1566 case BO_Or: return Success(Result.getInt() | RHS, E);
1567 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001568 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001569 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001570 return Success(Result.getInt() / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001571 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001572 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001573 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001574 return Success(Result.getInt() % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001575 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001576 // During constant-folding, a negative shift is an opposite shift.
1577 if (RHS.isSigned() && RHS.isNegative()) {
1578 RHS = -RHS;
1579 goto shift_right;
1580 }
1581
1582 shift_left:
1583 unsigned SA
1584 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001585 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001586 }
John McCalle3027922010-08-25 11:45:40 +00001587 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001588 // During constant-folding, a negative shift is an opposite shift.
1589 if (RHS.isSigned() && RHS.isNegative()) {
1590 RHS = -RHS;
1591 goto shift_left;
1592 }
1593
1594 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001595 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001596 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1597 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001598 }
Mike Stump11289f42009-09-09 15:08:12 +00001599
John McCalle3027922010-08-25 11:45:40 +00001600 case BO_LT: return Success(Result.getInt() < RHS, E);
1601 case BO_GT: return Success(Result.getInt() > RHS, E);
1602 case BO_LE: return Success(Result.getInt() <= RHS, E);
1603 case BO_GE: return Success(Result.getInt() >= RHS, E);
1604 case BO_EQ: return Success(Result.getInt() == RHS, E);
1605 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001606 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001607}
1608
Ken Dyck160146e2010-01-27 17:10:57 +00001609CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001610 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1611 // the result is the size of the referenced type."
1612 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1613 // result shall be the alignment of the referenced type."
1614 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1615 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00001616
1617 // __alignof is defined to return the preferred alignment.
1618 return Info.Ctx.toCharUnitsFromBits(
1619 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001620}
1621
Ken Dyck160146e2010-01-27 17:10:57 +00001622CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001623 E = E->IgnoreParens();
1624
1625 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001626 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001627 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001628 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1629 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001630
Chris Lattner68061312009-01-24 21:53:27 +00001631 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001632 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1633 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001634
Chris Lattner24aeeab2009-01-24 21:09:06 +00001635 return GetAlignOfType(E->getType());
1636}
1637
1638
Peter Collingbournee190dee2011-03-11 19:24:49 +00001639/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1640/// a result as the expression's type.
1641bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1642 const UnaryExprOrTypeTraitExpr *E) {
1643 switch(E->getKind()) {
1644 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001645 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00001646 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001647 else
Ken Dyckdbc01912011-03-11 02:13:43 +00001648 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001649 }
Eli Friedman64004332009-03-23 04:38:34 +00001650
Peter Collingbournee190dee2011-03-11 19:24:49 +00001651 case UETT_VecStep: {
1652 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00001653
Peter Collingbournee190dee2011-03-11 19:24:49 +00001654 if (Ty->isVectorType()) {
1655 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00001656
Peter Collingbournee190dee2011-03-11 19:24:49 +00001657 // The vec_step built-in functions that take a 3-component
1658 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1659 if (n == 3)
1660 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001661
Peter Collingbournee190dee2011-03-11 19:24:49 +00001662 return Success(n, E);
1663 } else
1664 return Success(1, E);
1665 }
1666
1667 case UETT_SizeOf: {
1668 QualType SrcTy = E->getTypeOfArgument();
1669 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1670 // the result is the size of the referenced type."
1671 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1672 // result shall be the alignment of the referenced type."
1673 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1674 SrcTy = Ref->getPointeeType();
1675
1676 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1677 // extension.
1678 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1679 return Success(1, E);
1680
1681 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1682 if (!SrcTy->isConstantSizeType())
1683 return false;
1684
1685 // Get information about the size.
1686 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1687 }
1688 }
1689
1690 llvm_unreachable("unknown expr/type trait");
1691 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001692}
1693
Peter Collingbournee9200682011-05-13 03:29:01 +00001694bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00001695 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00001696 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00001697 if (n == 0)
1698 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001699 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00001700 for (unsigned i = 0; i != n; ++i) {
1701 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1702 switch (ON.getKind()) {
1703 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00001704 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00001705 APSInt IdxResult;
1706 if (!EvaluateInteger(Idx, IdxResult, Info))
1707 return false;
1708 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1709 if (!AT)
1710 return false;
1711 CurrentType = AT->getElementType();
1712 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1713 Result += IdxResult.getSExtValue() * ElementSize;
1714 break;
1715 }
1716
1717 case OffsetOfExpr::OffsetOfNode::Field: {
1718 FieldDecl *MemberDecl = ON.getField();
1719 const RecordType *RT = CurrentType->getAs<RecordType>();
1720 if (!RT)
1721 return false;
1722 RecordDecl *RD = RT->getDecl();
1723 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00001724 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00001725 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001726 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00001727 CurrentType = MemberDecl->getType().getNonReferenceType();
1728 break;
1729 }
1730
1731 case OffsetOfExpr::OffsetOfNode::Identifier:
1732 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001733 return false;
1734
1735 case OffsetOfExpr::OffsetOfNode::Base: {
1736 CXXBaseSpecifier *BaseSpec = ON.getBase();
1737 if (BaseSpec->isVirtual())
1738 return false;
1739
1740 // Find the layout of the class whose base we are looking into.
1741 const RecordType *RT = CurrentType->getAs<RecordType>();
1742 if (!RT)
1743 return false;
1744 RecordDecl *RD = RT->getDecl();
1745 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1746
1747 // Find the base class itself.
1748 CurrentType = BaseSpec->getType();
1749 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1750 if (!BaseRT)
1751 return false;
1752
1753 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00001754 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00001755 break;
1756 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001757 }
1758 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001759 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00001760}
1761
Chris Lattnere13042c2008-07-11 19:10:17 +00001762bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001763 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001764 // LNot's operand isn't necessarily an integer, so we handle it specially.
1765 bool bres;
1766 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1767 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001768 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001769 }
1770
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001771 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00001772 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001773 return false;
1774
Chris Lattnercdf34e72008-07-11 22:52:41 +00001775 // Get the operand value into 'Result'.
1776 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001777 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001778
Chris Lattnerf09ad162008-07-11 22:15:16 +00001779 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001780 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001781 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1782 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001783 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001784 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001785 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1786 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001787 return true;
John McCalle3027922010-08-25 11:45:40 +00001788 case UO_Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001789 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001790 return true;
John McCalle3027922010-08-25 11:45:40 +00001791 case UO_Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001792 if (!Result.isInt()) return false;
1793 return Success(-Result.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00001794 case UO_Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001795 if (!Result.isInt()) return false;
1796 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001797 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001798}
Mike Stump11289f42009-09-09 15:08:12 +00001799
Chris Lattner477c4be2008-07-12 01:15:53 +00001800/// HandleCast - This is used to evaluate implicit or explicit casts where the
1801/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00001802bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1803 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001804 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001805 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001806
Eli Friedmanc757de22011-03-25 00:43:55 +00001807 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00001808 case CK_BaseToDerived:
1809 case CK_DerivedToBase:
1810 case CK_UncheckedDerivedToBase:
1811 case CK_Dynamic:
1812 case CK_ToUnion:
1813 case CK_ArrayToPointerDecay:
1814 case CK_FunctionToPointerDecay:
1815 case CK_NullToPointer:
1816 case CK_NullToMemberPointer:
1817 case CK_BaseToDerivedMemberPointer:
1818 case CK_DerivedToBaseMemberPointer:
1819 case CK_ConstructorConversion:
1820 case CK_IntegralToPointer:
1821 case CK_ToVoid:
1822 case CK_VectorSplat:
1823 case CK_IntegralToFloating:
1824 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00001825 case CK_CPointerToObjCPointerCast:
1826 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001827 case CK_AnyPointerToBlockPointerCast:
1828 case CK_ObjCObjectLValueCast:
1829 case CK_FloatingRealToComplex:
1830 case CK_FloatingComplexToReal:
1831 case CK_FloatingComplexCast:
1832 case CK_FloatingComplexToIntegralComplex:
1833 case CK_IntegralRealToComplex:
1834 case CK_IntegralComplexCast:
1835 case CK_IntegralComplexToFloatingComplex:
1836 llvm_unreachable("invalid cast kind for integral value");
1837
Eli Friedman9faf2f92011-03-25 19:07:11 +00001838 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001839 case CK_Dependent:
1840 case CK_GetObjCProperty:
1841 case CK_LValueBitCast:
1842 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00001843 case CK_ARCProduceObject:
1844 case CK_ARCConsumeObject:
1845 case CK_ARCReclaimReturnedObject:
1846 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00001847 return false;
1848
1849 case CK_LValueToRValue:
1850 case CK_NoOp:
1851 return Visit(E->getSubExpr());
1852
1853 case CK_MemberPointerToBoolean:
1854 case CK_PointerToBoolean:
1855 case CK_IntegralToBoolean:
1856 case CK_FloatingToBoolean:
1857 case CK_FloatingComplexToBoolean:
1858 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00001859 bool BoolResult;
1860 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1861 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001862 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001863 }
1864
Eli Friedmanc757de22011-03-25 00:43:55 +00001865 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00001866 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001867 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001868
Eli Friedman742421e2009-02-20 01:15:07 +00001869 if (!Result.isInt()) {
1870 // Only allow casts of lvalues if they are lossless.
1871 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1872 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001873
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001874 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001875 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001876 }
Mike Stump11289f42009-09-09 15:08:12 +00001877
Eli Friedmanc757de22011-03-25 00:43:55 +00001878 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00001879 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001880 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001881 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001882
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001883 if (LV.getLValueBase()) {
1884 // Only allow based lvalue casts if they are lossless.
1885 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1886 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001887
John McCall45d55e42010-05-07 21:00:08 +00001888 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001889 return true;
1890 }
1891
Ken Dyck02990832010-01-15 12:37:54 +00001892 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1893 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001894 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001895 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001896
Eli Friedmanc757de22011-03-25 00:43:55 +00001897 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00001898 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001899 if (!EvaluateComplex(SubExpr, C, Info))
1900 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00001901 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001902 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001903
Eli Friedmanc757de22011-03-25 00:43:55 +00001904 case CK_FloatingToIntegral: {
1905 APFloat F(0.0);
1906 if (!EvaluateFloat(SubExpr, F, Info))
1907 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00001908
Eli Friedmanc757de22011-03-25 00:43:55 +00001909 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1910 }
1911 }
Mike Stump11289f42009-09-09 15:08:12 +00001912
Eli Friedmanc757de22011-03-25 00:43:55 +00001913 llvm_unreachable("unknown cast resulting in integral value");
1914 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001915}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001916
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001917bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1918 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001919 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001920 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1921 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1922 return Success(LV.getComplexIntReal(), E);
1923 }
1924
1925 return Visit(E->getSubExpr());
1926}
1927
Eli Friedman4e7a2412009-02-27 04:45:43 +00001928bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001929 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001930 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001931 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1932 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1933 return Success(LV.getComplexIntImag(), E);
1934 }
1935
Eli Friedman4e7a2412009-02-27 04:45:43 +00001936 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1937 Info.EvalResult.HasSideEffects = true;
1938 return Success(0, E);
1939}
1940
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001941bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1942 return Success(E->getPackLength(), E);
1943}
1944
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001945bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1946 return Success(E->getValue(), E);
1947}
1948
Sebastian Redl12757ab2011-09-24 17:48:14 +00001949bool IntExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
1950 if (!Info.Ctx.getLangOptions().CPlusPlus0x)
1951 return Error(E);
1952
1953 if (E->getNumInits() == 0)
1954 return Success(0, E);
1955
1956 assert(E->getNumInits() == 1 && "Excess initializers for integer in C++11.");
1957 return Visit(E->getInit(0));
1958}
1959
Chris Lattner05706e882008-07-11 18:11:29 +00001960//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00001961// Float Evaluation
1962//===----------------------------------------------------------------------===//
1963
1964namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001965class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001966 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00001967 APFloat &Result;
1968public:
1969 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001970 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00001971
Peter Collingbournee9200682011-05-13 03:29:01 +00001972 bool Success(const APValue &V, const Expr *e) {
1973 Result = V.getFloat();
1974 return true;
1975 }
1976 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00001977 return false;
1978 }
1979
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001980 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001981
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001982 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001983 bool VisitBinaryOperator(const BinaryOperator *E);
1984 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001985 bool VisitCastExpr(const CastExpr *E);
1986 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00001987
John McCallb1fb0d32010-05-07 22:08:54 +00001988 bool VisitUnaryReal(const UnaryOperator *E);
1989 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00001990
John McCalla2fabff2010-10-09 01:34:31 +00001991 bool VisitDeclRefExpr(const DeclRefExpr *E);
1992
Sebastian Redl12757ab2011-09-24 17:48:14 +00001993 bool VisitInitListExpr(const InitListExpr *E);
1994
John McCallb1fb0d32010-05-07 22:08:54 +00001995 // FIXME: Missing: array subscript of vector, member of vector,
1996 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00001997};
1998} // end anonymous namespace
1999
2000static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002001 assert(E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002002 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002003}
2004
Jay Foad39c79802011-01-12 09:06:06 +00002005static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002006 QualType ResultTy,
2007 const Expr *Arg,
2008 bool SNaN,
2009 llvm::APFloat &Result) {
2010 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2011 if (!S) return false;
2012
2013 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2014
2015 llvm::APInt fill;
2016
2017 // Treat empty strings as if they were zero.
2018 if (S->getString().empty())
2019 fill = llvm::APInt(32, 0);
2020 else if (S->getString().getAsInteger(0, fill))
2021 return false;
2022
2023 if (SNaN)
2024 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2025 else
2026 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2027 return true;
2028}
2029
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002030bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002031 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002032 default:
2033 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2034
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002035 case Builtin::BI__builtin_huge_val:
2036 case Builtin::BI__builtin_huge_valf:
2037 case Builtin::BI__builtin_huge_vall:
2038 case Builtin::BI__builtin_inf:
2039 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002040 case Builtin::BI__builtin_infl: {
2041 const llvm::fltSemantics &Sem =
2042 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002043 Result = llvm::APFloat::getInf(Sem);
2044 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002045 }
Mike Stump11289f42009-09-09 15:08:12 +00002046
John McCall16291492010-02-28 13:00:19 +00002047 case Builtin::BI__builtin_nans:
2048 case Builtin::BI__builtin_nansf:
2049 case Builtin::BI__builtin_nansl:
2050 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2051 true, Result);
2052
Chris Lattner0b7282e2008-10-06 06:31:58 +00002053 case Builtin::BI__builtin_nan:
2054 case Builtin::BI__builtin_nanf:
2055 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002056 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002057 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002058 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2059 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002060
2061 case Builtin::BI__builtin_fabs:
2062 case Builtin::BI__builtin_fabsf:
2063 case Builtin::BI__builtin_fabsl:
2064 if (!EvaluateFloat(E->getArg(0), Result, Info))
2065 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002066
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002067 if (Result.isNegative())
2068 Result.changeSign();
2069 return true;
2070
Mike Stump11289f42009-09-09 15:08:12 +00002071 case Builtin::BI__builtin_copysign:
2072 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002073 case Builtin::BI__builtin_copysignl: {
2074 APFloat RHS(0.);
2075 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2076 !EvaluateFloat(E->getArg(1), RHS, Info))
2077 return false;
2078 Result.copySign(RHS);
2079 return true;
2080 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002081 }
2082}
2083
John McCalla2fabff2010-10-09 01:34:31 +00002084bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002085 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2086 return true;
2087
John McCalla2fabff2010-10-09 01:34:31 +00002088 const Decl *D = E->getDecl();
2089 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2090 const VarDecl *VD = cast<VarDecl>(D);
2091
2092 // Require the qualifiers to be const and not volatile.
2093 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2094 if (!T.isConstQualified() || T.isVolatileQualified())
2095 return false;
2096
2097 const Expr *Init = VD->getAnyInitializer();
2098 if (!Init) return false;
2099
2100 if (APValue *V = VD->getEvaluatedValue()) {
2101 if (V->isFloat()) {
2102 Result = V->getFloat();
2103 return true;
2104 }
2105 return false;
2106 }
2107
2108 if (VD->isEvaluatingValue())
2109 return false;
2110
2111 VD->setEvaluatingValue();
2112
2113 Expr::EvalResult InitResult;
2114 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2115 InitResult.Val.isFloat()) {
2116 // Cache the evaluated value in the variable declaration.
2117 Result = InitResult.Val.getFloat();
2118 VD->setEvaluatedValue(InitResult.Val);
2119 return true;
2120 }
2121
2122 VD->setEvaluatedValue(APValue());
2123 return false;
2124}
2125
John McCallb1fb0d32010-05-07 22:08:54 +00002126bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002127 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2128 ComplexValue CV;
2129 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2130 return false;
2131 Result = CV.FloatReal;
2132 return true;
2133 }
2134
2135 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002136}
2137
2138bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002139 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2140 ComplexValue CV;
2141 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2142 return false;
2143 Result = CV.FloatImag;
2144 return true;
2145 }
2146
2147 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2148 Info.EvalResult.HasSideEffects = true;
2149 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2150 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002151 return true;
2152}
2153
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002154bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002155 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002156 return false;
2157
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002158 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2159 return false;
2160
2161 switch (E->getOpcode()) {
2162 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002163 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002164 return true;
John McCalle3027922010-08-25 11:45:40 +00002165 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002166 Result.changeSign();
2167 return true;
2168 }
2169}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002170
Eli Friedman24c01542008-08-22 00:06:13 +00002171bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002172 if (E->getOpcode() == BO_Comma) {
Eli Friedman141fbf32009-11-16 04:25:37 +00002173 if (!EvaluateFloat(E->getRHS(), Result, Info))
2174 return false;
2175
2176 // If we can't evaluate the LHS, it might have side effects;
2177 // conservatively mark it.
2178 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2179 Info.EvalResult.HasSideEffects = true;
2180
2181 return true;
2182 }
2183
Anders Carlssona5df61a2010-10-31 01:21:47 +00002184 // We can't evaluate pointer-to-member operations.
2185 if (E->isPtrMemOp())
2186 return false;
2187
Eli Friedman24c01542008-08-22 00:06:13 +00002188 // FIXME: Diagnostics? I really don't understand how the warnings
2189 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002190 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002191 if (!EvaluateFloat(E->getLHS(), Result, Info))
2192 return false;
2193 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2194 return false;
2195
2196 switch (E->getOpcode()) {
2197 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002198 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002199 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2200 return true;
John McCalle3027922010-08-25 11:45:40 +00002201 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002202 Result.add(RHS, APFloat::rmNearestTiesToEven);
2203 return true;
John McCalle3027922010-08-25 11:45:40 +00002204 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002205 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2206 return true;
John McCalle3027922010-08-25 11:45:40 +00002207 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002208 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2209 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002210 }
2211}
2212
2213bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2214 Result = E->getValue();
2215 return true;
2216}
2217
Peter Collingbournee9200682011-05-13 03:29:01 +00002218bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2219 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002220
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002221 switch (E->getCastKind()) {
2222 default:
2223 return false;
2224
2225 case CK_LValueToRValue:
2226 case CK_NoOp:
2227 return Visit(SubExpr);
2228
2229 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002230 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002231 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002232 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002233 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002234 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002235 return true;
2236 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002237
2238 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002239 if (!Visit(SubExpr))
2240 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002241 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2242 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002243 return true;
2244 }
John McCalld7646252010-11-14 08:17:51 +00002245
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002246 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002247 ComplexValue V;
2248 if (!EvaluateComplex(SubExpr, V, Info))
2249 return false;
2250 Result = V.getComplexFloatReal();
2251 return true;
2252 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002253 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002254
2255 return false;
2256}
2257
Peter Collingbournee9200682011-05-13 03:29:01 +00002258bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +00002259 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2260 return true;
2261}
2262
Sebastian Redl12757ab2011-09-24 17:48:14 +00002263bool FloatExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2264 if (!Info.Ctx.getLangOptions().CPlusPlus0x)
2265 return Error(E);
2266
2267 if (E->getNumInits() == 0) {
2268 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2269 return true;
2270 }
2271
2272 assert(E->getNumInits() == 1 && "Excess initializers for integer in C++11.");
2273 return Visit(E->getInit(0));
2274}
2275
Eli Friedman24c01542008-08-22 00:06:13 +00002276//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002277// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002278//===----------------------------------------------------------------------===//
2279
2280namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002281class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002282 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002283 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002284
Anders Carlsson537969c2008-11-16 20:27:53 +00002285public:
John McCall93d91dc2010-05-07 17:22:02 +00002286 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002287 : ExprEvaluatorBaseTy(info), Result(Result) {}
2288
2289 bool Success(const APValue &V, const Expr *e) {
2290 Result.setFrom(V);
2291 return true;
2292 }
2293 bool Error(const Expr *E) {
2294 return false;
2295 }
Mike Stump11289f42009-09-09 15:08:12 +00002296
Anders Carlsson537969c2008-11-16 20:27:53 +00002297 //===--------------------------------------------------------------------===//
2298 // Visitor Methods
2299 //===--------------------------------------------------------------------===//
2300
Peter Collingbournee9200682011-05-13 03:29:01 +00002301 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002302
Peter Collingbournee9200682011-05-13 03:29:01 +00002303 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002304
John McCall93d91dc2010-05-07 17:22:02 +00002305 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002306 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002307 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002308};
2309} // end anonymous namespace
2310
John McCall93d91dc2010-05-07 17:22:02 +00002311static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2312 EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002313 assert(E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002314 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002315}
2316
Peter Collingbournee9200682011-05-13 03:29:01 +00002317bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2318 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002319
2320 if (SubExpr->getType()->isRealFloatingType()) {
2321 Result.makeComplexFloat();
2322 APFloat &Imag = Result.FloatImag;
2323 if (!EvaluateFloat(SubExpr, Imag, Info))
2324 return false;
2325
2326 Result.FloatReal = APFloat(Imag.getSemantics());
2327 return true;
2328 } else {
2329 assert(SubExpr->getType()->isIntegerType() &&
2330 "Unexpected imaginary literal.");
2331
2332 Result.makeComplexInt();
2333 APSInt &Imag = Result.IntImag;
2334 if (!EvaluateInteger(SubExpr, Imag, Info))
2335 return false;
2336
2337 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2338 return true;
2339 }
2340}
2341
Peter Collingbournee9200682011-05-13 03:29:01 +00002342bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002343
John McCallfcef3cf2010-12-14 17:51:41 +00002344 switch (E->getCastKind()) {
2345 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002346 case CK_BaseToDerived:
2347 case CK_DerivedToBase:
2348 case CK_UncheckedDerivedToBase:
2349 case CK_Dynamic:
2350 case CK_ToUnion:
2351 case CK_ArrayToPointerDecay:
2352 case CK_FunctionToPointerDecay:
2353 case CK_NullToPointer:
2354 case CK_NullToMemberPointer:
2355 case CK_BaseToDerivedMemberPointer:
2356 case CK_DerivedToBaseMemberPointer:
2357 case CK_MemberPointerToBoolean:
2358 case CK_ConstructorConversion:
2359 case CK_IntegralToPointer:
2360 case CK_PointerToIntegral:
2361 case CK_PointerToBoolean:
2362 case CK_ToVoid:
2363 case CK_VectorSplat:
2364 case CK_IntegralCast:
2365 case CK_IntegralToBoolean:
2366 case CK_IntegralToFloating:
2367 case CK_FloatingToIntegral:
2368 case CK_FloatingToBoolean:
2369 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002370 case CK_CPointerToObjCPointerCast:
2371 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002372 case CK_AnyPointerToBlockPointerCast:
2373 case CK_ObjCObjectLValueCast:
2374 case CK_FloatingComplexToReal:
2375 case CK_FloatingComplexToBoolean:
2376 case CK_IntegralComplexToReal:
2377 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002378 case CK_ARCProduceObject:
2379 case CK_ARCConsumeObject:
2380 case CK_ARCReclaimReturnedObject:
2381 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002382 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002383
John McCallfcef3cf2010-12-14 17:51:41 +00002384 case CK_LValueToRValue:
2385 case CK_NoOp:
2386 return Visit(E->getSubExpr());
2387
2388 case CK_Dependent:
2389 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002390 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002391 case CK_UserDefinedConversion:
2392 return false;
2393
2394 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002395 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002396 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002397 return false;
2398
John McCallfcef3cf2010-12-14 17:51:41 +00002399 Result.makeComplexFloat();
2400 Result.FloatImag = APFloat(Real.getSemantics());
2401 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002402 }
2403
John McCallfcef3cf2010-12-14 17:51:41 +00002404 case CK_FloatingComplexCast: {
2405 if (!Visit(E->getSubExpr()))
2406 return false;
2407
2408 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2409 QualType From
2410 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2411
2412 Result.FloatReal
2413 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2414 Result.FloatImag
2415 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2416 return true;
2417 }
2418
2419 case CK_FloatingComplexToIntegralComplex: {
2420 if (!Visit(E->getSubExpr()))
2421 return false;
2422
2423 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2424 QualType From
2425 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2426 Result.makeComplexInt();
2427 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2428 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2429 return true;
2430 }
2431
2432 case CK_IntegralRealToComplex: {
2433 APSInt &Real = Result.IntReal;
2434 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2435 return false;
2436
2437 Result.makeComplexInt();
2438 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2439 return true;
2440 }
2441
2442 case CK_IntegralComplexCast: {
2443 if (!Visit(E->getSubExpr()))
2444 return false;
2445
2446 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2447 QualType From
2448 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2449
2450 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2451 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2452 return true;
2453 }
2454
2455 case CK_IntegralComplexToFloatingComplex: {
2456 if (!Visit(E->getSubExpr()))
2457 return false;
2458
2459 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2460 QualType From
2461 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2462 Result.makeComplexFloat();
2463 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2464 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2465 return true;
2466 }
2467 }
2468
2469 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002470 return false;
2471}
2472
John McCall93d91dc2010-05-07 17:22:02 +00002473bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002474 if (E->getOpcode() == BO_Comma) {
2475 if (!Visit(E->getRHS()))
2476 return false;
2477
2478 // If we can't evaluate the LHS, it might have side effects;
2479 // conservatively mark it.
2480 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2481 Info.EvalResult.HasSideEffects = true;
2482
2483 return true;
2484 }
John McCall93d91dc2010-05-07 17:22:02 +00002485 if (!Visit(E->getLHS()))
2486 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002487
John McCall93d91dc2010-05-07 17:22:02 +00002488 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002489 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002490 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002491
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002492 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2493 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002494 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002495 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002496 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002497 if (Result.isComplexFloat()) {
2498 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2499 APFloat::rmNearestTiesToEven);
2500 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2501 APFloat::rmNearestTiesToEven);
2502 } else {
2503 Result.getComplexIntReal() += RHS.getComplexIntReal();
2504 Result.getComplexIntImag() += RHS.getComplexIntImag();
2505 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002506 break;
John McCalle3027922010-08-25 11:45:40 +00002507 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002508 if (Result.isComplexFloat()) {
2509 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2510 APFloat::rmNearestTiesToEven);
2511 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2512 APFloat::rmNearestTiesToEven);
2513 } else {
2514 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2515 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2516 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002517 break;
John McCalle3027922010-08-25 11:45:40 +00002518 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002519 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002520 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002521 APFloat &LHS_r = LHS.getComplexFloatReal();
2522 APFloat &LHS_i = LHS.getComplexFloatImag();
2523 APFloat &RHS_r = RHS.getComplexFloatReal();
2524 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002525
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002526 APFloat Tmp = LHS_r;
2527 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2528 Result.getComplexFloatReal() = Tmp;
2529 Tmp = LHS_i;
2530 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2531 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2532
2533 Tmp = LHS_r;
2534 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2535 Result.getComplexFloatImag() = Tmp;
2536 Tmp = LHS_i;
2537 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2538 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2539 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002540 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002541 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002542 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2543 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002544 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002545 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2546 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2547 }
2548 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002549 case BO_Div:
2550 if (Result.isComplexFloat()) {
2551 ComplexValue LHS = Result;
2552 APFloat &LHS_r = LHS.getComplexFloatReal();
2553 APFloat &LHS_i = LHS.getComplexFloatImag();
2554 APFloat &RHS_r = RHS.getComplexFloatReal();
2555 APFloat &RHS_i = RHS.getComplexFloatImag();
2556 APFloat &Res_r = Result.getComplexFloatReal();
2557 APFloat &Res_i = Result.getComplexFloatImag();
2558
2559 APFloat Den = RHS_r;
2560 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2561 APFloat Tmp = RHS_i;
2562 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2563 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2564
2565 Res_r = LHS_r;
2566 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2567 Tmp = LHS_i;
2568 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2569 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2570 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2571
2572 Res_i = LHS_i;
2573 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2574 Tmp = LHS_r;
2575 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2576 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2577 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2578 } else {
2579 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2580 // FIXME: what about diagnostics?
2581 return false;
2582 }
2583 ComplexValue LHS = Result;
2584 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2585 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2586 Result.getComplexIntReal() =
2587 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2588 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2589 Result.getComplexIntImag() =
2590 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2591 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2592 }
2593 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002594 }
2595
John McCall93d91dc2010-05-07 17:22:02 +00002596 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002597}
2598
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002599bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2600 // Get the operand value into 'Result'.
2601 if (!Visit(E->getSubExpr()))
2602 return false;
2603
2604 switch (E->getOpcode()) {
2605 default:
2606 // FIXME: what about diagnostics?
2607 return false;
2608 case UO_Extension:
2609 return true;
2610 case UO_Plus:
2611 // The result is always just the subexpr.
2612 return true;
2613 case UO_Minus:
2614 if (Result.isComplexFloat()) {
2615 Result.getComplexFloatReal().changeSign();
2616 Result.getComplexFloatImag().changeSign();
2617 }
2618 else {
2619 Result.getComplexIntReal() = -Result.getComplexIntReal();
2620 Result.getComplexIntImag() = -Result.getComplexIntImag();
2621 }
2622 return true;
2623 case UO_Not:
2624 if (Result.isComplexFloat())
2625 Result.getComplexFloatImag().changeSign();
2626 else
2627 Result.getComplexIntImag() = -Result.getComplexIntImag();
2628 return true;
2629 }
2630}
2631
Anders Carlsson537969c2008-11-16 20:27:53 +00002632//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002633// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002634//===----------------------------------------------------------------------===//
2635
John McCallc07a0c72011-02-17 10:25:35 +00002636static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00002637 if (E->getType()->isVectorType()) {
2638 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002639 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002640 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002641 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002642 return false;
John McCallc07a0c72011-02-17 10:25:35 +00002643 if (Info.EvalResult.Val.isLValue() &&
2644 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall11086fc2010-07-07 05:08:32 +00002645 return false;
John McCall45d55e42010-05-07 21:00:08 +00002646 } else if (E->getType()->hasPointerRepresentation()) {
2647 LValue LV;
2648 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002649 return false;
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002650 if (!IsGlobalLValue(LV.Base))
John McCall95007602010-05-10 23:27:23 +00002651 return false;
John McCall45d55e42010-05-07 21:00:08 +00002652 LV.moveInto(Info.EvalResult.Val);
2653 } else if (E->getType()->isRealFloatingType()) {
2654 llvm::APFloat F(0.0);
2655 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002656 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002657
John McCall45d55e42010-05-07 21:00:08 +00002658 Info.EvalResult.Val = APValue(F);
2659 } else if (E->getType()->isAnyComplexType()) {
2660 ComplexValue C;
2661 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002662 return false;
John McCall45d55e42010-05-07 21:00:08 +00002663 C.moveInto(Info.EvalResult.Val);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002664 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002665 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002666
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002667 return true;
2668}
2669
John McCallc07a0c72011-02-17 10:25:35 +00002670/// Evaluate - Return true if this is a constant which we can fold using
2671/// any crazy technique (that has nothing to do with language standards) that
2672/// we want to. If this function returns true, it returns the folded constant
2673/// in Result.
2674bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2675 EvalInfo Info(Ctx, Result);
2676 return ::Evaluate(Info, this);
2677}
2678
Jay Foad39c79802011-01-12 09:06:06 +00002679bool Expr::EvaluateAsBooleanCondition(bool &Result,
2680 const ASTContext &Ctx) const {
John McCall1be1c632010-01-05 23:42:56 +00002681 EvalResult Scratch;
2682 EvalInfo Info(Ctx, Scratch);
2683
2684 return HandleConversionToBool(this, Result, Info);
2685}
2686
Richard Smithcaf33902011-10-10 18:28:20 +00002687bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
2688 EvalResult Scratch;
2689 EvalInfo Info(Ctx, Scratch);
2690
2691 return EvaluateInteger(this, Result, Info) && !Scratch.HasSideEffects;
2692}
2693
Jay Foad39c79802011-01-12 09:06:06 +00002694bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002695 EvalInfo Info(Ctx, Result);
2696
John McCall45d55e42010-05-07 21:00:08 +00002697 LValue LV;
John McCall95007602010-05-10 23:27:23 +00002698 if (EvaluateLValue(this, LV, Info) &&
2699 !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002700 IsGlobalLValue(LV.Base)) {
2701 LV.moveInto(Result.Val);
2702 return true;
2703 }
2704 return false;
2705}
2706
Jay Foad39c79802011-01-12 09:06:06 +00002707bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2708 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002709 EvalInfo Info(Ctx, Result);
2710
2711 LValue LV;
2712 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00002713 LV.moveInto(Result.Val);
2714 return true;
2715 }
2716 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00002717}
2718
Chris Lattner67d7b922008-11-16 21:24:15 +00002719/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002720/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00002721bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002722 EvalResult Result;
2723 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002724}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002725
Jay Foad39c79802011-01-12 09:06:06 +00002726bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002727 Expr::EvalResult Result;
2728 EvalInfo Info(Ctx, Result);
Peter Collingbournee9200682011-05-13 03:29:01 +00002729 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002730}
2731
Richard Smithcaf33902011-10-10 18:28:20 +00002732APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002733 EvalResult EvalResult;
2734 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002735 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002736 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002737 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002738
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002739 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002740}
John McCall864e3962010-05-07 05:32:02 +00002741
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002742 bool Expr::EvalResult::isGlobalLValue() const {
2743 assert(Val.isLValue());
2744 return IsGlobalLValue(Val.getLValueBase());
2745 }
2746
2747
John McCall864e3962010-05-07 05:32:02 +00002748/// isIntegerConstantExpr - this recursive routine will test if an expression is
2749/// an integer constant expression.
2750
2751/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2752/// comma, etc
2753///
2754/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2755/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2756/// cast+dereference.
2757
2758// CheckICE - This function does the fundamental ICE checking: the returned
2759// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2760// Note that to reduce code duplication, this helper does no evaluation
2761// itself; the caller checks whether the expression is evaluatable, and
2762// in the rare cases where CheckICE actually cares about the evaluated
2763// value, it calls into Evalute.
2764//
2765// Meanings of Val:
2766// 0: This expression is an ICE if it can be evaluated by Evaluate.
2767// 1: This expression is not an ICE, but if it isn't evaluated, it's
2768// a legal subexpression for an ICE. This return value is used to handle
2769// the comma operator in C99 mode.
2770// 2: This expression is not an ICE, and is not a legal subexpression for one.
2771
Dan Gohman28ade552010-07-26 21:25:24 +00002772namespace {
2773
John McCall864e3962010-05-07 05:32:02 +00002774struct ICEDiag {
2775 unsigned Val;
2776 SourceLocation Loc;
2777
2778 public:
2779 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2780 ICEDiag() : Val(0) {}
2781};
2782
Dan Gohman28ade552010-07-26 21:25:24 +00002783}
2784
2785static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00002786
2787static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2788 Expr::EvalResult EVResult;
2789 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2790 !EVResult.Val.isInt()) {
2791 return ICEDiag(2, E->getLocStart());
2792 }
2793 return NoDiag();
2794}
2795
2796static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2797 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00002798 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00002799 return ICEDiag(2, E->getLocStart());
2800 }
2801
2802 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00002803#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00002804#define STMT(Node, Base) case Expr::Node##Class:
2805#define EXPR(Node, Base)
2806#include "clang/AST/StmtNodes.inc"
2807 case Expr::PredefinedExprClass:
2808 case Expr::FloatingLiteralClass:
2809 case Expr::ImaginaryLiteralClass:
2810 case Expr::StringLiteralClass:
2811 case Expr::ArraySubscriptExprClass:
2812 case Expr::MemberExprClass:
2813 case Expr::CompoundAssignOperatorClass:
2814 case Expr::CompoundLiteralExprClass:
2815 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00002816 case Expr::DesignatedInitExprClass:
2817 case Expr::ImplicitValueInitExprClass:
2818 case Expr::ParenListExprClass:
2819 case Expr::VAArgExprClass:
2820 case Expr::AddrLabelExprClass:
2821 case Expr::StmtExprClass:
2822 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00002823 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00002824 case Expr::CXXDynamicCastExprClass:
2825 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00002826 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00002827 case Expr::CXXNullPtrLiteralExprClass:
2828 case Expr::CXXThisExprClass:
2829 case Expr::CXXThrowExprClass:
2830 case Expr::CXXNewExprClass:
2831 case Expr::CXXDeleteExprClass:
2832 case Expr::CXXPseudoDestructorExprClass:
2833 case Expr::UnresolvedLookupExprClass:
2834 case Expr::DependentScopeDeclRefExprClass:
2835 case Expr::CXXConstructExprClass:
2836 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00002837 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00002838 case Expr::CXXTemporaryObjectExprClass:
2839 case Expr::CXXUnresolvedConstructExprClass:
2840 case Expr::CXXDependentScopeMemberExprClass:
2841 case Expr::UnresolvedMemberExprClass:
2842 case Expr::ObjCStringLiteralClass:
2843 case Expr::ObjCEncodeExprClass:
2844 case Expr::ObjCMessageExprClass:
2845 case Expr::ObjCSelectorExprClass:
2846 case Expr::ObjCProtocolExprClass:
2847 case Expr::ObjCIvarRefExprClass:
2848 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00002849 case Expr::ObjCIsaExprClass:
2850 case Expr::ShuffleVectorExprClass:
2851 case Expr::BlockExprClass:
2852 case Expr::BlockDeclRefExprClass:
2853 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00002854 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00002855 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00002856 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00002857 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00002858 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00002859 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002860 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00002861 return ICEDiag(2, E->getLocStart());
2862
Sebastian Redl12757ab2011-09-24 17:48:14 +00002863 case Expr::InitListExprClass:
2864 if (Ctx.getLangOptions().CPlusPlus0x) {
2865 const InitListExpr *ILE = cast<InitListExpr>(E);
2866 if (ILE->getNumInits() == 0)
2867 return NoDiag();
2868 if (ILE->getNumInits() == 1)
2869 return CheckICE(ILE->getInit(0), Ctx);
2870 // Fall through for more than 1 expression.
2871 }
2872 return ICEDiag(2, E->getLocStart());
2873
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002874 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00002875 case Expr::GNUNullExprClass:
2876 // GCC considers the GNU __null value to be an integral constant expression.
2877 return NoDiag();
2878
John McCall7c454bb2011-07-15 05:09:51 +00002879 case Expr::SubstNonTypeTemplateParmExprClass:
2880 return
2881 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2882
John McCall864e3962010-05-07 05:32:02 +00002883 case Expr::ParenExprClass:
2884 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002885 case Expr::GenericSelectionExprClass:
2886 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002887 case Expr::IntegerLiteralClass:
2888 case Expr::CharacterLiteralClass:
2889 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00002890 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00002891 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002892 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00002893 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00002894 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00002895 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00002896 return NoDiag();
2897 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00002898 case Expr::CXXOperatorCallExprClass: {
John McCall864e3962010-05-07 05:32:02 +00002899 const CallExpr *CE = cast<CallExpr>(E);
2900 if (CE->isBuiltinCall(Ctx))
2901 return CheckEvalInICE(E, Ctx);
2902 return ICEDiag(2, E->getLocStart());
2903 }
2904 case Expr::DeclRefExprClass:
2905 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2906 return NoDiag();
2907 if (Ctx.getLangOptions().CPlusPlus &&
2908 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2909 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2910
2911 // Parameter variables are never constants. Without this check,
2912 // getAnyInitializer() can find a default argument, which leads
2913 // to chaos.
2914 if (isa<ParmVarDecl>(D))
2915 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2916
2917 // C++ 7.1.5.1p2
2918 // A variable of non-volatile const-qualified integral or enumeration
2919 // type initialized by an ICE can be used in ICEs.
2920 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2921 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2922 if (Quals.hasVolatile() || !Quals.hasConst())
2923 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2924
2925 // Look for a declaration of this variable that has an initializer.
2926 const VarDecl *ID = 0;
2927 const Expr *Init = Dcl->getAnyInitializer(ID);
2928 if (Init) {
2929 if (ID->isInitKnownICE()) {
2930 // We have already checked whether this subexpression is an
2931 // integral constant expression.
2932 if (ID->isInitICE())
2933 return NoDiag();
2934 else
2935 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2936 }
2937
2938 // It's an ICE whether or not the definition we found is
2939 // out-of-line. See DR 721 and the discussion in Clang PR
2940 // 6206 for details.
2941
2942 if (Dcl->isCheckingICE()) {
2943 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2944 }
2945
2946 Dcl->setCheckingICE();
2947 ICEDiag Result = CheckICE(Init, Ctx);
2948 // Cache the result of the ICE test.
2949 Dcl->setInitKnownICE(Result.Val == 0);
2950 return Result;
2951 }
2952 }
2953 }
2954 return ICEDiag(2, E->getLocStart());
2955 case Expr::UnaryOperatorClass: {
2956 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2957 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002958 case UO_PostInc:
2959 case UO_PostDec:
2960 case UO_PreInc:
2961 case UO_PreDec:
2962 case UO_AddrOf:
2963 case UO_Deref:
John McCall864e3962010-05-07 05:32:02 +00002964 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00002965 case UO_Extension:
2966 case UO_LNot:
2967 case UO_Plus:
2968 case UO_Minus:
2969 case UO_Not:
2970 case UO_Real:
2971 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00002972 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002973 }
2974
2975 // OffsetOf falls through here.
2976 }
2977 case Expr::OffsetOfExprClass: {
2978 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2979 // Evaluate matches the proposed gcc behavior for cases like
2980 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2981 // compliance: we should warn earlier for offsetof expressions with
2982 // array subscripts that aren't ICEs, and if the array subscripts
2983 // are ICEs, the value of the offsetof must be an integer constant.
2984 return CheckEvalInICE(E, Ctx);
2985 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002986 case Expr::UnaryExprOrTypeTraitExprClass: {
2987 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2988 if ((Exp->getKind() == UETT_SizeOf) &&
2989 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00002990 return ICEDiag(2, E->getLocStart());
2991 return NoDiag();
2992 }
2993 case Expr::BinaryOperatorClass: {
2994 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2995 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002996 case BO_PtrMemD:
2997 case BO_PtrMemI:
2998 case BO_Assign:
2999 case BO_MulAssign:
3000 case BO_DivAssign:
3001 case BO_RemAssign:
3002 case BO_AddAssign:
3003 case BO_SubAssign:
3004 case BO_ShlAssign:
3005 case BO_ShrAssign:
3006 case BO_AndAssign:
3007 case BO_XorAssign:
3008 case BO_OrAssign:
John McCall864e3962010-05-07 05:32:02 +00003009 return ICEDiag(2, E->getLocStart());
3010
John McCalle3027922010-08-25 11:45:40 +00003011 case BO_Mul:
3012 case BO_Div:
3013 case BO_Rem:
3014 case BO_Add:
3015 case BO_Sub:
3016 case BO_Shl:
3017 case BO_Shr:
3018 case BO_LT:
3019 case BO_GT:
3020 case BO_LE:
3021 case BO_GE:
3022 case BO_EQ:
3023 case BO_NE:
3024 case BO_And:
3025 case BO_Xor:
3026 case BO_Or:
3027 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003028 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3029 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003030 if (Exp->getOpcode() == BO_Div ||
3031 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00003032 // Evaluate gives an error for undefined Div/Rem, so make sure
3033 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003034 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003035 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003036 if (REval == 0)
3037 return ICEDiag(1, E->getLocStart());
3038 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003039 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003040 if (LEval.isMinSignedValue())
3041 return ICEDiag(1, E->getLocStart());
3042 }
3043 }
3044 }
John McCalle3027922010-08-25 11:45:40 +00003045 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003046 if (Ctx.getLangOptions().C99) {
3047 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3048 // if it isn't evaluated.
3049 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3050 return ICEDiag(1, E->getLocStart());
3051 } else {
3052 // In both C89 and C++, commas in ICEs are illegal.
3053 return ICEDiag(2, E->getLocStart());
3054 }
3055 }
3056 if (LHSResult.Val >= RHSResult.Val)
3057 return LHSResult;
3058 return RHSResult;
3059 }
John McCalle3027922010-08-25 11:45:40 +00003060 case BO_LAnd:
3061 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003062 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003063
3064 // C++0x [expr.const]p2:
3065 // [...] subexpressions of logical AND (5.14), logical OR
3066 // (5.15), and condi- tional (5.16) operations that are not
3067 // evaluated are not considered.
3068 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3069 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003070 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003071 return LHSResult;
3072
3073 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003074 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003075 return LHSResult;
3076 }
3077
John McCall864e3962010-05-07 05:32:02 +00003078 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3079 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3080 // Rare case where the RHS has a comma "side-effect"; we need
3081 // to actually check the condition to see whether the side
3082 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003083 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003084 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003085 return RHSResult;
3086 return NoDiag();
3087 }
3088
3089 if (LHSResult.Val >= RHSResult.Val)
3090 return LHSResult;
3091 return RHSResult;
3092 }
3093 }
3094 }
3095 case Expr::ImplicitCastExprClass:
3096 case Expr::CStyleCastExprClass:
3097 case Expr::CXXFunctionalCastExprClass:
3098 case Expr::CXXStaticCastExprClass:
3099 case Expr::CXXReinterpretCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003100 case Expr::CXXConstCastExprClass:
3101 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003102 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman76d4e432011-09-29 21:49:34 +00003103 switch (cast<CastExpr>(E)->getCastKind()) {
3104 case CK_LValueToRValue:
3105 case CK_NoOp:
3106 case CK_IntegralToBoolean:
3107 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003108 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003109 default:
3110 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3111 return NoDiag();
3112 return ICEDiag(2, E->getLocStart());
3113 }
John McCall864e3962010-05-07 05:32:02 +00003114 }
John McCallc07a0c72011-02-17 10:25:35 +00003115 case Expr::BinaryConditionalOperatorClass: {
3116 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3117 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3118 if (CommonResult.Val == 2) return CommonResult;
3119 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3120 if (FalseResult.Val == 2) return FalseResult;
3121 if (CommonResult.Val == 1) return CommonResult;
3122 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003123 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003124 return FalseResult;
3125 }
John McCall864e3962010-05-07 05:32:02 +00003126 case Expr::ConditionalOperatorClass: {
3127 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3128 // If the condition (ignoring parens) is a __builtin_constant_p call,
3129 // then only the true side is actually considered in an integer constant
3130 // expression, and it is fully evaluated. This is an important GNU
3131 // extension. See GCC PR38377 for discussion.
3132 if (const CallExpr *CallCE
3133 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3134 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3135 Expr::EvalResult EVResult;
3136 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3137 !EVResult.Val.isInt()) {
3138 return ICEDiag(2, E->getLocStart());
3139 }
3140 return NoDiag();
3141 }
3142 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003143 if (CondResult.Val == 2)
3144 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003145
3146 // C++0x [expr.const]p2:
3147 // subexpressions of [...] conditional (5.16) operations that
3148 // are not evaluated are not considered
3149 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003150 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003151 : false;
3152 ICEDiag TrueResult = NoDiag();
3153 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3154 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3155 ICEDiag FalseResult = NoDiag();
3156 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3157 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3158
John McCall864e3962010-05-07 05:32:02 +00003159 if (TrueResult.Val == 2)
3160 return TrueResult;
3161 if (FalseResult.Val == 2)
3162 return FalseResult;
3163 if (CondResult.Val == 1)
3164 return CondResult;
3165 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3166 return NoDiag();
3167 // Rare case where the diagnostics depend on which side is evaluated
3168 // Note that if we get here, CondResult is 0, and at least one of
3169 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003170 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003171 return FalseResult;
3172 }
3173 return TrueResult;
3174 }
3175 case Expr::CXXDefaultArgExprClass:
3176 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3177 case Expr::ChooseExprClass: {
3178 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3179 }
3180 }
3181
3182 // Silence a GCC warning
3183 return ICEDiag(2, E->getLocStart());
3184}
3185
3186bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3187 SourceLocation *Loc, bool isEvaluated) const {
3188 ICEDiag d = CheckICE(this, Ctx);
3189 if (d.Val != 0) {
3190 if (Loc) *Loc = d.Loc;
3191 return false;
3192 }
3193 EvalResult EvalResult;
3194 if (!Evaluate(EvalResult, Ctx))
3195 llvm_unreachable("ICE cannot be evaluated!");
3196 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3197 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3198 Result = EvalResult.Val.getInt();
3199 return true;
3200}