blob: 1ff1430c9c3b2c5319d21a6bfb7d54b930c52a37 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Benjamin Kramerc54061a2011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
49 /// EvalResult - Contains information about the evaluation.
50 Expr::EvalResult &EvalResult;
51
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
61 : Ctx(ctx), EvalResult(evalresult) {}
62 };
63
John McCallf4cf1a12010-05-07 17:22:02 +000064 struct ComplexValue {
65 private:
66 bool IsInt;
67
68 public:
69 APSInt IntReal, IntImag;
70 APFloat FloatReal, FloatImag;
71
72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
73
74 void makeComplexFloat() { IsInt = false; }
75 bool isComplexFloat() const { return !IsInt; }
76 APFloat &getComplexFloatReal() { return FloatReal; }
77 APFloat &getComplexFloatImag() { return FloatImag; }
78
79 void makeComplexInt() { IsInt = true; }
80 bool isComplexInt() const { return IsInt; }
81 APSInt &getComplexIntReal() { return IntReal; }
82 APSInt &getComplexIntImag() { return IntImag; }
83
John McCall56ca35d2011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCall56ca35d2011-02-17 10:25:35 +000090 void setFrom(const APValue &v) {
91 assert(v.isComplexFloat() || v.isComplexInt());
92 if (v.isComplexFloat()) {
93 makeComplexFloat();
94 FloatReal = v.getComplexFloatReal();
95 FloatImag = v.getComplexFloatImag();
96 } else {
97 makeComplexInt();
98 IntReal = v.getComplexIntReal();
99 IntImag = v.getComplexIntImag();
100 }
101 }
John McCallf4cf1a12010-05-07 17:22:02 +0000102 };
John McCallefdb83e2010-05-07 21:00:08 +0000103
104 struct LValue {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000105 const Expr *Base;
John McCallefdb83e2010-05-07 21:00:08 +0000106 CharUnits Offset;
107
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000108 const Expr *getLValueBase() { return Base; }
John McCallefdb83e2010-05-07 21:00:08 +0000109 CharUnits getLValueOffset() { return Offset; }
110
John McCall56ca35d2011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCallefdb83e2010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCall56ca35d2011-02-17 10:25:35 +0000114 void setFrom(const APValue &v) {
115 assert(v.isLValue());
116 Base = v.getLValueBase();
117 Offset = v.getLValueOffset();
118 }
John McCallefdb83e2010-05-07 21:00:08 +0000119 };
John McCallf4cf1a12010-05-07 17:22:02 +0000120}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000121
John McCall56ca35d2011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000136 if (!E) return true;
137
138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
139 if (isa<FunctionDecl>(DRE->getDecl()))
140 return true;
141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
142 return VD->hasGlobalStorage();
143 return false;
144 }
145
146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
147 return CLE->isFileScope();
148
149 return true;
150}
151
John McCallefdb83e2010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000154
John McCall35542832010-05-07 21:34:32 +0000155 // A null base expression indicates a null pointer. These are always
156 // evaluatable, and they are false unless the offset is zero.
157 if (!Base) {
158 Result = !Value.Offset.isZero();
159 return true;
160 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000161
John McCall42c8f872010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000164
John McCall35542832010-05-07 21:34:32 +0000165 // We have a non-null base expression. These are generally known to
166 // be true, but if it'a decl-ref to a weak symbol it can be null at
167 // runtime.
John McCall35542832010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCall35542832010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman5bc86102009-06-14 02:17:33 +0000181 return true;
182}
183
John McCallcd7a4452010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000187 APSInt IntResult;
188 if (!EvaluateInteger(E, IntResult, Info))
189 return false;
190 Result = IntResult != 0;
191 return true;
192 } else if (E->getType()->isRealFloatingType()) {
193 APFloat FloatResult(0.0);
194 if (!EvaluateFloat(E, FloatResult, Info))
195 return false;
196 Result = !FloatResult.isZero();
197 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000205 if (!EvaluateComplex(E, ComplexResult, Info))
206 return false;
207 if (ComplexResult.isComplexFloat()) {
208 Result = !ComplexResult.getComplexFloatReal().isZero() ||
209 !ComplexResult.getComplexFloatImag().isZero();
210 } else {
211 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
212 ComplexResult.getComplexIntImag().getBoolValue();
213 }
214 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump1eb44332009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000224 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000227 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000228 bool ignored;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000229 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
230 return Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000231}
232
Mike Stump1eb44332009-09-09 15:08:12 +0000233static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000234 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000235 bool ignored;
236 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000237 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000238 APFloat::rmNearestTiesToEven, &ignored);
239 return Result;
240}
241
Mike Stump1eb44332009-09-09 15:08:12 +0000242static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000243 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000244 unsigned DestWidth = Ctx.getIntWidth(DestType);
245 APSInt Result = Value;
246 // Figure out if this is a truncate, extend or noop cast.
247 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000248 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000249 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000250 return Result;
251}
252
Mike Stump1eb44332009-09-09 15:08:12 +0000253static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000254 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000255
256 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
257 Result.convertFromAPInt(Value, Value.isSigned(),
258 APFloat::rmNearestTiesToEven);
259 return Result;
260}
261
Mike Stumpc4c90452009-10-27 22:09:17 +0000262namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000263class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000264 : public ConstStmtVisitor<HasSideEffect, bool> {
Mike Stumpc4c90452009-10-27 22:09:17 +0000265 EvalInfo &Info;
266public:
267
268 HasSideEffect(EvalInfo &info) : Info(info) {}
269
270 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000271 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +0000272 return true;
273 }
274
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000275 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
276 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000277 return Visit(E->getResultExpr());
278 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000279 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000280 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000281 return true;
282 return false;
283 }
John McCallf85e1932011-06-15 23:02:42 +0000284 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
285 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
286 return true;
287 return false;
288 }
289 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
290 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
291 return true;
292 return false;
293 }
294
Mike Stumpc4c90452009-10-27 22:09:17 +0000295 // We don't want to evaluate BlockExprs multiple times, as they generate
296 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000297 bool VisitBlockExpr(const BlockExpr *E) { return true; }
298 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
299 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000300 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000301 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
302 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
303 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
304 bool VisitStringLiteral(const StringLiteral *E) { return false; }
305 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
306 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000307 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000308 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000309 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000310 bool VisitChooseExpr(const ChooseExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000311 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000312 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
313 bool VisitBinAssign(const BinaryOperator *E) { return true; }
314 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
315 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +0000316 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000317 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
318 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
319 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
320 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
321 bool VisitUnaryDeref(const UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000322 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000323 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000324 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000325 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000326 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000327
328 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000329 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +0000330 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
331 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000332 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000333 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000334 return false;
335 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000336
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000337 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000338};
339
John McCall56ca35d2011-02-17 10:25:35 +0000340class OpaqueValueEvaluation {
341 EvalInfo &info;
342 OpaqueValueExpr *opaqueValue;
343
344public:
345 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
346 Expr *value)
347 : info(info), opaqueValue(opaqueValue) {
348
349 // If evaluation fails, fail immediately.
350 if (!Evaluate(info, value)) {
351 this->opaqueValue = 0;
352 return;
353 }
354 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
355 }
356
357 bool hasError() const { return opaqueValue == 0; }
358
359 ~OpaqueValueEvaluation() {
360 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
361 }
362};
363
Mike Stumpc4c90452009-10-27 22:09:17 +0000364} // end anonymous namespace
365
Eli Friedman4efaa272008-11-12 09:44:48 +0000366//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000367// Generic Evaluation
368//===----------------------------------------------------------------------===//
369namespace {
370
371template <class Derived, typename RetTy=void>
372class ExprEvaluatorBase
373 : public ConstStmtVisitor<Derived, RetTy> {
374private:
375 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
376 return static_cast<Derived*>(this)->Success(V, E);
377 }
378 RetTy DerivedError(const Expr *E) {
379 return static_cast<Derived*>(this)->Error(E);
380 }
381
382protected:
383 EvalInfo &Info;
384 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
385 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
386
387public:
388 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
389
390 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000391 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000392 }
393 RetTy VisitExpr(const Expr *E) {
394 return DerivedError(E);
395 }
396
397 RetTy VisitParenExpr(const ParenExpr *E)
398 { return StmtVisitorTy::Visit(E->getSubExpr()); }
399 RetTy VisitUnaryExtension(const UnaryOperator *E)
400 { return StmtVisitorTy::Visit(E->getSubExpr()); }
401 RetTy VisitUnaryPlus(const UnaryOperator *E)
402 { return StmtVisitorTy::Visit(E->getSubExpr()); }
403 RetTy VisitChooseExpr(const ChooseExpr *E)
404 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
405 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
406 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000407 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
408 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000409
410 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
411 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
412 if (opaque.hasError())
413 return DerivedError(E);
414
415 bool cond;
416 if (!HandleConversionToBool(E->getCond(), cond, Info))
417 return DerivedError(E);
418
419 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
420 }
421
422 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
423 bool BoolResult;
424 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
425 return DerivedError(E);
426
427 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
428 return StmtVisitorTy::Visit(EvalExpr);
429 }
430
431 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
432 const APValue *value = Info.getOpaqueValue(E);
433 if (!value)
434 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
435 : DerivedError(E));
436 return DerivedSuccess(*value, E);
437 }
438};
439
440}
441
442//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000443// LValue Evaluation
444//===----------------------------------------------------------------------===//
445namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000446class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000447 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000448 LValue &Result;
Chandler Carruth01248392011-08-22 17:24:56 +0000449 const Decl *PrevDecl;
John McCallefdb83e2010-05-07 21:00:08 +0000450
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000451 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000452 Result.Base = E;
453 Result.Offset = CharUnits::Zero();
454 return true;
455 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000456public:
Mike Stump1eb44332009-09-09 15:08:12 +0000457
John McCallefdb83e2010-05-07 21:00:08 +0000458 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth01248392011-08-22 17:24:56 +0000459 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000460
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000461 bool Success(const APValue &V, const Expr *E) {
462 Result.setFrom(V);
463 return true;
464 }
465 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000466 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000467 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000468
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000469 bool VisitDeclRefExpr(const DeclRefExpr *E);
470 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
471 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
472 bool VisitMemberExpr(const MemberExpr *E);
473 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
474 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
475 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
476 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +0000477
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000478 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000479 switch (E->getCastKind()) {
480 default:
John McCallefdb83e2010-05-07 21:00:08 +0000481 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000482
John McCall2de56d12010-08-25 11:45:40 +0000483 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000484 return Visit(E->getSubExpr());
485 }
486 }
Sebastian Redlcea8d962011-09-24 17:48:14 +0000487
488 bool VisitInitListExpr(const InitListExpr *E) {
489 if (Info.Ctx.getLangOptions().CPlusPlus0x && E->getNumInits() == 1)
490 return Visit(E->getInit(0));
491 return Error(E);
492 }
493
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000494 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000495
Eli Friedman4efaa272008-11-12 09:44:48 +0000496};
497} // end anonymous namespace
498
John McCallefdb83e2010-05-07 21:00:08 +0000499static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000500 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000501}
502
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000503bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000504 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000505 return Success(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000506 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000507 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000508 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000509 // Reference parameters can refer to anything even if they have an
510 // "initializer" in the form of a default argument.
Chandler Carruth01248392011-08-22 17:24:56 +0000511 if (!isa<ParmVarDecl>(VD)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000512 // FIXME: Check whether VD might be overridden!
Chandler Carruth01248392011-08-22 17:24:56 +0000513
514 // Check for recursive initializers of references.
515 if (PrevDecl == VD)
516 return Error(E);
517 PrevDecl = VD;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000518 if (const Expr *Init = VD->getAnyInitializer())
519 return Visit(Init);
Chandler Carruth01248392011-08-22 17:24:56 +0000520 }
Eli Friedman50c39ea2009-05-27 06:04:58 +0000521 }
522
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000523 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlsson35873c42008-11-24 04:41:22 +0000524}
525
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000526bool
527LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000528 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000529}
530
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000531bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000532 QualType Ty;
533 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000534 if (!EvaluatePointer(E->getBase(), Result, Info))
535 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000536 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000537 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000538 if (!Visit(E->getBase()))
539 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000540 Ty = E->getBase()->getType();
541 }
542
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000543 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000544 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000545
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000546 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor86f19402008-12-20 23:49:58 +0000547 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000548 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000549
550 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000551 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000552
Eli Friedman82905742011-07-07 01:54:01 +0000553 unsigned i = FD->getFieldIndex();
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000554 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000555 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000556}
557
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000558bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000559 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000560 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Anders Carlsson3068d112008-11-16 19:01:22 +0000562 APSInt Index;
563 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000564 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000565
Ken Dyck199c3d62010-01-11 17:06:35 +0000566 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000567 Result.Offset += Index.getSExtValue() * ElementSize;
568 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000569}
Eli Friedman4efaa272008-11-12 09:44:48 +0000570
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000571bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000572 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000573}
574
Eli Friedman4efaa272008-11-12 09:44:48 +0000575//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000576// Pointer Evaluation
577//===----------------------------------------------------------------------===//
578
Anders Carlssonc754aa62008-07-08 05:13:58 +0000579namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000580class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000581 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000582 LValue &Result;
583
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000584 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000585 Result.Base = E;
586 Result.Offset = CharUnits::Zero();
587 return true;
588 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000589public:
Mike Stump1eb44332009-09-09 15:08:12 +0000590
John McCallefdb83e2010-05-07 21:00:08 +0000591 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000592 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000593
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000594 bool Success(const APValue &V, const Expr *E) {
595 Result.setFrom(V);
596 return true;
597 }
598 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +0000599 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000600 }
601
John McCallefdb83e2010-05-07 21:00:08 +0000602 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000603 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +0000604 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000605 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +0000606 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000607 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000608 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000609 bool VisitCallExpr(const CallExpr *E);
610 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000611 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000612 return Success(E);
613 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000614 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000615 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000616 { return Success((Expr*)0); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000617 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000618 { return Success((Expr*)0); }
Peter Collingbourne620b9332011-09-27 17:33:05 +0000619 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E)
620 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000621
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000622 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000623};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000624} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000625
John McCallefdb83e2010-05-07 21:00:08 +0000626static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000627 assert(E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000628 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000629}
630
John McCallefdb83e2010-05-07 21:00:08 +0000631bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000632 if (E->getOpcode() != BO_Add &&
633 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000634 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000636 const Expr *PExp = E->getLHS();
637 const Expr *IExp = E->getRHS();
638 if (IExp->getType()->isPointerType())
639 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000640
John McCallefdb83e2010-05-07 21:00:08 +0000641 if (!EvaluatePointer(PExp, Result, Info))
642 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000643
John McCallefdb83e2010-05-07 21:00:08 +0000644 llvm::APSInt Offset;
645 if (!EvaluateInteger(IExp, Offset, Info))
646 return false;
647 int64_t AdditionalOffset
648 = Offset.isSigned() ? Offset.getSExtValue()
649 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000650
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000651 // Compute the new offset in the appropriate width.
652
653 QualType PointeeType =
654 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000655 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000657 // Explicitly handle GNU void* and function pointer arithmetic extensions.
658 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000659 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000660 else
John McCallefdb83e2010-05-07 21:00:08 +0000661 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000662
John McCall2de56d12010-08-25 11:45:40 +0000663 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000664 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000665 else
John McCallefdb83e2010-05-07 21:00:08 +0000666 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000667
John McCallefdb83e2010-05-07 21:00:08 +0000668 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000669}
Eli Friedman4efaa272008-11-12 09:44:48 +0000670
John McCallefdb83e2010-05-07 21:00:08 +0000671bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
672 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000673}
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000675
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000676bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
677 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000678
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000679 switch (E->getCastKind()) {
680 default:
681 break;
682
John McCall2de56d12010-08-25 11:45:40 +0000683 case CK_NoOp:
684 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +0000685 case CK_CPointerToObjCPointerCast:
686 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +0000687 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000688 return Visit(SubExpr);
689
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000690 case CK_DerivedToBase:
691 case CK_UncheckedDerivedToBase: {
692 LValue BaseLV;
693 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
694 return false;
695
696 // Now figure out the necessary offset to add to the baseLV to get from
697 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000698 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000699
700 QualType Ty = E->getSubExpr()->getType();
701 const CXXRecordDecl *DerivedDecl =
702 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
703
704 for (CastExpr::path_const_iterator PathI = E->path_begin(),
705 PathE = E->path_end(); PathI != PathE; ++PathI) {
706 const CXXBaseSpecifier *Base = *PathI;
707
708 // FIXME: If the base is virtual, we'd need to determine the type of the
709 // most derived class and we don't support that right now.
710 if (Base->isVirtual())
711 return false;
712
713 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
714 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
715
Ken Dyck7c7f8202011-01-26 02:17:08 +0000716 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000717 DerivedDecl = BaseDecl;
718 }
719
720 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000721 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000722 return true;
723 }
724
John McCall404cd162010-11-13 01:35:44 +0000725 case CK_NullToPointer: {
726 Result.Base = 0;
727 Result.Offset = CharUnits::Zero();
728 return true;
729 }
730
John McCall2de56d12010-08-25 11:45:40 +0000731 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000732 APValue Value;
733 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000734 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000735
John McCallefdb83e2010-05-07 21:00:08 +0000736 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000737 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000738 Result.Base = 0;
739 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
740 return true;
741 } else {
742 // Cast is of an lvalue, no need to change value.
743 Result.Base = Value.getLValueBase();
744 Result.Offset = Value.getLValueOffset();
745 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000746 }
747 }
John McCall2de56d12010-08-25 11:45:40 +0000748 case CK_ArrayToPointerDecay:
749 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000750 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000751 }
752
John McCallefdb83e2010-05-07 21:00:08 +0000753 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000754}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000755
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000756bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000757 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000758 Builtin::BI__builtin___CFStringMakeConstantString ||
759 E->isBuiltinCall(Info.Ctx) ==
760 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000761 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +0000762
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000763 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000764}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000765
766//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000767// Vector Evaluation
768//===----------------------------------------------------------------------===//
769
770namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000771 class VectorExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000772 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman91110ee2009-02-23 04:23:56 +0000773 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000774 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000776 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000778 APValue Success(const APValue &V, const Expr *E) { return V; }
779 APValue Error(const Expr *E) { return APValue(); }
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Eli Friedman91110ee2009-02-23 04:23:56 +0000781 APValue VisitUnaryReal(const UnaryOperator *E)
782 { return Visit(E->getSubExpr()); }
783 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
784 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000785 APValue VisitCastExpr(const CastExpr* E);
786 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
787 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000788 APValue VisitUnaryImag(const UnaryOperator *E);
789 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000790 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000791 // shufflevector, ExtVectorElementExpr
792 // (Note that these require implementing conversions
793 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000794 };
795} // end anonymous namespace
796
797static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
798 if (!E->getType()->isVectorType())
799 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000800 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +0000801 return !Result.isUninit();
802}
803
804APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000805 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000806 QualType EltTy = VTy->getElementType();
807 unsigned NElts = VTy->getNumElements();
808 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Nate Begeman59b5da62009-01-18 03:20:47 +0000810 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000811 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000812
Eli Friedman46a52322011-03-25 00:43:55 +0000813 switch (E->getCastKind()) {
814 case CK_VectorSplat: {
815 APValue Result = APValue();
816 if (SETy->isIntegerType()) {
817 APSInt IntResult;
818 if (!EvaluateInteger(SE, IntResult, Info))
819 return APValue();
820 Result = APValue(IntResult);
821 } else if (SETy->isRealFloatingType()) {
822 APFloat F(0.0);
823 if (!EvaluateFloat(SE, F, Info))
824 return APValue();
825 Result = APValue(F);
826 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000827 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000828 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000829
830 // Splat and create vector APValue.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000831 SmallVector<APValue, 4> Elts(NElts, Result);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000832 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000833 }
Eli Friedman46a52322011-03-25 00:43:55 +0000834 case CK_BitCast: {
835 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000836 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000837
Eli Friedman46a52322011-03-25 00:43:55 +0000838 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000839 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Eli Friedman46a52322011-03-25 00:43:55 +0000841 APSInt Init;
842 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000843 return APValue();
844
Eli Friedman46a52322011-03-25 00:43:55 +0000845 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
846 "Vectors must be composed of ints or floats");
847
Chris Lattner5f9e2722011-07-23 10:55:15 +0000848 SmallVector<APValue, 4> Elts;
Eli Friedman46a52322011-03-25 00:43:55 +0000849 for (unsigned i = 0; i != NElts; ++i) {
850 APSInt Tmp = Init.extOrTrunc(EltWidth);
851
852 if (EltTy->isIntegerType())
853 Elts.push_back(APValue(Tmp));
854 else
855 Elts.push_back(APValue(APFloat(Tmp)));
856
857 Init >>= EltWidth;
858 }
859 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000860 }
Eli Friedman46a52322011-03-25 00:43:55 +0000861 case CK_LValueToRValue:
862 case CK_NoOp:
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000863 return Visit(SE);
Eli Friedman46a52322011-03-25 00:43:55 +0000864 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000865 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000866 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000867}
868
Mike Stump1eb44332009-09-09 15:08:12 +0000869APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000870VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000871 return this->Visit(E->getInitializer());
Nate Begeman59b5da62009-01-18 03:20:47 +0000872}
873
Mike Stump1eb44332009-09-09 15:08:12 +0000874APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000875VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000876 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000877 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000878 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Nate Begeman59b5da62009-01-18 03:20:47 +0000880 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000881 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +0000882
John McCalla7d6c222010-06-11 17:54:15 +0000883 // If a vector is initialized with a single element, that value
884 // becomes every element of the vector, not just the first.
885 // This is the behavior described in the IBM AltiVec documentation.
886 if (NumInits == 1) {
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000887
888 // Handle the case where the vector is initialized by a another
889 // vector (OpenCL 6.1.6).
890 if (E->getInit(0)->getType()->isVectorType())
891 return this->Visit(const_cast<Expr*>(E->getInit(0)));
892
John McCalla7d6c222010-06-11 17:54:15 +0000893 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000894 if (EltTy->isIntegerType()) {
895 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000896 if (!EvaluateInteger(E->getInit(0), sInt, Info))
897 return APValue();
898 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000899 } else {
900 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000901 if (!EvaluateFloat(E->getInit(0), f, Info))
902 return APValue();
903 InitValue = APValue(f);
904 }
905 for (unsigned i = 0; i < NumElements; i++) {
906 Elements.push_back(InitValue);
907 }
908 } else {
909 for (unsigned i = 0; i < NumElements; i++) {
910 if (EltTy->isIntegerType()) {
911 llvm::APSInt sInt(32);
912 if (i < NumInits) {
913 if (!EvaluateInteger(E->getInit(i), sInt, Info))
914 return APValue();
915 } else {
916 sInt = Info.Ctx.MakeIntValue(0, EltTy);
917 }
918 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000919 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000920 llvm::APFloat f(0.0);
921 if (i < NumInits) {
922 if (!EvaluateFloat(E->getInit(i), f, Info))
923 return APValue();
924 } else {
925 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
926 }
927 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000928 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000929 }
930 }
931 return APValue(&Elements[0], Elements.size());
932}
933
Mike Stump1eb44332009-09-09 15:08:12 +0000934APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000935VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000936 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000937 QualType EltTy = VT->getElementType();
938 APValue ZeroElement;
939 if (EltTy->isIntegerType())
940 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
941 else
942 ZeroElement =
943 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
944
Chris Lattner5f9e2722011-07-23 10:55:15 +0000945 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Eli Friedman91110ee2009-02-23 04:23:56 +0000946 return APValue(&Elements[0], Elements.size());
947}
948
Eli Friedman91110ee2009-02-23 04:23:56 +0000949APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
950 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
951 Info.EvalResult.HasSideEffects = true;
952 return GetZeroVector(E->getType());
953}
954
Nate Begeman59b5da62009-01-18 03:20:47 +0000955//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000956// Integer Evaluation
957//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000958
959namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000960class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000961 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000962 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000963public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000964 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000965 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000966
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000967 bool Success(const llvm::APSInt &SI, const Expr *E) {
968 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000969 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000970 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000971 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000972 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000973 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000974 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000975 return true;
976 }
977
Daniel Dunbar131eb432009-02-19 09:06:44 +0000978 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000979 assert(E->getType()->isIntegralOrEnumerationType() &&
980 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000981 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000982 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000983 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +0000984 Result.getInt().setIsUnsigned(
985 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000986 return true;
987 }
988
989 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000990 assert(E->getType()->isIntegralOrEnumerationType() &&
991 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000992 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000993 return true;
994 }
995
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000996 bool Success(CharUnits Size, const Expr *E) {
997 return Success(Size.getQuantity(), E);
998 }
999
1000
Anders Carlsson82206e22008-11-30 18:14:57 +00001001 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001002 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +00001003 if (Info.EvalResult.Diag == 0) {
1004 Info.EvalResult.DiagLoc = L;
1005 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +00001006 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +00001007 }
Chris Lattner54176fd2008-07-12 00:14:42 +00001008 return false;
Chris Lattner7a767782008-07-11 19:24:49 +00001009 }
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001011 bool Success(const APValue &V, const Expr *E) {
1012 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00001013 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001014 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001015 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00001016 }
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001018 //===--------------------------------------------------------------------===//
1019 // Visitor Methods
1020 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00001021
Chris Lattner4c4867e2008-07-12 00:38:25 +00001022 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001023 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001024 }
1025 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001026 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001027 }
Eli Friedman04309752009-11-24 05:28:59 +00001028
1029 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1030 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001031 if (CheckReferencedDecl(E, E->getDecl()))
1032 return true;
1033
1034 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001035 }
1036 bool VisitMemberExpr(const MemberExpr *E) {
1037 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1038 // Conservatively assume a MemberExpr will have side-effects
1039 Info.EvalResult.HasSideEffects = true;
1040 return true;
1041 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001042
1043 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001044 }
1045
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001046 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001047 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001048 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001049 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001050
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001051 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001052 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001053
Anders Carlsson3068d112008-11-16 19:01:22 +00001054 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001055 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001056 }
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Anders Carlsson3f704562008-12-21 22:39:40 +00001058 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001059 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Douglas Gregored8abf12010-07-08 06:14:04 +00001062 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001063 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001064 }
1065
Eli Friedman664a1042009-02-27 04:45:43 +00001066 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1067 return Success(0, E);
1068 }
1069
Sebastian Redl64b45f72009-01-05 20:52:13 +00001070 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001071 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001072 }
1073
Francois Pichet6ad6f282010-12-07 00:08:36 +00001074 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1075 return Success(E->getValue(), E);
1076 }
1077
John Wiegley21ff2e52011-04-28 00:16:57 +00001078 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1079 return Success(E->getValue(), E);
1080 }
1081
John Wiegley55262202011-04-25 06:54:41 +00001082 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1083 return Success(E->getValue(), E);
1084 }
1085
Eli Friedman722c7172009-02-28 03:59:05 +00001086 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001087 bool VisitUnaryImag(const UnaryOperator *E);
1088
Sebastian Redl295995c2010-09-10 20:55:47 +00001089 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001090 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00001091
1092 bool VisitInitListExpr(const InitListExpr *E);
1093
Chris Lattnerfcee0012008-07-11 21:24:13 +00001094private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001095 CharUnits GetAlignOfExpr(const Expr *E);
1096 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001097 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001098 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001099 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001100};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001101} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001102
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001103static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001104 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001105 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001106}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001107
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001108static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001109 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001110
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001111 APValue Val;
1112 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1113 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001114 Result = Val.getInt();
1115 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001116}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001117
Eli Friedman04309752009-11-24 05:28:59 +00001118bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001119 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001120 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001121 // Check for signedness/width mismatches between E type and ECD value.
1122 bool SameSign = (ECD->getInitVal().isSigned()
1123 == E->getType()->isSignedIntegerOrEnumerationType());
1124 bool SameWidth = (ECD->getInitVal().getBitWidth()
1125 == Info.Ctx.getIntWidth(E->getType()));
1126 if (SameSign && SameWidth)
1127 return Success(ECD->getInitVal(), E);
1128 else {
1129 // Get rid of mismatch (otherwise Success assertions will fail)
1130 // by computing a new value matching the type of E.
1131 llvm::APSInt Val = ECD->getInitVal();
1132 if (!SameSign)
1133 Val.setIsSigned(!ECD->getInitVal().isSigned());
1134 if (!SameWidth)
1135 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1136 return Success(Val, E);
1137 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001138 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001139
1140 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001141 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001142 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1143 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001144
1145 if (isa<ParmVarDecl>(D))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001146 return false;
Anders Carlssonf6b60252010-02-03 21:58:41 +00001147
Eli Friedman04309752009-11-24 05:28:59 +00001148 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001149 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001150 if (APValue *V = VD->getEvaluatedValue()) {
1151 if (V->isInt())
1152 return Success(V->getInt(), E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001153 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001154 }
1155
1156 if (VD->isEvaluatingValue())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001157 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001158
1159 VD->setEvaluatingValue();
1160
Eli Friedmana7dedf72010-09-06 00:10:32 +00001161 Expr::EvalResult EResult;
1162 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1163 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001164 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001165 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001166 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001167 return true;
1168 }
1169
Eli Friedmanc0131182009-12-03 20:31:57 +00001170 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001171 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001172 }
1173 }
1174
Chris Lattner4c4867e2008-07-12 00:38:25 +00001175 // Otherwise, random variable references are not constants.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001176 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00001177}
1178
Chris Lattnera4d55d82008-10-06 06:40:35 +00001179/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1180/// as GCC.
1181static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1182 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001183 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001184 enum gcc_type_class {
1185 no_type_class = -1,
1186 void_type_class, integer_type_class, char_type_class,
1187 enumeral_type_class, boolean_type_class,
1188 pointer_type_class, reference_type_class, offset_type_class,
1189 real_type_class, complex_type_class,
1190 function_type_class, method_type_class,
1191 record_type_class, union_type_class,
1192 array_type_class, string_type_class,
1193 lang_type_class
1194 };
Mike Stump1eb44332009-09-09 15:08:12 +00001195
1196 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001197 // ideal, however it is what gcc does.
1198 if (E->getNumArgs() == 0)
1199 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Chris Lattnera4d55d82008-10-06 06:40:35 +00001201 QualType ArgTy = E->getArg(0)->getType();
1202 if (ArgTy->isVoidType())
1203 return void_type_class;
1204 else if (ArgTy->isEnumeralType())
1205 return enumeral_type_class;
1206 else if (ArgTy->isBooleanType())
1207 return boolean_type_class;
1208 else if (ArgTy->isCharType())
1209 return string_type_class; // gcc doesn't appear to use char_type_class
1210 else if (ArgTy->isIntegerType())
1211 return integer_type_class;
1212 else if (ArgTy->isPointerType())
1213 return pointer_type_class;
1214 else if (ArgTy->isReferenceType())
1215 return reference_type_class;
1216 else if (ArgTy->isRealType())
1217 return real_type_class;
1218 else if (ArgTy->isComplexType())
1219 return complex_type_class;
1220 else if (ArgTy->isFunctionType())
1221 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001222 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001223 return record_type_class;
1224 else if (ArgTy->isUnionType())
1225 return union_type_class;
1226 else if (ArgTy->isArrayType())
1227 return array_type_class;
1228 else if (ArgTy->isUnionType())
1229 return union_type_class;
1230 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00001231 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00001232 return -1;
1233}
1234
John McCall42c8f872010-05-10 23:27:23 +00001235/// Retrieves the "underlying object type" of the given expression,
1236/// as used by __builtin_object_size.
1237QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1238 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1239 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1240 return VD->getType();
1241 } else if (isa<CompoundLiteralExpr>(E)) {
1242 return E->getType();
1243 }
1244
1245 return QualType();
1246}
1247
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001248bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00001249 // TODO: Perhaps we should let LLVM lower this?
1250 LValue Base;
1251 if (!EvaluatePointer(E->getArg(0), Base, Info))
1252 return false;
1253
1254 // If we can prove the base is null, lower to zero now.
1255 const Expr *LVBase = Base.getLValueBase();
1256 if (!LVBase) return Success(0, E);
1257
1258 QualType T = GetObjectType(LVBase);
1259 if (T.isNull() ||
1260 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001261 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001262 T->isVariablyModifiedType() ||
1263 T->isDependentType())
1264 return false;
1265
1266 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1267 CharUnits Offset = Base.getLValueOffset();
1268
1269 if (!Offset.isNegative() && Offset <= Size)
1270 Size -= Offset;
1271 else
1272 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001273 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001274}
1275
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001276bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001277 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001278 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001279 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001280
1281 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001282 if (TryEvaluateBuiltinObjectSize(E))
1283 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001284
Eric Christopherb2aaf512010-01-19 22:58:35 +00001285 // If evaluating the argument has side-effects we can't determine
1286 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001287 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001288 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001289 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001290 return Success(0, E);
1291 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001292
Mike Stump64eda9e2009-10-26 18:35:08 +00001293 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1294 }
1295
Chris Lattner019f4e82008-10-06 05:28:25 +00001296 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001297 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001299 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001300 // __builtin_constant_p always has one operand: it returns true if that
1301 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001302 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001303
1304 case Builtin::BI__builtin_eh_return_data_regno: {
1305 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001306 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001307 return Success(Operand, E);
1308 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001309
1310 case Builtin::BI__builtin_expect:
1311 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001312
1313 case Builtin::BIstrlen:
1314 case Builtin::BI__builtin_strlen:
1315 // As an extension, we support strlen() and __builtin_strlen() as constant
1316 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001317 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00001318 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1319 // The string literal may have embedded null characters. Find the first
1320 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001321 StringRef Str = S->getString();
1322 StringRef::size_type Pos = Str.find(0);
1323 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00001324 Str = Str.substr(0, Pos);
1325
1326 return Success(Str.size(), E);
1327 }
1328
1329 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001330 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001331}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001332
Chris Lattnerb542afe2008-07-11 19:10:17 +00001333bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001334 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001335 if (!Visit(E->getRHS()))
1336 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001337
Eli Friedman33ef1452009-02-26 10:19:36 +00001338 // If we can't evaluate the LHS, it might have side effects;
1339 // conservatively mark it.
1340 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1341 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001342
Anders Carlsson027f62e2008-12-01 02:07:06 +00001343 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001344 }
1345
1346 if (E->isLogicalOp()) {
1347 // These need to be handled specially because the operands aren't
1348 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001349 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001351 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001352 // We were able to evaluate the LHS, see if we can get away with not
1353 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001354 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001355 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001356
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001357 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001358 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001359 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001360 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001361 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001362 }
1363 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001364 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001365 // We can't evaluate the LHS; however, sometimes the result
1366 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001367 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1368 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001369 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001370 // must have had side effects.
1371 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001372
1373 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001374 }
1375 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001376 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001377
Eli Friedmana6afa762008-11-13 06:09:17 +00001378 return false;
1379 }
1380
Anders Carlsson286f85e2008-11-16 07:17:21 +00001381 QualType LHSTy = E->getLHS()->getType();
1382 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001383
1384 if (LHSTy->isAnyComplexType()) {
1385 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001386 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001387
1388 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1389 return false;
1390
1391 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1392 return false;
1393
1394 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001395 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001396 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001397 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001398 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1399
John McCall2de56d12010-08-25 11:45:40 +00001400 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001401 return Success((CR_r == APFloat::cmpEqual &&
1402 CR_i == APFloat::cmpEqual), E);
1403 else {
John McCall2de56d12010-08-25 11:45:40 +00001404 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001405 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001406 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001407 CR_r == APFloat::cmpLessThan ||
1408 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001409 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001410 CR_i == APFloat::cmpLessThan ||
1411 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001412 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001413 } else {
John McCall2de56d12010-08-25 11:45:40 +00001414 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001415 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1416 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1417 else {
John McCall2de56d12010-08-25 11:45:40 +00001418 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001419 "Invalid compex comparison.");
1420 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1421 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1422 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001423 }
1424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Anders Carlsson286f85e2008-11-16 07:17:21 +00001426 if (LHSTy->isRealFloatingType() &&
1427 RHSTy->isRealFloatingType()) {
1428 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Anders Carlsson286f85e2008-11-16 07:17:21 +00001430 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1431 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Anders Carlsson286f85e2008-11-16 07:17:21 +00001433 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1434 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Anders Carlsson286f85e2008-11-16 07:17:21 +00001436 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001437
Anders Carlsson286f85e2008-11-16 07:17:21 +00001438 switch (E->getOpcode()) {
1439 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001440 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001441 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001442 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001443 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001444 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001445 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001446 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001447 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001448 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001449 E);
John McCall2de56d12010-08-25 11:45:40 +00001450 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001451 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001452 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001453 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001454 || CR == APFloat::cmpLessThan
1455 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001456 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001457 }
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001459 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001460 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001461 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001462 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1463 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001464
John McCallefdb83e2010-05-07 21:00:08 +00001465 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001466 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1467 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001468
Eli Friedman5bc86102009-06-14 02:17:33 +00001469 // Reject any bases from the normal codepath; we special-case comparisons
1470 // to null.
1471 if (LHSValue.getLValueBase()) {
1472 if (!E->isEqualityOp())
1473 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001474 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001475 return false;
1476 bool bres;
1477 if (!EvalPointerValueAsBool(LHSValue, bres))
1478 return false;
John McCall2de56d12010-08-25 11:45:40 +00001479 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001480 } else if (RHSValue.getLValueBase()) {
1481 if (!E->isEqualityOp())
1482 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001483 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001484 return false;
1485 bool bres;
1486 if (!EvalPointerValueAsBool(RHSValue, bres))
1487 return false;
John McCall2de56d12010-08-25 11:45:40 +00001488 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001489 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001490
John McCall2de56d12010-08-25 11:45:40 +00001491 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001492 QualType Type = E->getLHS()->getType();
1493 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001494
Ken Dycka7305832010-01-15 12:37:54 +00001495 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001496 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001497 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001498
Ken Dycka7305832010-01-15 12:37:54 +00001499 CharUnits Diff = LHSValue.getLValueOffset() -
1500 RHSValue.getLValueOffset();
1501 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001502 }
1503 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001504 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001505 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001506 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001507 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1508 }
1509 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001510 }
1511 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001512 if (!LHSTy->isIntegralOrEnumerationType() ||
1513 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001514 // We can't continue from here for non-integral types, and they
1515 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001516 return false;
1517 }
1518
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001519 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001520 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001521 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001522
Eli Friedman42edd0d2009-03-24 01:14:50 +00001523 APValue RHSVal;
1524 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001525 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001526
1527 // Handle cases like (unsigned long)&a + 4.
1528 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001529 CharUnits Offset = Result.getLValueOffset();
1530 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1531 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001532 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001533 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001534 else
Ken Dycka7305832010-01-15 12:37:54 +00001535 Offset -= AdditionalOffset;
1536 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001537 return true;
1538 }
1539
1540 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001541 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001542 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001543 CharUnits Offset = RHSVal.getLValueOffset();
1544 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1545 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001546 return true;
1547 }
1548
1549 // All the following cases expect both operands to be an integer
1550 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001551 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001552
Eli Friedman42edd0d2009-03-24 01:14:50 +00001553 APSInt& RHS = RHSVal.getInt();
1554
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001555 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001556 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001557 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001558 case BO_Mul: return Success(Result.getInt() * RHS, E);
1559 case BO_Add: return Success(Result.getInt() + RHS, E);
1560 case BO_Sub: return Success(Result.getInt() - RHS, E);
1561 case BO_And: return Success(Result.getInt() & RHS, E);
1562 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1563 case BO_Or: return Success(Result.getInt() | RHS, E);
1564 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001565 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001566 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001567 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001568 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001569 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001570 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001571 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001572 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001573 // During constant-folding, a negative shift is an opposite shift.
1574 if (RHS.isSigned() && RHS.isNegative()) {
1575 RHS = -RHS;
1576 goto shift_right;
1577 }
1578
1579 shift_left:
1580 unsigned SA
1581 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001582 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001583 }
John McCall2de56d12010-08-25 11:45:40 +00001584 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001585 // During constant-folding, a negative shift is an opposite shift.
1586 if (RHS.isSigned() && RHS.isNegative()) {
1587 RHS = -RHS;
1588 goto shift_left;
1589 }
1590
1591 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001592 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001593 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1594 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001595 }
Mike Stump1eb44332009-09-09 15:08:12 +00001596
John McCall2de56d12010-08-25 11:45:40 +00001597 case BO_LT: return Success(Result.getInt() < RHS, E);
1598 case BO_GT: return Success(Result.getInt() > RHS, E);
1599 case BO_LE: return Success(Result.getInt() <= RHS, E);
1600 case BO_GE: return Success(Result.getInt() >= RHS, E);
1601 case BO_EQ: return Success(Result.getInt() == RHS, E);
1602 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001603 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001604}
1605
Ken Dyck8b752f12010-01-27 17:10:57 +00001606CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001607 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1608 // the result is the size of the referenced type."
1609 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1610 // result shall be the alignment of the referenced type."
1611 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1612 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00001613
1614 // __alignof is defined to return the preferred alignment.
1615 return Info.Ctx.toCharUnitsFromBits(
1616 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001617}
1618
Ken Dyck8b752f12010-01-27 17:10:57 +00001619CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001620 E = E->IgnoreParens();
1621
1622 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001623 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001624 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001625 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1626 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001627
Chris Lattneraf707ab2009-01-24 21:53:27 +00001628 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001629 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1630 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001631
Chris Lattnere9feb472009-01-24 21:09:06 +00001632 return GetAlignOfType(E->getType());
1633}
1634
1635
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001636/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1637/// a result as the expression's type.
1638bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1639 const UnaryExprOrTypeTraitExpr *E) {
1640 switch(E->getKind()) {
1641 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001642 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001643 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001644 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001645 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001646 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001647
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001648 case UETT_VecStep: {
1649 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001650
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001651 if (Ty->isVectorType()) {
1652 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001653
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001654 // The vec_step built-in functions that take a 3-component
1655 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1656 if (n == 3)
1657 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001658
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001659 return Success(n, E);
1660 } else
1661 return Success(1, E);
1662 }
1663
1664 case UETT_SizeOf: {
1665 QualType SrcTy = E->getTypeOfArgument();
1666 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1667 // the result is the size of the referenced type."
1668 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1669 // result shall be the alignment of the referenced type."
1670 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1671 SrcTy = Ref->getPointeeType();
1672
1673 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1674 // extension.
1675 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1676 return Success(1, E);
1677
1678 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1679 if (!SrcTy->isConstantSizeType())
1680 return false;
1681
1682 // Get information about the size.
1683 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1684 }
1685 }
1686
1687 llvm_unreachable("unknown expr/type trait");
1688 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001689}
1690
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001691bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001692 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001693 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001694 if (n == 0)
1695 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001696 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001697 for (unsigned i = 0; i != n; ++i) {
1698 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1699 switch (ON.getKind()) {
1700 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001701 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001702 APSInt IdxResult;
1703 if (!EvaluateInteger(Idx, IdxResult, Info))
1704 return false;
1705 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1706 if (!AT)
1707 return false;
1708 CurrentType = AT->getElementType();
1709 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1710 Result += IdxResult.getSExtValue() * ElementSize;
1711 break;
1712 }
1713
1714 case OffsetOfExpr::OffsetOfNode::Field: {
1715 FieldDecl *MemberDecl = ON.getField();
1716 const RecordType *RT = CurrentType->getAs<RecordType>();
1717 if (!RT)
1718 return false;
1719 RecordDecl *RD = RT->getDecl();
1720 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001721 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001722 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001723 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001724 CurrentType = MemberDecl->getType().getNonReferenceType();
1725 break;
1726 }
1727
1728 case OffsetOfExpr::OffsetOfNode::Identifier:
1729 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001730 return false;
1731
1732 case OffsetOfExpr::OffsetOfNode::Base: {
1733 CXXBaseSpecifier *BaseSpec = ON.getBase();
1734 if (BaseSpec->isVirtual())
1735 return false;
1736
1737 // Find the layout of the class whose base we are looking into.
1738 const RecordType *RT = CurrentType->getAs<RecordType>();
1739 if (!RT)
1740 return false;
1741 RecordDecl *RD = RT->getDecl();
1742 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1743
1744 // Find the base class itself.
1745 CurrentType = BaseSpec->getType();
1746 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1747 if (!BaseRT)
1748 return false;
1749
1750 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001751 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001752 break;
1753 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001754 }
1755 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001756 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001757}
1758
Chris Lattnerb542afe2008-07-11 19:10:17 +00001759bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001760 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001761 // LNot's operand isn't necessarily an integer, so we handle it specially.
1762 bool bres;
1763 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1764 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001765 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001766 }
1767
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001768 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001769 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001770 return false;
1771
Chris Lattner87eae5e2008-07-11 22:52:41 +00001772 // Get the operand value into 'Result'.
1773 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001774 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001775
Chris Lattner75a48812008-07-11 22:15:16 +00001776 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001777 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001778 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1779 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001780 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001781 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001782 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1783 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001784 return true;
John McCall2de56d12010-08-25 11:45:40 +00001785 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001786 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001787 return true;
John McCall2de56d12010-08-25 11:45:40 +00001788 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001789 if (!Result.isInt()) return false;
1790 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001791 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001792 if (!Result.isInt()) return false;
1793 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001794 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001795}
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Chris Lattner732b2232008-07-12 01:15:53 +00001797/// HandleCast - This is used to evaluate implicit or explicit casts where the
1798/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001799bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1800 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00001801 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001802 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001803
Eli Friedman46a52322011-03-25 00:43:55 +00001804 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001805 case CK_BaseToDerived:
1806 case CK_DerivedToBase:
1807 case CK_UncheckedDerivedToBase:
1808 case CK_Dynamic:
1809 case CK_ToUnion:
1810 case CK_ArrayToPointerDecay:
1811 case CK_FunctionToPointerDecay:
1812 case CK_NullToPointer:
1813 case CK_NullToMemberPointer:
1814 case CK_BaseToDerivedMemberPointer:
1815 case CK_DerivedToBaseMemberPointer:
1816 case CK_ConstructorConversion:
1817 case CK_IntegralToPointer:
1818 case CK_ToVoid:
1819 case CK_VectorSplat:
1820 case CK_IntegralToFloating:
1821 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001822 case CK_CPointerToObjCPointerCast:
1823 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001824 case CK_AnyPointerToBlockPointerCast:
1825 case CK_ObjCObjectLValueCast:
1826 case CK_FloatingRealToComplex:
1827 case CK_FloatingComplexToReal:
1828 case CK_FloatingComplexCast:
1829 case CK_FloatingComplexToIntegralComplex:
1830 case CK_IntegralRealToComplex:
1831 case CK_IntegralComplexCast:
1832 case CK_IntegralComplexToFloatingComplex:
1833 llvm_unreachable("invalid cast kind for integral value");
1834
Eli Friedmane50c2972011-03-25 19:07:11 +00001835 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001836 case CK_Dependent:
1837 case CK_GetObjCProperty:
1838 case CK_LValueBitCast:
1839 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00001840 case CK_ARCProduceObject:
1841 case CK_ARCConsumeObject:
1842 case CK_ARCReclaimReturnedObject:
1843 case CK_ARCExtendBlockObject:
Eli Friedman46a52322011-03-25 00:43:55 +00001844 return false;
1845
1846 case CK_LValueToRValue:
1847 case CK_NoOp:
1848 return Visit(E->getSubExpr());
1849
1850 case CK_MemberPointerToBoolean:
1851 case CK_PointerToBoolean:
1852 case CK_IntegralToBoolean:
1853 case CK_FloatingToBoolean:
1854 case CK_FloatingComplexToBoolean:
1855 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001856 bool BoolResult;
1857 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1858 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001859 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001860 }
1861
Eli Friedman46a52322011-03-25 00:43:55 +00001862 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001863 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001864 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001865
Eli Friedmanbe265702009-02-20 01:15:07 +00001866 if (!Result.isInt()) {
1867 // Only allow casts of lvalues if they are lossless.
1868 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1869 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001870
Daniel Dunbardd211642009-02-19 22:24:01 +00001871 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001872 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001873 }
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Eli Friedman46a52322011-03-25 00:43:55 +00001875 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001876 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001877 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001878 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001879
Daniel Dunbardd211642009-02-19 22:24:01 +00001880 if (LV.getLValueBase()) {
1881 // Only allow based lvalue casts if they are lossless.
1882 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1883 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001884
John McCallefdb83e2010-05-07 21:00:08 +00001885 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001886 return true;
1887 }
1888
Ken Dycka7305832010-01-15 12:37:54 +00001889 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1890 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001891 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001892 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001893
Eli Friedman46a52322011-03-25 00:43:55 +00001894 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001895 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001896 if (!EvaluateComplex(SubExpr, C, Info))
1897 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001898 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001899 }
Eli Friedman2217c872009-02-22 11:46:18 +00001900
Eli Friedman46a52322011-03-25 00:43:55 +00001901 case CK_FloatingToIntegral: {
1902 APFloat F(0.0);
1903 if (!EvaluateFloat(SubExpr, F, Info))
1904 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001905
Eli Friedman46a52322011-03-25 00:43:55 +00001906 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1907 }
1908 }
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Eli Friedman46a52322011-03-25 00:43:55 +00001910 llvm_unreachable("unknown cast resulting in integral value");
1911 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001912}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001913
Eli Friedman722c7172009-02-28 03:59:05 +00001914bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1915 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001916 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001917 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1918 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1919 return Success(LV.getComplexIntReal(), E);
1920 }
1921
1922 return Visit(E->getSubExpr());
1923}
1924
Eli Friedman664a1042009-02-27 04:45:43 +00001925bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001926 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001927 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001928 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1929 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1930 return Success(LV.getComplexIntImag(), E);
1931 }
1932
Eli Friedman664a1042009-02-27 04:45:43 +00001933 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1934 Info.EvalResult.HasSideEffects = true;
1935 return Success(0, E);
1936}
1937
Douglas Gregoree8aff02011-01-04 17:33:58 +00001938bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1939 return Success(E->getPackLength(), E);
1940}
1941
Sebastian Redl295995c2010-09-10 20:55:47 +00001942bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1943 return Success(E->getValue(), E);
1944}
1945
Sebastian Redlcea8d962011-09-24 17:48:14 +00001946bool IntExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
1947 if (!Info.Ctx.getLangOptions().CPlusPlus0x)
1948 return Error(E);
1949
1950 if (E->getNumInits() == 0)
1951 return Success(0, E);
1952
1953 assert(E->getNumInits() == 1 && "Excess initializers for integer in C++11.");
1954 return Visit(E->getInit(0));
1955}
1956
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001957//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001958// Float Evaluation
1959//===----------------------------------------------------------------------===//
1960
1961namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001962class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001963 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001964 APFloat &Result;
1965public:
1966 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001967 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001968
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001969 bool Success(const APValue &V, const Expr *e) {
1970 Result = V.getFloat();
1971 return true;
1972 }
1973 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001974 return false;
1975 }
1976
Chris Lattner019f4e82008-10-06 05:28:25 +00001977 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001978
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001979 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001980 bool VisitBinaryOperator(const BinaryOperator *E);
1981 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001982 bool VisitCastExpr(const CastExpr *E);
1983 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001984
John McCallabd3a852010-05-07 22:08:54 +00001985 bool VisitUnaryReal(const UnaryOperator *E);
1986 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001987
John McCall189d6ef2010-10-09 01:34:31 +00001988 bool VisitDeclRefExpr(const DeclRefExpr *E);
1989
Sebastian Redlcea8d962011-09-24 17:48:14 +00001990 bool VisitInitListExpr(const InitListExpr *E);
1991
John McCallabd3a852010-05-07 22:08:54 +00001992 // FIXME: Missing: array subscript of vector, member of vector,
1993 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001994};
1995} // end anonymous namespace
1996
1997static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001998 assert(E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001999 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002000}
2001
Jay Foad4ba2a172011-01-12 09:06:06 +00002002static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00002003 QualType ResultTy,
2004 const Expr *Arg,
2005 bool SNaN,
2006 llvm::APFloat &Result) {
2007 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2008 if (!S) return false;
2009
2010 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2011
2012 llvm::APInt fill;
2013
2014 // Treat empty strings as if they were zero.
2015 if (S->getString().empty())
2016 fill = llvm::APInt(32, 0);
2017 else if (S->getString().getAsInteger(0, fill))
2018 return false;
2019
2020 if (SNaN)
2021 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2022 else
2023 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2024 return true;
2025}
2026
Chris Lattner019f4e82008-10-06 05:28:25 +00002027bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00002028 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002029 default:
2030 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2031
Chris Lattner019f4e82008-10-06 05:28:25 +00002032 case Builtin::BI__builtin_huge_val:
2033 case Builtin::BI__builtin_huge_valf:
2034 case Builtin::BI__builtin_huge_vall:
2035 case Builtin::BI__builtin_inf:
2036 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002037 case Builtin::BI__builtin_infl: {
2038 const llvm::fltSemantics &Sem =
2039 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002040 Result = llvm::APFloat::getInf(Sem);
2041 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002042 }
Mike Stump1eb44332009-09-09 15:08:12 +00002043
John McCalldb7b72a2010-02-28 13:00:19 +00002044 case Builtin::BI__builtin_nans:
2045 case Builtin::BI__builtin_nansf:
2046 case Builtin::BI__builtin_nansl:
2047 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2048 true, Result);
2049
Chris Lattner9e621712008-10-06 06:31:58 +00002050 case Builtin::BI__builtin_nan:
2051 case Builtin::BI__builtin_nanf:
2052 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002053 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002054 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002055 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2056 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002057
2058 case Builtin::BI__builtin_fabs:
2059 case Builtin::BI__builtin_fabsf:
2060 case Builtin::BI__builtin_fabsl:
2061 if (!EvaluateFloat(E->getArg(0), Result, Info))
2062 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002064 if (Result.isNegative())
2065 Result.changeSign();
2066 return true;
2067
Mike Stump1eb44332009-09-09 15:08:12 +00002068 case Builtin::BI__builtin_copysign:
2069 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002070 case Builtin::BI__builtin_copysignl: {
2071 APFloat RHS(0.);
2072 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2073 !EvaluateFloat(E->getArg(1), RHS, Info))
2074 return false;
2075 Result.copySign(RHS);
2076 return true;
2077 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002078 }
2079}
2080
John McCall189d6ef2010-10-09 01:34:31 +00002081bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002082 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2083 return true;
2084
John McCall189d6ef2010-10-09 01:34:31 +00002085 const Decl *D = E->getDecl();
2086 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2087 const VarDecl *VD = cast<VarDecl>(D);
2088
2089 // Require the qualifiers to be const and not volatile.
2090 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2091 if (!T.isConstQualified() || T.isVolatileQualified())
2092 return false;
2093
2094 const Expr *Init = VD->getAnyInitializer();
2095 if (!Init) return false;
2096
2097 if (APValue *V = VD->getEvaluatedValue()) {
2098 if (V->isFloat()) {
2099 Result = V->getFloat();
2100 return true;
2101 }
2102 return false;
2103 }
2104
2105 if (VD->isEvaluatingValue())
2106 return false;
2107
2108 VD->setEvaluatingValue();
2109
2110 Expr::EvalResult InitResult;
2111 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2112 InitResult.Val.isFloat()) {
2113 // Cache the evaluated value in the variable declaration.
2114 Result = InitResult.Val.getFloat();
2115 VD->setEvaluatedValue(InitResult.Val);
2116 return true;
2117 }
2118
2119 VD->setEvaluatedValue(APValue());
2120 return false;
2121}
2122
John McCallabd3a852010-05-07 22:08:54 +00002123bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002124 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2125 ComplexValue CV;
2126 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2127 return false;
2128 Result = CV.FloatReal;
2129 return true;
2130 }
2131
2132 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002133}
2134
2135bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002136 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2137 ComplexValue CV;
2138 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2139 return false;
2140 Result = CV.FloatImag;
2141 return true;
2142 }
2143
2144 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2145 Info.EvalResult.HasSideEffects = true;
2146 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2147 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002148 return true;
2149}
2150
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002151bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002152 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002153 return false;
2154
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002155 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2156 return false;
2157
2158 switch (E->getOpcode()) {
2159 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002160 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002161 return true;
John McCall2de56d12010-08-25 11:45:40 +00002162 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002163 Result.changeSign();
2164 return true;
2165 }
2166}
Chris Lattner019f4e82008-10-06 05:28:25 +00002167
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002168bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002169 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002170 if (!EvaluateFloat(E->getRHS(), Result, Info))
2171 return false;
2172
2173 // If we can't evaluate the LHS, it might have side effects;
2174 // conservatively mark it.
2175 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2176 Info.EvalResult.HasSideEffects = true;
2177
2178 return true;
2179 }
2180
Anders Carlsson96e93662010-10-31 01:21:47 +00002181 // We can't evaluate pointer-to-member operations.
2182 if (E->isPtrMemOp())
2183 return false;
2184
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002185 // FIXME: Diagnostics? I really don't understand how the warnings
2186 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002187 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002188 if (!EvaluateFloat(E->getLHS(), Result, Info))
2189 return false;
2190 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2191 return false;
2192
2193 switch (E->getOpcode()) {
2194 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002195 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002196 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2197 return true;
John McCall2de56d12010-08-25 11:45:40 +00002198 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002199 Result.add(RHS, APFloat::rmNearestTiesToEven);
2200 return true;
John McCall2de56d12010-08-25 11:45:40 +00002201 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002202 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2203 return true;
John McCall2de56d12010-08-25 11:45:40 +00002204 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002205 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2206 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002207 }
2208}
2209
2210bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2211 Result = E->getValue();
2212 return true;
2213}
2214
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002215bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2216 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Eli Friedman2a523ee2011-03-25 00:54:52 +00002218 switch (E->getCastKind()) {
2219 default:
2220 return false;
2221
2222 case CK_LValueToRValue:
2223 case CK_NoOp:
2224 return Visit(SubExpr);
2225
2226 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002227 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002228 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002229 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002230 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002231 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002232 return true;
2233 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002234
2235 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002236 if (!Visit(SubExpr))
2237 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002238 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2239 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002240 return true;
2241 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002242
Eli Friedman2a523ee2011-03-25 00:54:52 +00002243 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002244 ComplexValue V;
2245 if (!EvaluateComplex(SubExpr, V, Info))
2246 return false;
2247 Result = V.getComplexFloatReal();
2248 return true;
2249 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002250 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002251
2252 return false;
2253}
2254
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002255bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002256 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2257 return true;
2258}
2259
Sebastian Redlcea8d962011-09-24 17:48:14 +00002260bool FloatExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2261 if (!Info.Ctx.getLangOptions().CPlusPlus0x)
2262 return Error(E);
2263
2264 if (E->getNumInits() == 0) {
2265 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2266 return true;
2267 }
2268
2269 assert(E->getNumInits() == 1 && "Excess initializers for integer in C++11.");
2270 return Visit(E->getInit(0));
2271}
2272
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002273//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002274// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002275//===----------------------------------------------------------------------===//
2276
2277namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002278class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002279 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00002280 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002282public:
John McCallf4cf1a12010-05-07 17:22:02 +00002283 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002284 : ExprEvaluatorBaseTy(info), Result(Result) {}
2285
2286 bool Success(const APValue &V, const Expr *e) {
2287 Result.setFrom(V);
2288 return true;
2289 }
2290 bool Error(const Expr *E) {
2291 return false;
2292 }
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002294 //===--------------------------------------------------------------------===//
2295 // Visitor Methods
2296 //===--------------------------------------------------------------------===//
2297
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002298 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002300 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002301
John McCallf4cf1a12010-05-07 17:22:02 +00002302 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002303 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00002304 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002305};
2306} // end anonymous namespace
2307
John McCallf4cf1a12010-05-07 17:22:02 +00002308static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2309 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002310 assert(E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002311 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002312}
2313
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002314bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2315 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002316
2317 if (SubExpr->getType()->isRealFloatingType()) {
2318 Result.makeComplexFloat();
2319 APFloat &Imag = Result.FloatImag;
2320 if (!EvaluateFloat(SubExpr, Imag, Info))
2321 return false;
2322
2323 Result.FloatReal = APFloat(Imag.getSemantics());
2324 return true;
2325 } else {
2326 assert(SubExpr->getType()->isIntegerType() &&
2327 "Unexpected imaginary literal.");
2328
2329 Result.makeComplexInt();
2330 APSInt &Imag = Result.IntImag;
2331 if (!EvaluateInteger(SubExpr, Imag, Info))
2332 return false;
2333
2334 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2335 return true;
2336 }
2337}
2338
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002339bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002340
John McCall8786da72010-12-14 17:51:41 +00002341 switch (E->getCastKind()) {
2342 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002343 case CK_BaseToDerived:
2344 case CK_DerivedToBase:
2345 case CK_UncheckedDerivedToBase:
2346 case CK_Dynamic:
2347 case CK_ToUnion:
2348 case CK_ArrayToPointerDecay:
2349 case CK_FunctionToPointerDecay:
2350 case CK_NullToPointer:
2351 case CK_NullToMemberPointer:
2352 case CK_BaseToDerivedMemberPointer:
2353 case CK_DerivedToBaseMemberPointer:
2354 case CK_MemberPointerToBoolean:
2355 case CK_ConstructorConversion:
2356 case CK_IntegralToPointer:
2357 case CK_PointerToIntegral:
2358 case CK_PointerToBoolean:
2359 case CK_ToVoid:
2360 case CK_VectorSplat:
2361 case CK_IntegralCast:
2362 case CK_IntegralToBoolean:
2363 case CK_IntegralToFloating:
2364 case CK_FloatingToIntegral:
2365 case CK_FloatingToBoolean:
2366 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002367 case CK_CPointerToObjCPointerCast:
2368 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00002369 case CK_AnyPointerToBlockPointerCast:
2370 case CK_ObjCObjectLValueCast:
2371 case CK_FloatingComplexToReal:
2372 case CK_FloatingComplexToBoolean:
2373 case CK_IntegralComplexToReal:
2374 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00002375 case CK_ARCProduceObject:
2376 case CK_ARCConsumeObject:
2377 case CK_ARCReclaimReturnedObject:
2378 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00002379 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002380
John McCall8786da72010-12-14 17:51:41 +00002381 case CK_LValueToRValue:
2382 case CK_NoOp:
2383 return Visit(E->getSubExpr());
2384
2385 case CK_Dependent:
2386 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002387 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002388 case CK_UserDefinedConversion:
2389 return false;
2390
2391 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002392 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002393 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002394 return false;
2395
John McCall8786da72010-12-14 17:51:41 +00002396 Result.makeComplexFloat();
2397 Result.FloatImag = APFloat(Real.getSemantics());
2398 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002399 }
2400
John McCall8786da72010-12-14 17:51:41 +00002401 case CK_FloatingComplexCast: {
2402 if (!Visit(E->getSubExpr()))
2403 return false;
2404
2405 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2406 QualType From
2407 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2408
2409 Result.FloatReal
2410 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2411 Result.FloatImag
2412 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2413 return true;
2414 }
2415
2416 case CK_FloatingComplexToIntegralComplex: {
2417 if (!Visit(E->getSubExpr()))
2418 return false;
2419
2420 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2421 QualType From
2422 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2423 Result.makeComplexInt();
2424 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2425 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2426 return true;
2427 }
2428
2429 case CK_IntegralRealToComplex: {
2430 APSInt &Real = Result.IntReal;
2431 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2432 return false;
2433
2434 Result.makeComplexInt();
2435 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2436 return true;
2437 }
2438
2439 case CK_IntegralComplexCast: {
2440 if (!Visit(E->getSubExpr()))
2441 return false;
2442
2443 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2444 QualType From
2445 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2446
2447 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2448 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2449 return true;
2450 }
2451
2452 case CK_IntegralComplexToFloatingComplex: {
2453 if (!Visit(E->getSubExpr()))
2454 return false;
2455
2456 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2457 QualType From
2458 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2459 Result.makeComplexFloat();
2460 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2461 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2462 return true;
2463 }
2464 }
2465
2466 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002467 return false;
2468}
2469
John McCallf4cf1a12010-05-07 17:22:02 +00002470bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002471 if (E->getOpcode() == BO_Comma) {
2472 if (!Visit(E->getRHS()))
2473 return false;
2474
2475 // If we can't evaluate the LHS, it might have side effects;
2476 // conservatively mark it.
2477 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2478 Info.EvalResult.HasSideEffects = true;
2479
2480 return true;
2481 }
John McCallf4cf1a12010-05-07 17:22:02 +00002482 if (!Visit(E->getLHS()))
2483 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002484
John McCallf4cf1a12010-05-07 17:22:02 +00002485 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002486 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002487 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002488
Daniel Dunbar3f279872009-01-29 01:32:56 +00002489 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2490 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002491 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002492 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002493 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002494 if (Result.isComplexFloat()) {
2495 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2496 APFloat::rmNearestTiesToEven);
2497 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2498 APFloat::rmNearestTiesToEven);
2499 } else {
2500 Result.getComplexIntReal() += RHS.getComplexIntReal();
2501 Result.getComplexIntImag() += RHS.getComplexIntImag();
2502 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002503 break;
John McCall2de56d12010-08-25 11:45:40 +00002504 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002505 if (Result.isComplexFloat()) {
2506 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2507 APFloat::rmNearestTiesToEven);
2508 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2509 APFloat::rmNearestTiesToEven);
2510 } else {
2511 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2512 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2513 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002514 break;
John McCall2de56d12010-08-25 11:45:40 +00002515 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002516 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002517 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002518 APFloat &LHS_r = LHS.getComplexFloatReal();
2519 APFloat &LHS_i = LHS.getComplexFloatImag();
2520 APFloat &RHS_r = RHS.getComplexFloatReal();
2521 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002522
Daniel Dunbar3f279872009-01-29 01:32:56 +00002523 APFloat Tmp = LHS_r;
2524 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2525 Result.getComplexFloatReal() = Tmp;
2526 Tmp = LHS_i;
2527 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2528 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2529
2530 Tmp = LHS_r;
2531 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2532 Result.getComplexFloatImag() = Tmp;
2533 Tmp = LHS_i;
2534 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2535 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2536 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002537 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002538 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002539 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2540 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002541 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002542 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2543 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2544 }
2545 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002546 case BO_Div:
2547 if (Result.isComplexFloat()) {
2548 ComplexValue LHS = Result;
2549 APFloat &LHS_r = LHS.getComplexFloatReal();
2550 APFloat &LHS_i = LHS.getComplexFloatImag();
2551 APFloat &RHS_r = RHS.getComplexFloatReal();
2552 APFloat &RHS_i = RHS.getComplexFloatImag();
2553 APFloat &Res_r = Result.getComplexFloatReal();
2554 APFloat &Res_i = Result.getComplexFloatImag();
2555
2556 APFloat Den = RHS_r;
2557 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2558 APFloat Tmp = RHS_i;
2559 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2560 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2561
2562 Res_r = LHS_r;
2563 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2564 Tmp = LHS_i;
2565 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2566 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2567 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2568
2569 Res_i = LHS_i;
2570 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2571 Tmp = LHS_r;
2572 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2573 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2574 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2575 } else {
2576 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2577 // FIXME: what about diagnostics?
2578 return false;
2579 }
2580 ComplexValue LHS = Result;
2581 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2582 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2583 Result.getComplexIntReal() =
2584 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2585 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2586 Result.getComplexIntImag() =
2587 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2588 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2589 }
2590 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002591 }
2592
John McCallf4cf1a12010-05-07 17:22:02 +00002593 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002594}
2595
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002596bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2597 // Get the operand value into 'Result'.
2598 if (!Visit(E->getSubExpr()))
2599 return false;
2600
2601 switch (E->getOpcode()) {
2602 default:
2603 // FIXME: what about diagnostics?
2604 return false;
2605 case UO_Extension:
2606 return true;
2607 case UO_Plus:
2608 // The result is always just the subexpr.
2609 return true;
2610 case UO_Minus:
2611 if (Result.isComplexFloat()) {
2612 Result.getComplexFloatReal().changeSign();
2613 Result.getComplexFloatImag().changeSign();
2614 }
2615 else {
2616 Result.getComplexIntReal() = -Result.getComplexIntReal();
2617 Result.getComplexIntImag() = -Result.getComplexIntImag();
2618 }
2619 return true;
2620 case UO_Not:
2621 if (Result.isComplexFloat())
2622 Result.getComplexFloatImag().changeSign();
2623 else
2624 Result.getComplexIntImag() = -Result.getComplexIntImag();
2625 return true;
2626 }
2627}
2628
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002629//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002630// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002631//===----------------------------------------------------------------------===//
2632
John McCall56ca35d2011-02-17 10:25:35 +00002633static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002634 if (E->getType()->isVectorType()) {
2635 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002636 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00002637 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002638 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002639 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002640 if (Info.EvalResult.Val.isLValue() &&
2641 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002642 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002643 } else if (E->getType()->hasPointerRepresentation()) {
2644 LValue LV;
2645 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002646 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002647 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002648 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002649 LV.moveInto(Info.EvalResult.Val);
2650 } else if (E->getType()->isRealFloatingType()) {
2651 llvm::APFloat F(0.0);
2652 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002653 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002654
John McCallefdb83e2010-05-07 21:00:08 +00002655 Info.EvalResult.Val = APValue(F);
2656 } else if (E->getType()->isAnyComplexType()) {
2657 ComplexValue C;
2658 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002659 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002660 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002661 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002662 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002663
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002664 return true;
2665}
2666
John McCall56ca35d2011-02-17 10:25:35 +00002667/// Evaluate - Return true if this is a constant which we can fold using
2668/// any crazy technique (that has nothing to do with language standards) that
2669/// we want to. If this function returns true, it returns the folded constant
2670/// in Result.
2671bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2672 EvalInfo Info(Ctx, Result);
2673 return ::Evaluate(Info, this);
2674}
2675
Jay Foad4ba2a172011-01-12 09:06:06 +00002676bool Expr::EvaluateAsBooleanCondition(bool &Result,
2677 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002678 EvalResult Scratch;
2679 EvalInfo Info(Ctx, Scratch);
2680
2681 return HandleConversionToBool(this, Result, Info);
2682}
2683
Jay Foad4ba2a172011-01-12 09:06:06 +00002684bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002685 EvalInfo Info(Ctx, Result);
2686
John McCallefdb83e2010-05-07 21:00:08 +00002687 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002688 if (EvaluateLValue(this, LV, Info) &&
2689 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002690 IsGlobalLValue(LV.Base)) {
2691 LV.moveInto(Result.Val);
2692 return true;
2693 }
2694 return false;
2695}
2696
Jay Foad4ba2a172011-01-12 09:06:06 +00002697bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2698 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002699 EvalInfo Info(Ctx, Result);
2700
2701 LValue LV;
2702 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002703 LV.moveInto(Result.Val);
2704 return true;
2705 }
2706 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002707}
2708
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002709/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002710/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002711bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002712 EvalResult Result;
2713 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002714}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002715
Jay Foad4ba2a172011-01-12 09:06:06 +00002716bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002717 Expr::EvalResult Result;
2718 EvalInfo Info(Ctx, Result);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002719 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002720}
2721
Jay Foad4ba2a172011-01-12 09:06:06 +00002722APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002723 EvalResult EvalResult;
2724 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002725 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002726 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002727 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002728
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002729 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002730}
John McCalld905f5a2010-05-07 05:32:02 +00002731
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002732 bool Expr::EvalResult::isGlobalLValue() const {
2733 assert(Val.isLValue());
2734 return IsGlobalLValue(Val.getLValueBase());
2735 }
2736
2737
John McCalld905f5a2010-05-07 05:32:02 +00002738/// isIntegerConstantExpr - this recursive routine will test if an expression is
2739/// an integer constant expression.
2740
2741/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2742/// comma, etc
2743///
2744/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2745/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2746/// cast+dereference.
2747
2748// CheckICE - This function does the fundamental ICE checking: the returned
2749// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2750// Note that to reduce code duplication, this helper does no evaluation
2751// itself; the caller checks whether the expression is evaluatable, and
2752// in the rare cases where CheckICE actually cares about the evaluated
2753// value, it calls into Evalute.
2754//
2755// Meanings of Val:
2756// 0: This expression is an ICE if it can be evaluated by Evaluate.
2757// 1: This expression is not an ICE, but if it isn't evaluated, it's
2758// a legal subexpression for an ICE. This return value is used to handle
2759// the comma operator in C99 mode.
2760// 2: This expression is not an ICE, and is not a legal subexpression for one.
2761
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002762namespace {
2763
John McCalld905f5a2010-05-07 05:32:02 +00002764struct ICEDiag {
2765 unsigned Val;
2766 SourceLocation Loc;
2767
2768 public:
2769 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2770 ICEDiag() : Val(0) {}
2771};
2772
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002773}
2774
2775static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002776
2777static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2778 Expr::EvalResult EVResult;
2779 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2780 !EVResult.Val.isInt()) {
2781 return ICEDiag(2, E->getLocStart());
2782 }
2783 return NoDiag();
2784}
2785
2786static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2787 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002788 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002789 return ICEDiag(2, E->getLocStart());
2790 }
2791
2792 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002793#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002794#define STMT(Node, Base) case Expr::Node##Class:
2795#define EXPR(Node, Base)
2796#include "clang/AST/StmtNodes.inc"
2797 case Expr::PredefinedExprClass:
2798 case Expr::FloatingLiteralClass:
2799 case Expr::ImaginaryLiteralClass:
2800 case Expr::StringLiteralClass:
2801 case Expr::ArraySubscriptExprClass:
2802 case Expr::MemberExprClass:
2803 case Expr::CompoundAssignOperatorClass:
2804 case Expr::CompoundLiteralExprClass:
2805 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002806 case Expr::DesignatedInitExprClass:
2807 case Expr::ImplicitValueInitExprClass:
2808 case Expr::ParenListExprClass:
2809 case Expr::VAArgExprClass:
2810 case Expr::AddrLabelExprClass:
2811 case Expr::StmtExprClass:
2812 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002813 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002814 case Expr::CXXDynamicCastExprClass:
2815 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002816 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002817 case Expr::CXXNullPtrLiteralExprClass:
2818 case Expr::CXXThisExprClass:
2819 case Expr::CXXThrowExprClass:
2820 case Expr::CXXNewExprClass:
2821 case Expr::CXXDeleteExprClass:
2822 case Expr::CXXPseudoDestructorExprClass:
2823 case Expr::UnresolvedLookupExprClass:
2824 case Expr::DependentScopeDeclRefExprClass:
2825 case Expr::CXXConstructExprClass:
2826 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002827 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002828 case Expr::CXXTemporaryObjectExprClass:
2829 case Expr::CXXUnresolvedConstructExprClass:
2830 case Expr::CXXDependentScopeMemberExprClass:
2831 case Expr::UnresolvedMemberExprClass:
2832 case Expr::ObjCStringLiteralClass:
2833 case Expr::ObjCEncodeExprClass:
2834 case Expr::ObjCMessageExprClass:
2835 case Expr::ObjCSelectorExprClass:
2836 case Expr::ObjCProtocolExprClass:
2837 case Expr::ObjCIvarRefExprClass:
2838 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002839 case Expr::ObjCIsaExprClass:
2840 case Expr::ShuffleVectorExprClass:
2841 case Expr::BlockExprClass:
2842 case Expr::BlockDeclRefExprClass:
2843 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002844 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002845 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002846 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002847 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002848 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00002849 case Expr::MaterializeTemporaryExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002850 return ICEDiag(2, E->getLocStart());
2851
Sebastian Redlcea8d962011-09-24 17:48:14 +00002852 case Expr::InitListExprClass:
2853 if (Ctx.getLangOptions().CPlusPlus0x) {
2854 const InitListExpr *ILE = cast<InitListExpr>(E);
2855 if (ILE->getNumInits() == 0)
2856 return NoDiag();
2857 if (ILE->getNumInits() == 1)
2858 return CheckICE(ILE->getInit(0), Ctx);
2859 // Fall through for more than 1 expression.
2860 }
2861 return ICEDiag(2, E->getLocStart());
2862
Douglas Gregoree8aff02011-01-04 17:33:58 +00002863 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002864 case Expr::GNUNullExprClass:
2865 // GCC considers the GNU __null value to be an integral constant expression.
2866 return NoDiag();
2867
John McCall91a57552011-07-15 05:09:51 +00002868 case Expr::SubstNonTypeTemplateParmExprClass:
2869 return
2870 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2871
John McCalld905f5a2010-05-07 05:32:02 +00002872 case Expr::ParenExprClass:
2873 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002874 case Expr::GenericSelectionExprClass:
2875 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002876 case Expr::IntegerLiteralClass:
2877 case Expr::CharacterLiteralClass:
2878 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002879 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002880 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002881 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00002882 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00002883 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002884 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002885 return NoDiag();
2886 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002887 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002888 const CallExpr *CE = cast<CallExpr>(E);
2889 if (CE->isBuiltinCall(Ctx))
2890 return CheckEvalInICE(E, Ctx);
2891 return ICEDiag(2, E->getLocStart());
2892 }
2893 case Expr::DeclRefExprClass:
2894 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2895 return NoDiag();
2896 if (Ctx.getLangOptions().CPlusPlus &&
2897 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2898 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2899
2900 // Parameter variables are never constants. Without this check,
2901 // getAnyInitializer() can find a default argument, which leads
2902 // to chaos.
2903 if (isa<ParmVarDecl>(D))
2904 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2905
2906 // C++ 7.1.5.1p2
2907 // A variable of non-volatile const-qualified integral or enumeration
2908 // type initialized by an ICE can be used in ICEs.
2909 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2910 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2911 if (Quals.hasVolatile() || !Quals.hasConst())
2912 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2913
2914 // Look for a declaration of this variable that has an initializer.
2915 const VarDecl *ID = 0;
2916 const Expr *Init = Dcl->getAnyInitializer(ID);
2917 if (Init) {
2918 if (ID->isInitKnownICE()) {
2919 // We have already checked whether this subexpression is an
2920 // integral constant expression.
2921 if (ID->isInitICE())
2922 return NoDiag();
2923 else
2924 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2925 }
2926
2927 // It's an ICE whether or not the definition we found is
2928 // out-of-line. See DR 721 and the discussion in Clang PR
2929 // 6206 for details.
2930
2931 if (Dcl->isCheckingICE()) {
2932 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2933 }
2934
2935 Dcl->setCheckingICE();
2936 ICEDiag Result = CheckICE(Init, Ctx);
2937 // Cache the result of the ICE test.
2938 Dcl->setInitKnownICE(Result.Val == 0);
2939 return Result;
2940 }
2941 }
2942 }
2943 return ICEDiag(2, E->getLocStart());
2944 case Expr::UnaryOperatorClass: {
2945 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2946 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002947 case UO_PostInc:
2948 case UO_PostDec:
2949 case UO_PreInc:
2950 case UO_PreDec:
2951 case UO_AddrOf:
2952 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002953 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002954 case UO_Extension:
2955 case UO_LNot:
2956 case UO_Plus:
2957 case UO_Minus:
2958 case UO_Not:
2959 case UO_Real:
2960 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002961 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002962 }
2963
2964 // OffsetOf falls through here.
2965 }
2966 case Expr::OffsetOfExprClass: {
2967 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2968 // Evaluate matches the proposed gcc behavior for cases like
2969 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2970 // compliance: we should warn earlier for offsetof expressions with
2971 // array subscripts that aren't ICEs, and if the array subscripts
2972 // are ICEs, the value of the offsetof must be an integer constant.
2973 return CheckEvalInICE(E, Ctx);
2974 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002975 case Expr::UnaryExprOrTypeTraitExprClass: {
2976 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2977 if ((Exp->getKind() == UETT_SizeOf) &&
2978 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002979 return ICEDiag(2, E->getLocStart());
2980 return NoDiag();
2981 }
2982 case Expr::BinaryOperatorClass: {
2983 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2984 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002985 case BO_PtrMemD:
2986 case BO_PtrMemI:
2987 case BO_Assign:
2988 case BO_MulAssign:
2989 case BO_DivAssign:
2990 case BO_RemAssign:
2991 case BO_AddAssign:
2992 case BO_SubAssign:
2993 case BO_ShlAssign:
2994 case BO_ShrAssign:
2995 case BO_AndAssign:
2996 case BO_XorAssign:
2997 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002998 return ICEDiag(2, E->getLocStart());
2999
John McCall2de56d12010-08-25 11:45:40 +00003000 case BO_Mul:
3001 case BO_Div:
3002 case BO_Rem:
3003 case BO_Add:
3004 case BO_Sub:
3005 case BO_Shl:
3006 case BO_Shr:
3007 case BO_LT:
3008 case BO_GT:
3009 case BO_LE:
3010 case BO_GE:
3011 case BO_EQ:
3012 case BO_NE:
3013 case BO_And:
3014 case BO_Xor:
3015 case BO_Or:
3016 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00003017 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3018 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00003019 if (Exp->getOpcode() == BO_Div ||
3020 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00003021 // Evaluate gives an error for undefined Div/Rem, so make sure
3022 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00003023 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00003024 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
3025 if (REval == 0)
3026 return ICEDiag(1, E->getLocStart());
3027 if (REval.isSigned() && REval.isAllOnesValue()) {
3028 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
3029 if (LEval.isMinSignedValue())
3030 return ICEDiag(1, E->getLocStart());
3031 }
3032 }
3033 }
John McCall2de56d12010-08-25 11:45:40 +00003034 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00003035 if (Ctx.getLangOptions().C99) {
3036 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3037 // if it isn't evaluated.
3038 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3039 return ICEDiag(1, E->getLocStart());
3040 } else {
3041 // In both C89 and C++, commas in ICEs are illegal.
3042 return ICEDiag(2, E->getLocStart());
3043 }
3044 }
3045 if (LHSResult.Val >= RHSResult.Val)
3046 return LHSResult;
3047 return RHSResult;
3048 }
John McCall2de56d12010-08-25 11:45:40 +00003049 case BO_LAnd:
3050 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00003051 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00003052
3053 // C++0x [expr.const]p2:
3054 // [...] subexpressions of logical AND (5.14), logical OR
3055 // (5.15), and condi- tional (5.16) operations that are not
3056 // evaluated are not considered.
3057 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3058 if (Exp->getOpcode() == BO_LAnd &&
3059 Exp->getLHS()->EvaluateAsInt(Ctx) == 0)
3060 return LHSResult;
3061
3062 if (Exp->getOpcode() == BO_LOr &&
3063 Exp->getLHS()->EvaluateAsInt(Ctx) != 0)
3064 return LHSResult;
3065 }
3066
John McCalld905f5a2010-05-07 05:32:02 +00003067 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3068 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3069 // Rare case where the RHS has a comma "side-effect"; we need
3070 // to actually check the condition to see whether the side
3071 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003072 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00003073 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3074 return RHSResult;
3075 return NoDiag();
3076 }
3077
3078 if (LHSResult.Val >= RHSResult.Val)
3079 return LHSResult;
3080 return RHSResult;
3081 }
3082 }
3083 }
3084 case Expr::ImplicitCastExprClass:
3085 case Expr::CStyleCastExprClass:
3086 case Expr::CXXFunctionalCastExprClass:
3087 case Expr::CXXStaticCastExprClass:
3088 case Expr::CXXReinterpretCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003089 case Expr::CXXConstCastExprClass:
3090 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00003091 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003092 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003093 return CheckICE(SubExpr, Ctx);
3094 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3095 return NoDiag();
3096 return ICEDiag(2, E->getLocStart());
3097 }
John McCall56ca35d2011-02-17 10:25:35 +00003098 case Expr::BinaryConditionalOperatorClass: {
3099 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3100 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3101 if (CommonResult.Val == 2) return CommonResult;
3102 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3103 if (FalseResult.Val == 2) return FalseResult;
3104 if (CommonResult.Val == 1) return CommonResult;
3105 if (FalseResult.Val == 1 &&
3106 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3107 return FalseResult;
3108 }
John McCalld905f5a2010-05-07 05:32:02 +00003109 case Expr::ConditionalOperatorClass: {
3110 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3111 // If the condition (ignoring parens) is a __builtin_constant_p call,
3112 // then only the true side is actually considered in an integer constant
3113 // expression, and it is fully evaluated. This is an important GNU
3114 // extension. See GCC PR38377 for discussion.
3115 if (const CallExpr *CallCE
3116 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3117 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3118 Expr::EvalResult EVResult;
3119 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3120 !EVResult.Val.isInt()) {
3121 return ICEDiag(2, E->getLocStart());
3122 }
3123 return NoDiag();
3124 }
3125 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003126 if (CondResult.Val == 2)
3127 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00003128
3129 // C++0x [expr.const]p2:
3130 // subexpressions of [...] conditional (5.16) operations that
3131 // are not evaluated are not considered
3132 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
3133 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0
3134 : false;
3135 ICEDiag TrueResult = NoDiag();
3136 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3137 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3138 ICEDiag FalseResult = NoDiag();
3139 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3140 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3141
John McCalld905f5a2010-05-07 05:32:02 +00003142 if (TrueResult.Val == 2)
3143 return TrueResult;
3144 if (FalseResult.Val == 2)
3145 return FalseResult;
3146 if (CondResult.Val == 1)
3147 return CondResult;
3148 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3149 return NoDiag();
3150 // Rare case where the diagnostics depend on which side is evaluated
3151 // Note that if we get here, CondResult is 0, and at least one of
3152 // TrueResult and FalseResult is non-zero.
3153 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3154 return FalseResult;
3155 }
3156 return TrueResult;
3157 }
3158 case Expr::CXXDefaultArgExprClass:
3159 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3160 case Expr::ChooseExprClass: {
3161 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3162 }
3163 }
3164
3165 // Silence a GCC warning
3166 return ICEDiag(2, E->getLocStart());
3167}
3168
3169bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3170 SourceLocation *Loc, bool isEvaluated) const {
3171 ICEDiag d = CheckICE(this, Ctx);
3172 if (d.Val != 0) {
3173 if (Loc) *Loc = d.Loc;
3174 return false;
3175 }
3176 EvalResult EvalResult;
3177 if (!Evaluate(EvalResult, Ctx))
3178 llvm_unreachable("ICE cannot be evaluated!");
3179 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3180 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3181 Result = EvalResult.Val.getInt();
3182 return true;
3183}