blob: c3cc78e053ccf3227d2fc63422156390bfa1e19a [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Benjamin Kramer024e6192011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
Richard Smith725810a2011-10-16 21:26:27 +000049 /// EvalStatus - Contains information about the evaluation.
50 Expr::EvalStatus &EvalStatus;
Benjamin Kramer024e6192011-03-04 13:12:48 +000051
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
Richard Smith725810a2011-10-16 21:26:27 +000060 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
61 : Ctx(C), EvalStatus(S) {}
Richard Smith4ce706a2011-10-11 21:43:33 +000062
63 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
Benjamin Kramer024e6192011-03-04 13:12:48 +000064 };
65
John McCall93d91dc2010-05-07 17:22:02 +000066 struct ComplexValue {
67 private:
68 bool IsInt;
69
70 public:
71 APSInt IntReal, IntImag;
72 APFloat FloatReal, FloatImag;
73
74 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
75
76 void makeComplexFloat() { IsInt = false; }
77 bool isComplexFloat() const { return !IsInt; }
78 APFloat &getComplexFloatReal() { return FloatReal; }
79 APFloat &getComplexFloatImag() { return FloatImag; }
80
81 void makeComplexInt() { IsInt = true; }
82 bool isComplexInt() const { return IsInt; }
83 APSInt &getComplexIntReal() { return IntReal; }
84 APSInt &getComplexIntImag() { return IntImag; }
85
John McCallc07a0c72011-02-17 10:25:35 +000086 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +000087 if (isComplexFloat())
88 v = APValue(FloatReal, FloatImag);
89 else
90 v = APValue(IntReal, IntImag);
91 }
John McCallc07a0c72011-02-17 10:25:35 +000092 void setFrom(const APValue &v) {
93 assert(v.isComplexFloat() || v.isComplexInt());
94 if (v.isComplexFloat()) {
95 makeComplexFloat();
96 FloatReal = v.getComplexFloatReal();
97 FloatImag = v.getComplexFloatImag();
98 } else {
99 makeComplexInt();
100 IntReal = v.getComplexIntReal();
101 IntImag = v.getComplexIntImag();
102 }
103 }
John McCall93d91dc2010-05-07 17:22:02 +0000104 };
John McCall45d55e42010-05-07 21:00:08 +0000105
106 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000107 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000108 CharUnits Offset;
109
Peter Collingbournee9200682011-05-13 03:29:01 +0000110 const Expr *getLValueBase() { return Base; }
John McCall45d55e42010-05-07 21:00:08 +0000111 CharUnits getLValueOffset() { return Offset; }
112
John McCallc07a0c72011-02-17 10:25:35 +0000113 void moveInto(APValue &v) const {
John McCall45d55e42010-05-07 21:00:08 +0000114 v = APValue(Base, Offset);
115 }
John McCallc07a0c72011-02-17 10:25:35 +0000116 void setFrom(const APValue &v) {
117 assert(v.isLValue());
118 Base = v.getLValueBase();
119 Offset = v.getLValueOffset();
120 }
John McCall45d55e42010-05-07 21:00:08 +0000121 };
John McCall93d91dc2010-05-07 17:22:02 +0000122}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000123
Richard Smith725810a2011-10-16 21:26:27 +0000124static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000125static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
126static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000127static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattner6c4d2552009-10-28 23:59:40 +0000128static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
129 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000130static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000131static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000132
133//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000134// Misc utilities
135//===----------------------------------------------------------------------===//
136
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000137static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000138 if (!E) return true;
139
140 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
141 if (isa<FunctionDecl>(DRE->getDecl()))
142 return true;
143 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
144 return VD->hasGlobalStorage();
145 return false;
146 }
147
148 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
149 return CLE->isFileScope();
150
151 return true;
152}
153
John McCall45d55e42010-05-07 21:00:08 +0000154static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
155 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000156
John McCalleb3e4f32010-05-07 21:34:32 +0000157 // A null base expression indicates a null pointer. These are always
158 // evaluatable, and they are false unless the offset is zero.
159 if (!Base) {
160 Result = !Value.Offset.isZero();
161 return true;
162 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000163
John McCall95007602010-05-10 23:27:23 +0000164 // Require the base expression to be a global l-value.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000165 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000166
John McCalleb3e4f32010-05-07 21:34:32 +0000167 // We have a non-null base expression. These are generally known to
168 // be true, but if it'a decl-ref to a weak symbol it can be null at
169 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000170 Result = true;
171
172 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000173 if (!DeclRef)
174 return true;
175
John McCalleb3e4f32010-05-07 21:34:32 +0000176 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000177 const ValueDecl* Decl = DeclRef->getDecl();
178 if (Decl->hasAttr<WeakAttr>() ||
179 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000180 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000181 return false;
182
Eli Friedman334046a2009-06-14 02:17:33 +0000183 return true;
184}
185
John McCall1be1c632010-01-05 23:42:56 +0000186static bool HandleConversionToBool(const Expr* E, bool& Result,
187 EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000188 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000189 APSInt IntResult;
190 if (!EvaluateInteger(E, IntResult, Info))
191 return false;
192 Result = IntResult != 0;
193 return true;
194 } else if (E->getType()->isRealFloatingType()) {
195 APFloat FloatResult(0.0);
196 if (!EvaluateFloat(E, FloatResult, Info))
197 return false;
198 Result = !FloatResult.isZero();
199 return true;
Eli Friedman64004332009-03-23 04:38:34 +0000200 } else if (E->getType()->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +0000201 LValue PointerResult;
Eli Friedman9a156e52008-11-12 09:44:48 +0000202 if (!EvaluatePointer(E, PointerResult, Info))
203 return false;
Eli Friedman334046a2009-06-14 02:17:33 +0000204 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +0000205 } else if (E->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +0000206 ComplexValue ComplexResult;
Eli Friedman64004332009-03-23 04:38:34 +0000207 if (!EvaluateComplex(E, ComplexResult, Info))
208 return false;
209 if (ComplexResult.isComplexFloat()) {
210 Result = !ComplexResult.getComplexFloatReal().isZero() ||
211 !ComplexResult.getComplexFloatImag().isZero();
212 } else {
213 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
214 ComplexResult.getComplexIntImag().getBoolValue();
215 }
216 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000217 }
218
219 return false;
220}
221
Mike Stump11289f42009-09-09 15:08:12 +0000222static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000223 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000224 unsigned DestWidth = Ctx.getIntWidth(DestType);
225 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000226 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000227
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000228 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000229 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000230 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000231 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
232 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000233}
234
Mike Stump11289f42009-09-09 15:08:12 +0000235static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000236 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000237 bool ignored;
238 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000239 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000240 APFloat::rmNearestTiesToEven, &ignored);
241 return Result;
242}
243
Mike Stump11289f42009-09-09 15:08:12 +0000244static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000245 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000246 unsigned DestWidth = Ctx.getIntWidth(DestType);
247 APSInt Result = Value;
248 // Figure out if this is a truncate, extend or noop cast.
249 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000250 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000251 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000252 return Result;
253}
254
Mike Stump11289f42009-09-09 15:08:12 +0000255static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000256 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000257
258 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
259 Result.convertFromAPInt(Value, Value.isSigned(),
260 APFloat::rmNearestTiesToEven);
261 return Result;
262}
263
Mike Stump876387b2009-10-27 22:09:17 +0000264namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000265class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000266 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000267 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000268public:
269
Richard Smith725810a2011-10-16 21:26:27 +0000270 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000271
272 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000273 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000274 return true;
275 }
276
Peter Collingbournee9200682011-05-13 03:29:01 +0000277 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
278 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000279 return Visit(E->getResultExpr());
280 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000281 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000282 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000283 return true;
284 return false;
285 }
John McCall31168b02011-06-15 23:02:42 +0000286 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000287 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000288 return true;
289 return false;
290 }
291 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000292 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000293 return true;
294 return false;
295 }
296
Mike Stump876387b2009-10-27 22:09:17 +0000297 // We don't want to evaluate BlockExprs multiple times, as they generate
298 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000299 bool VisitBlockExpr(const BlockExpr *E) { return true; }
300 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
301 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000302 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000303 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
304 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
305 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
306 bool VisitStringLiteral(const StringLiteral *E) { return false; }
307 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
308 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000309 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000310 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000311 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000312 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000313 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000314 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
315 bool VisitBinAssign(const BinaryOperator *E) { return true; }
316 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
317 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000318 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000319 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
320 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
321 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
322 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
323 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000324 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000325 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000326 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000327 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000328 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000329
330 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000331 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000332 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
333 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000334 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000335 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000336 return false;
337 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000338
Peter Collingbournee9200682011-05-13 03:29:01 +0000339 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000340};
341
John McCallc07a0c72011-02-17 10:25:35 +0000342class OpaqueValueEvaluation {
343 EvalInfo &info;
344 OpaqueValueExpr *opaqueValue;
345
346public:
347 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
348 Expr *value)
349 : info(info), opaqueValue(opaqueValue) {
350
351 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000352 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000353 this->opaqueValue = 0;
354 return;
355 }
John McCallc07a0c72011-02-17 10:25:35 +0000356 }
357
358 bool hasError() const { return opaqueValue == 0; }
359
360 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000361 // FIXME: This will not work for recursive constexpr functions using opaque
362 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000363 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
364 }
365};
366
Mike Stump876387b2009-10-27 22:09:17 +0000367} // end anonymous namespace
368
Eli Friedman9a156e52008-11-12 09:44:48 +0000369//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000370// Generic Evaluation
371//===----------------------------------------------------------------------===//
372namespace {
373
374template <class Derived, typename RetTy=void>
375class ExprEvaluatorBase
376 : public ConstStmtVisitor<Derived, RetTy> {
377private:
378 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
379 return static_cast<Derived*>(this)->Success(V, E);
380 }
381 RetTy DerivedError(const Expr *E) {
382 return static_cast<Derived*>(this)->Error(E);
383 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000384 RetTy DerivedValueInitialization(const Expr *E) {
385 return static_cast<Derived*>(this)->ValueInitialization(E);
386 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000387
388protected:
389 EvalInfo &Info;
390 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
391 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
392
Richard Smith4ce706a2011-10-11 21:43:33 +0000393 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
394
Peter Collingbournee9200682011-05-13 03:29:01 +0000395public:
396 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
397
398 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000399 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000400 }
401 RetTy VisitExpr(const Expr *E) {
402 return DerivedError(E);
403 }
404
405 RetTy VisitParenExpr(const ParenExpr *E)
406 { return StmtVisitorTy::Visit(E->getSubExpr()); }
407 RetTy VisitUnaryExtension(const UnaryOperator *E)
408 { return StmtVisitorTy::Visit(E->getSubExpr()); }
409 RetTy VisitUnaryPlus(const UnaryOperator *E)
410 { return StmtVisitorTy::Visit(E->getSubExpr()); }
411 RetTy VisitChooseExpr(const ChooseExpr *E)
412 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
413 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
414 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000415 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
416 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000417
418 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
419 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
420 if (opaque.hasError())
421 return DerivedError(E);
422
423 bool cond;
424 if (!HandleConversionToBool(E->getCond(), cond, Info))
425 return DerivedError(E);
426
427 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
428 }
429
430 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
431 bool BoolResult;
432 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
433 return DerivedError(E);
434
435 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
436 return StmtVisitorTy::Visit(EvalExpr);
437 }
438
439 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
440 const APValue *value = Info.getOpaqueValue(E);
441 if (!value)
442 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
443 : DerivedError(E));
444 return DerivedSuccess(*value, E);
445 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000446
447 RetTy VisitInitListExpr(const InitListExpr *E) {
448 if (Info.getLangOpts().CPlusPlus0x) {
449 if (E->getNumInits() == 0)
450 return DerivedValueInitialization(E);
451 if (E->getNumInits() == 1)
452 return StmtVisitorTy::Visit(E->getInit(0));
453 }
454 return DerivedError(E);
455 }
456 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
457 return DerivedValueInitialization(E);
458 }
459 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
460 return DerivedValueInitialization(E);
461 }
462
Peter Collingbournee9200682011-05-13 03:29:01 +0000463};
464
465}
466
467//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000468// LValue Evaluation
469//===----------------------------------------------------------------------===//
470namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000471class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000472 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000473 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000474 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000475
Peter Collingbournee9200682011-05-13 03:29:01 +0000476 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000477 Result.Base = E;
478 Result.Offset = CharUnits::Zero();
479 return true;
480 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000481public:
Mike Stump11289f42009-09-09 15:08:12 +0000482
John McCall45d55e42010-05-07 21:00:08 +0000483 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000484 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000485
Peter Collingbournee9200682011-05-13 03:29:01 +0000486 bool Success(const APValue &V, const Expr *E) {
487 Result.setFrom(V);
488 return true;
489 }
490 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000491 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000492 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000493
Peter Collingbournee9200682011-05-13 03:29:01 +0000494 bool VisitDeclRefExpr(const DeclRefExpr *E);
495 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
496 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
497 bool VisitMemberExpr(const MemberExpr *E);
498 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
499 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
500 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
501 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000502
Peter Collingbournee9200682011-05-13 03:29:01 +0000503 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000504 switch (E->getCastKind()) {
505 default:
John McCall45d55e42010-05-07 21:00:08 +0000506 return false;
Anders Carlssonde55f642009-10-03 16:30:22 +0000507
John McCalle3027922010-08-25 11:45:40 +0000508 case CK_NoOp:
Eli Friedmance3e02a2011-10-11 00:13:24 +0000509 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000510 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000511
512 // FIXME: Support CK_DerivedToBase and friends.
Anders Carlssonde55f642009-10-03 16:30:22 +0000513 }
514 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000515
Eli Friedman449fe542009-03-23 04:56:01 +0000516 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000517
Eli Friedman9a156e52008-11-12 09:44:48 +0000518};
519} // end anonymous namespace
520
John McCall45d55e42010-05-07 21:00:08 +0000521static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000522 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000523}
524
Peter Collingbournee9200682011-05-13 03:29:01 +0000525bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000526 if (isa<FunctionDecl>(E->getDecl())) {
John McCall45d55e42010-05-07 21:00:08 +0000527 return Success(E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000528 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000529 if (!VD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000530 return Success(E);
Chandler Carruthe299ba62010-05-16 09:32:51 +0000531 // Reference parameters can refer to anything even if they have an
532 // "initializer" in the form of a default argument.
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000533 if (!isa<ParmVarDecl>(VD)) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000534 // FIXME: Check whether VD might be overridden!
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000535
536 // Check for recursive initializers of references.
537 if (PrevDecl == VD)
538 return Error(E);
539 PrevDecl = VD;
Peter Collingbournee9200682011-05-13 03:29:01 +0000540 if (const Expr *Init = VD->getAnyInitializer())
541 return Visit(Init);
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000542 }
Eli Friedman751aa72b72009-05-27 06:04:58 +0000543 }
544
Peter Collingbournee9200682011-05-13 03:29:01 +0000545 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000546}
547
Peter Collingbournee9200682011-05-13 03:29:01 +0000548bool
549LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000550 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000551}
552
Peter Collingbournee9200682011-05-13 03:29:01 +0000553bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000554 QualType Ty;
555 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000556 if (!EvaluatePointer(E->getBase(), Result, Info))
557 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000558 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000559 } else {
John McCall45d55e42010-05-07 21:00:08 +0000560 if (!Visit(E->getBase()))
561 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000562 Ty = E->getBase()->getType();
563 }
564
Peter Collingbournee9200682011-05-13 03:29:01 +0000565 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000566 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000567
Peter Collingbournee9200682011-05-13 03:29:01 +0000568 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000569 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000570 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000571
572 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000573 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000574
Eli Friedmana3c122d2011-07-07 01:54:01 +0000575 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000576 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000577 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000578}
579
Peter Collingbournee9200682011-05-13 03:29:01 +0000580bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000581 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000582 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000583
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000584 APSInt Index;
585 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000586 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000587
Ken Dyck40775002010-01-11 17:06:35 +0000588 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000589 Result.Offset += Index.getSExtValue() * ElementSize;
590 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000591}
Eli Friedman9a156e52008-11-12 09:44:48 +0000592
Peter Collingbournee9200682011-05-13 03:29:01 +0000593bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +0000594 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000595}
596
Eli Friedman9a156e52008-11-12 09:44:48 +0000597//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000598// Pointer Evaluation
599//===----------------------------------------------------------------------===//
600
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000601namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000602class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000603 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000604 LValue &Result;
605
Peter Collingbournee9200682011-05-13 03:29:01 +0000606 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000607 Result.Base = E;
608 Result.Offset = CharUnits::Zero();
609 return true;
610 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000611public:
Mike Stump11289f42009-09-09 15:08:12 +0000612
John McCall45d55e42010-05-07 21:00:08 +0000613 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000614 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000615
Peter Collingbournee9200682011-05-13 03:29:01 +0000616 bool Success(const APValue &V, const Expr *E) {
617 Result.setFrom(V);
618 return true;
619 }
620 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +0000621 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000622 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000623 bool ValueInitialization(const Expr *E) {
624 return Success((Expr*)0);
625 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000626
John McCall45d55e42010-05-07 21:00:08 +0000627 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000628 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +0000629 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000630 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +0000631 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000632 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000633 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000634 bool VisitCallExpr(const CallExpr *E);
635 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +0000636 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000637 return Success(E);
638 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000639 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000640 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +0000641 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +0000642
Eli Friedman449fe542009-03-23 04:56:01 +0000643 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000644};
Chris Lattner05706e882008-07-11 18:11:29 +0000645} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000646
John McCall45d55e42010-05-07 21:00:08 +0000647static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000648 assert(E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +0000649 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +0000650}
651
John McCall45d55e42010-05-07 21:00:08 +0000652bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000653 if (E->getOpcode() != BO_Add &&
654 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +0000655 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000656
Chris Lattner05706e882008-07-11 18:11:29 +0000657 const Expr *PExp = E->getLHS();
658 const Expr *IExp = E->getRHS();
659 if (IExp->getType()->isPointerType())
660 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000661
John McCall45d55e42010-05-07 21:00:08 +0000662 if (!EvaluatePointer(PExp, Result, Info))
663 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000664
John McCall45d55e42010-05-07 21:00:08 +0000665 llvm::APSInt Offset;
666 if (!EvaluateInteger(IExp, Offset, Info))
667 return false;
668 int64_t AdditionalOffset
669 = Offset.isSigned() ? Offset.getSExtValue()
670 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +0000671
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000672 // Compute the new offset in the appropriate width.
673
674 QualType PointeeType =
675 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +0000676 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +0000677
Anders Carlssonef56fba2009-02-19 04:55:58 +0000678 // Explicitly handle GNU void* and function pointer arithmetic extensions.
679 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +0000680 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +0000681 else
John McCall45d55e42010-05-07 21:00:08 +0000682 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +0000683
John McCalle3027922010-08-25 11:45:40 +0000684 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +0000685 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000686 else
John McCall45d55e42010-05-07 21:00:08 +0000687 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000688
John McCall45d55e42010-05-07 21:00:08 +0000689 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000690}
Eli Friedman9a156e52008-11-12 09:44:48 +0000691
John McCall45d55e42010-05-07 21:00:08 +0000692bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
693 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000694}
Mike Stump11289f42009-09-09 15:08:12 +0000695
Chris Lattner05706e882008-07-11 18:11:29 +0000696
Peter Collingbournee9200682011-05-13 03:29:01 +0000697bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
698 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000699
Eli Friedman847a2bc2009-12-27 05:43:15 +0000700 switch (E->getCastKind()) {
701 default:
702 break;
703
John McCalle3027922010-08-25 11:45:40 +0000704 case CK_NoOp:
705 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +0000706 case CK_CPointerToObjCPointerCast:
707 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +0000708 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +0000709 return Visit(SubExpr);
710
Anders Carlsson18275092010-10-31 20:41:46 +0000711 case CK_DerivedToBase:
712 case CK_UncheckedDerivedToBase: {
713 LValue BaseLV;
714 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
715 return false;
716
717 // Now figure out the necessary offset to add to the baseLV to get from
718 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +0000719 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +0000720
721 QualType Ty = E->getSubExpr()->getType();
722 const CXXRecordDecl *DerivedDecl =
723 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
724
725 for (CastExpr::path_const_iterator PathI = E->path_begin(),
726 PathE = E->path_end(); PathI != PathE; ++PathI) {
727 const CXXBaseSpecifier *Base = *PathI;
728
729 // FIXME: If the base is virtual, we'd need to determine the type of the
730 // most derived class and we don't support that right now.
731 if (Base->isVirtual())
732 return false;
733
734 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
735 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
736
Ken Dyck02155cb2011-01-26 02:17:08 +0000737 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +0000738 DerivedDecl = BaseDecl;
739 }
740
741 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +0000742 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +0000743 return true;
744 }
745
John McCalle84af4e2010-11-13 01:35:44 +0000746 case CK_NullToPointer: {
747 Result.Base = 0;
748 Result.Offset = CharUnits::Zero();
749 return true;
750 }
751
John McCalle3027922010-08-25 11:45:40 +0000752 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +0000753 APValue Value;
754 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000755 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000756
John McCall45d55e42010-05-07 21:00:08 +0000757 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000758 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-05-07 21:00:08 +0000759 Result.Base = 0;
760 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
761 return true;
762 } else {
763 // Cast is of an lvalue, no need to change value.
764 Result.Base = Value.getLValueBase();
765 Result.Offset = Value.getLValueOffset();
766 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000767 }
768 }
John McCalle3027922010-08-25 11:45:40 +0000769 case CK_ArrayToPointerDecay:
770 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +0000771 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000772 }
773
John McCall45d55e42010-05-07 21:00:08 +0000774 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000775}
Chris Lattner05706e882008-07-11 18:11:29 +0000776
Peter Collingbournee9200682011-05-13 03:29:01 +0000777bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000778 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000779 Builtin::BI__builtin___CFStringMakeConstantString ||
780 E->isBuiltinCall(Info.Ctx) ==
781 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +0000782 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000783
Peter Collingbournee9200682011-05-13 03:29:01 +0000784 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000785}
Chris Lattner05706e882008-07-11 18:11:29 +0000786
787//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000788// Vector Evaluation
789//===----------------------------------------------------------------------===//
790
791namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000792 class VectorExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000793 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman3ae59112009-02-23 04:23:56 +0000794 APValue GetZeroVector(QualType VecType);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000795 public:
Mike Stump11289f42009-09-09 15:08:12 +0000796
Peter Collingbournee9200682011-05-13 03:29:01 +0000797 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump11289f42009-09-09 15:08:12 +0000798
Peter Collingbournee9200682011-05-13 03:29:01 +0000799 APValue Success(const APValue &V, const Expr *E) { return V; }
800 APValue Error(const Expr *E) { return APValue(); }
Richard Smith4ce706a2011-10-11 21:43:33 +0000801 APValue ValueInitialization(const Expr *E)
802 { return GetZeroVector(E->getType()); }
Mike Stump11289f42009-09-09 15:08:12 +0000803
Eli Friedman3ae59112009-02-23 04:23:56 +0000804 APValue VisitUnaryReal(const UnaryOperator *E)
805 { return Visit(E->getSubExpr()); }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000806 APValue VisitCastExpr(const CastExpr* E);
807 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
808 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000809 APValue VisitUnaryImag(const UnaryOperator *E);
810 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000811 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000812 // shufflevector, ExtVectorElementExpr
813 // (Note that these require implementing conversions
814 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000815 };
816} // end anonymous namespace
817
818static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
819 if (!E->getType()->isVectorType())
820 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +0000821 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000822 return !Result.isUninit();
823}
824
825APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall9dd450b2009-09-21 23:43:11 +0000826 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000827 QualType EltTy = VTy->getElementType();
828 unsigned NElts = VTy->getNumElements();
829 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000830
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000831 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000832 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000833
Eli Friedmanc757de22011-03-25 00:43:55 +0000834 switch (E->getCastKind()) {
835 case CK_VectorSplat: {
836 APValue Result = APValue();
837 if (SETy->isIntegerType()) {
838 APSInt IntResult;
839 if (!EvaluateInteger(SE, IntResult, Info))
840 return APValue();
841 Result = APValue(IntResult);
842 } else if (SETy->isRealFloatingType()) {
843 APFloat F(0.0);
844 if (!EvaluateFloat(SE, F, Info))
845 return APValue();
846 Result = APValue(F);
847 } else {
Anders Carlsson6fc22042011-03-25 11:22:47 +0000848 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000849 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000850
851 // Splat and create vector APValue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000852 SmallVector<APValue, 4> Elts(NElts, Result);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000853 return APValue(&Elts[0], Elts.size());
Nate Begeman2ffd3842009-06-26 18:22:18 +0000854 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000855 case CK_BitCast: {
856 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +0000857 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000858
Eli Friedmanc757de22011-03-25 00:43:55 +0000859 if (!SETy->isIntegerType())
Anders Carlsson6fc22042011-03-25 11:22:47 +0000860 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000861
Eli Friedmanc757de22011-03-25 00:43:55 +0000862 APSInt Init;
863 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000864 return APValue();
865
Eli Friedmanc757de22011-03-25 00:43:55 +0000866 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
867 "Vectors must be composed of ints or floats");
868
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000869 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +0000870 for (unsigned i = 0; i != NElts; ++i) {
871 APSInt Tmp = Init.extOrTrunc(EltWidth);
872
873 if (EltTy->isIntegerType())
874 Elts.push_back(APValue(Tmp));
875 else
876 Elts.push_back(APValue(APFloat(Tmp)));
877
878 Init >>= EltWidth;
879 }
880 return APValue(&Elts[0], Elts.size());
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000881 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000882 case CK_LValueToRValue:
883 case CK_NoOp:
Peter Collingbournee9200682011-05-13 03:29:01 +0000884 return Visit(SE);
Eli Friedmanc757de22011-03-25 00:43:55 +0000885 default:
Anders Carlsson6fc22042011-03-25 11:22:47 +0000886 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000887 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000888}
889
Mike Stump11289f42009-09-09 15:08:12 +0000890APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000891VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000892 return this->Visit(E->getInitializer());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000893}
894
Mike Stump11289f42009-09-09 15:08:12 +0000895APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000896VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall9dd450b2009-09-21 23:43:11 +0000897 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000898 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000899 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000900
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000901 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000902 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000903
John McCall875679e2010-06-11 17:54:15 +0000904 // If a vector is initialized with a single element, that value
905 // becomes every element of the vector, not just the first.
906 // This is the behavior described in the IBM AltiVec documentation.
907 if (NumInits == 1) {
Tanya Lattner5ac257d2011-04-15 22:42:59 +0000908
909 // Handle the case where the vector is initialized by a another
910 // vector (OpenCL 6.1.6).
911 if (E->getInit(0)->getType()->isVectorType())
912 return this->Visit(const_cast<Expr*>(E->getInit(0)));
913
John McCall875679e2010-06-11 17:54:15 +0000914 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000915 if (EltTy->isIntegerType()) {
916 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +0000917 if (!EvaluateInteger(E->getInit(0), sInt, Info))
918 return APValue();
919 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000920 } else {
921 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +0000922 if (!EvaluateFloat(E->getInit(0), f, Info))
923 return APValue();
924 InitValue = APValue(f);
925 }
926 for (unsigned i = 0; i < NumElements; i++) {
927 Elements.push_back(InitValue);
928 }
929 } else {
930 for (unsigned i = 0; i < NumElements; i++) {
931 if (EltTy->isIntegerType()) {
932 llvm::APSInt sInt(32);
933 if (i < NumInits) {
934 if (!EvaluateInteger(E->getInit(i), sInt, Info))
935 return APValue();
936 } else {
937 sInt = Info.Ctx.MakeIntValue(0, EltTy);
938 }
939 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +0000940 } else {
John McCall875679e2010-06-11 17:54:15 +0000941 llvm::APFloat f(0.0);
942 if (i < NumInits) {
943 if (!EvaluateFloat(E->getInit(i), f, Info))
944 return APValue();
945 } else {
946 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
947 }
948 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +0000949 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000950 }
951 }
952 return APValue(&Elements[0], Elements.size());
953}
954
Mike Stump11289f42009-09-09 15:08:12 +0000955APValue
Eli Friedman3ae59112009-02-23 04:23:56 +0000956VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +0000957 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +0000958 QualType EltTy = VT->getElementType();
959 APValue ZeroElement;
960 if (EltTy->isIntegerType())
961 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
962 else
963 ZeroElement =
964 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
965
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000966 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Eli Friedman3ae59112009-02-23 04:23:56 +0000967 return APValue(&Elements[0], Elements.size());
968}
969
Eli Friedman3ae59112009-02-23 04:23:56 +0000970APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000971 APValue Scratch;
972 if (!Evaluate(Scratch, Info, E->getSubExpr()))
973 Info.EvalStatus.HasSideEffects = true;
Eli Friedman3ae59112009-02-23 04:23:56 +0000974 return GetZeroVector(E->getType());
975}
976
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000977//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000978// Integer Evaluation
979//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000980
981namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000982class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000983 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000984 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000985public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000986 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000987 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000988
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000989 bool Success(const llvm::APSInt &SI, const Expr *E) {
990 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +0000991 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000992 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000993 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000994 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000995 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000996 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000997 return true;
998 }
999
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001000 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001001 assert(E->getType()->isIntegralOrEnumerationType() &&
1002 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001003 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001004 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001005 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001006 Result.getInt().setIsUnsigned(
1007 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001008 return true;
1009 }
1010
1011 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001012 assert(E->getType()->isIntegralOrEnumerationType() &&
1013 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001014 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001015 return true;
1016 }
1017
Ken Dyckdbc01912011-03-11 02:13:43 +00001018 bool Success(CharUnits Size, const Expr *E) {
1019 return Success(Size.getQuantity(), E);
1020 }
1021
1022
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001023 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001024 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001025 if (Info.EvalStatus.Diag == 0) {
1026 Info.EvalStatus.DiagLoc = L;
1027 Info.EvalStatus.Diag = D;
1028 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001029 }
Chris Lattner99415702008-07-12 00:14:42 +00001030 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001031 }
Mike Stump11289f42009-09-09 15:08:12 +00001032
Peter Collingbournee9200682011-05-13 03:29:01 +00001033 bool Success(const APValue &V, const Expr *E) {
1034 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001035 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001036 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001037 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001038 }
Mike Stump11289f42009-09-09 15:08:12 +00001039
Richard Smith4ce706a2011-10-11 21:43:33 +00001040 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1041
Peter Collingbournee9200682011-05-13 03:29:01 +00001042 //===--------------------------------------------------------------------===//
1043 // Visitor Methods
1044 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001045
Chris Lattner7174bf32008-07-12 00:38:25 +00001046 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001047 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001048 }
1049 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001050 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001051 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001052
1053 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1054 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001055 if (CheckReferencedDecl(E, E->getDecl()))
1056 return true;
1057
1058 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001059 }
1060 bool VisitMemberExpr(const MemberExpr *E) {
1061 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1062 // Conservatively assume a MemberExpr will have side-effects
Richard Smith725810a2011-10-16 21:26:27 +00001063 Info.EvalStatus.HasSideEffects = true;
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001064 return true;
1065 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001066
1067 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001068 }
1069
Peter Collingbournee9200682011-05-13 03:29:01 +00001070 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001071 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001072 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001073 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001074
Peter Collingbournee9200682011-05-13 03:29:01 +00001075 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001076 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001077
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001078 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001079 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
Richard Smith4ce706a2011-10-11 21:43:33 +00001082 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001083 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001084 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001085 }
1086
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001087 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001088 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001089 }
1090
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001091 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1092 return Success(E->getValue(), E);
1093 }
1094
John Wiegley6242b6a2011-04-28 00:16:57 +00001095 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1096 return Success(E->getValue(), E);
1097 }
1098
John Wiegleyf9f65842011-04-25 06:54:41 +00001099 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1100 return Success(E->getValue(), E);
1101 }
1102
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001103 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001104 bool VisitUnaryImag(const UnaryOperator *E);
1105
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001106 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001107 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001108
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001109private:
Ken Dyck160146e2010-01-27 17:10:57 +00001110 CharUnits GetAlignOfExpr(const Expr *E);
1111 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001112 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001113 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001114 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001115};
Chris Lattner05706e882008-07-11 18:11:29 +00001116} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001117
Daniel Dunbarce399542009-02-20 18:22:23 +00001118static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001119 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001120 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001121}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001122
Daniel Dunbarce399542009-02-20 18:22:23 +00001123static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001124 assert(E->getType()->isIntegralOrEnumerationType());
John McCallf0c4f352010-05-07 05:46:35 +00001125
Daniel Dunbarce399542009-02-20 18:22:23 +00001126 APValue Val;
1127 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1128 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001129 Result = Val.getInt();
1130 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001131}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001132
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001133bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001134 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001135 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001136 // Check for signedness/width mismatches between E type and ECD value.
1137 bool SameSign = (ECD->getInitVal().isSigned()
1138 == E->getType()->isSignedIntegerOrEnumerationType());
1139 bool SameWidth = (ECD->getInitVal().getBitWidth()
1140 == Info.Ctx.getIntWidth(E->getType()));
1141 if (SameSign && SameWidth)
1142 return Success(ECD->getInitVal(), E);
1143 else {
1144 // Get rid of mismatch (otherwise Success assertions will fail)
1145 // by computing a new value matching the type of E.
1146 llvm::APSInt Val = ECD->getInitVal();
1147 if (!SameSign)
1148 Val.setIsSigned(!ECD->getInitVal().isSigned());
1149 if (!SameWidth)
1150 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1151 return Success(Val, E);
1152 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001153 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001154
1155 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +00001156 // In C, they can also be folded, although they are not ICEs.
Douglas Gregor0840cc02009-11-01 20:32:48 +00001157 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1158 == Qualifiers::Const) {
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001159
1160 if (isa<ParmVarDecl>(D))
Peter Collingbournee9200682011-05-13 03:29:01 +00001161 return false;
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001162
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001163 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001164 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedman1d6fb162009-12-03 20:31:57 +00001165 if (APValue *V = VD->getEvaluatedValue()) {
1166 if (V->isInt())
1167 return Success(V->getInt(), E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001168 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001169 }
1170
1171 if (VD->isEvaluatingValue())
Peter Collingbournee9200682011-05-13 03:29:01 +00001172 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001173
1174 VD->setEvaluatingValue();
1175
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001176 Expr::EvalResult EResult;
Richard Smith725810a2011-10-16 21:26:27 +00001177 // FIXME: Produce a diagnostic if the initializer isn't a constant
1178 // expression.
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001179 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1180 EResult.Val.isInt()) {
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001181 // Cache the evaluated value in the variable declaration.
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001182 Result = EResult.Val;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001183 VD->setEvaluatedValue(Result);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001184 return true;
1185 }
1186
Eli Friedman1d6fb162009-12-03 20:31:57 +00001187 VD->setEvaluatedValue(APValue());
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001188 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001189 }
1190 }
1191
Chris Lattner7174bf32008-07-12 00:38:25 +00001192 // Otherwise, random variable references are not constants.
Peter Collingbournee9200682011-05-13 03:29:01 +00001193 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001194}
1195
Chris Lattner86ee2862008-10-06 06:40:35 +00001196/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1197/// as GCC.
1198static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1199 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001200 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001201 enum gcc_type_class {
1202 no_type_class = -1,
1203 void_type_class, integer_type_class, char_type_class,
1204 enumeral_type_class, boolean_type_class,
1205 pointer_type_class, reference_type_class, offset_type_class,
1206 real_type_class, complex_type_class,
1207 function_type_class, method_type_class,
1208 record_type_class, union_type_class,
1209 array_type_class, string_type_class,
1210 lang_type_class
1211 };
Mike Stump11289f42009-09-09 15:08:12 +00001212
1213 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001214 // ideal, however it is what gcc does.
1215 if (E->getNumArgs() == 0)
1216 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001217
Chris Lattner86ee2862008-10-06 06:40:35 +00001218 QualType ArgTy = E->getArg(0)->getType();
1219 if (ArgTy->isVoidType())
1220 return void_type_class;
1221 else if (ArgTy->isEnumeralType())
1222 return enumeral_type_class;
1223 else if (ArgTy->isBooleanType())
1224 return boolean_type_class;
1225 else if (ArgTy->isCharType())
1226 return string_type_class; // gcc doesn't appear to use char_type_class
1227 else if (ArgTy->isIntegerType())
1228 return integer_type_class;
1229 else if (ArgTy->isPointerType())
1230 return pointer_type_class;
1231 else if (ArgTy->isReferenceType())
1232 return reference_type_class;
1233 else if (ArgTy->isRealType())
1234 return real_type_class;
1235 else if (ArgTy->isComplexType())
1236 return complex_type_class;
1237 else if (ArgTy->isFunctionType())
1238 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001239 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001240 return record_type_class;
1241 else if (ArgTy->isUnionType())
1242 return union_type_class;
1243 else if (ArgTy->isArrayType())
1244 return array_type_class;
1245 else if (ArgTy->isUnionType())
1246 return union_type_class;
1247 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001248 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001249 return -1;
1250}
1251
John McCall95007602010-05-10 23:27:23 +00001252/// Retrieves the "underlying object type" of the given expression,
1253/// as used by __builtin_object_size.
1254QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1255 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1256 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1257 return VD->getType();
1258 } else if (isa<CompoundLiteralExpr>(E)) {
1259 return E->getType();
1260 }
1261
1262 return QualType();
1263}
1264
Peter Collingbournee9200682011-05-13 03:29:01 +00001265bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001266 // TODO: Perhaps we should let LLVM lower this?
1267 LValue Base;
1268 if (!EvaluatePointer(E->getArg(0), Base, Info))
1269 return false;
1270
1271 // If we can prove the base is null, lower to zero now.
1272 const Expr *LVBase = Base.getLValueBase();
1273 if (!LVBase) return Success(0, E);
1274
1275 QualType T = GetObjectType(LVBase);
1276 if (T.isNull() ||
1277 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001278 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001279 T->isVariablyModifiedType() ||
1280 T->isDependentType())
1281 return false;
1282
1283 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1284 CharUnits Offset = Base.getLValueOffset();
1285
1286 if (!Offset.isNegative() && Offset <= Size)
1287 Size -= Offset;
1288 else
1289 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001290 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001291}
1292
Peter Collingbournee9200682011-05-13 03:29:01 +00001293bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001294 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001295 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001296 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001297
1298 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001299 if (TryEvaluateBuiltinObjectSize(E))
1300 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001301
Eric Christopher99469702010-01-19 22:58:35 +00001302 // If evaluating the argument has side-effects we can't determine
1303 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001304 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001305 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001306 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001307 return Success(0, E);
1308 }
Mike Stump876387b2009-10-27 22:09:17 +00001309
Mike Stump722cedf2009-10-26 18:35:08 +00001310 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1311 }
1312
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001313 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001314 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001315
Anders Carlsson4c76e932008-11-24 04:21:33 +00001316 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001317 // __builtin_constant_p always has one operand: it returns true if that
1318 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001319 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001320
1321 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001322 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001323 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001324 return Success(Operand, E);
1325 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001326
1327 case Builtin::BI__builtin_expect:
1328 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001329
1330 case Builtin::BIstrlen:
1331 case Builtin::BI__builtin_strlen:
1332 // As an extension, we support strlen() and __builtin_strlen() as constant
1333 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001334 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001335 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1336 // The string literal may have embedded null characters. Find the first
1337 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001338 StringRef Str = S->getString();
1339 StringRef::size_type Pos = Str.find(0);
1340 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001341 Str = Str.substr(0, Pos);
1342
1343 return Success(Str.size(), E);
1344 }
1345
1346 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001347
1348 case Builtin::BI__atomic_is_lock_free: {
1349 APSInt SizeVal;
1350 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1351 return false;
1352
1353 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1354 // of two less than the maximum inline atomic width, we know it is
1355 // lock-free. If the size isn't a power of two, or greater than the
1356 // maximum alignment where we promote atomics, we know it is not lock-free
1357 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1358 // the answer can only be determined at runtime; for example, 16-byte
1359 // atomics have lock-free implementations on some, but not all,
1360 // x86-64 processors.
1361
1362 // Check power-of-two.
1363 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1364 if (!Size.isPowerOfTwo())
1365#if 0
1366 // FIXME: Suppress this folding until the ABI for the promotion width
1367 // settles.
1368 return Success(0, E);
1369#else
1370 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1371#endif
1372
1373#if 0
1374 // Check against promotion width.
1375 // FIXME: Suppress this folding until the ABI for the promotion width
1376 // settles.
1377 unsigned PromoteWidthBits =
1378 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1379 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1380 return Success(0, E);
1381#endif
1382
1383 // Check against inlining width.
1384 unsigned InlineWidthBits =
1385 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1386 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1387 return Success(1, E);
1388
1389 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1390 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001391 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001392}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001393
Chris Lattnere13042c2008-07-11 19:10:17 +00001394bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001395 if (E->getOpcode() == BO_Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001396 if (!Visit(E->getRHS()))
1397 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001398
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001399 // If we can't evaluate the LHS, it might have side effects;
1400 // conservatively mark it.
Richard Smith725810a2011-10-16 21:26:27 +00001401 APValue Scratch;
1402 if (!Evaluate(Scratch, Info, E->getLHS()))
1403 Info.EvalStatus.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001404
Anders Carlsson564730a2008-12-01 02:07:06 +00001405 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001406 }
1407
1408 if (E->isLogicalOp()) {
1409 // These need to be handled specially because the operands aren't
1410 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001411 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001412
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001413 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001414 // We were able to evaluate the LHS, see if we can get away with not
1415 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001416 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001417 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001418
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001419 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001420 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001421 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001422 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001423 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001424 }
1425 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001426 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001427 // We can't evaluate the LHS; however, sometimes the result
1428 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001429 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1430 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001431 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001432 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001433 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001434
1435 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001436 }
1437 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001438 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001439
Eli Friedman5a332ea2008-11-13 06:09:17 +00001440 return false;
1441 }
1442
Anders Carlssonacc79812008-11-16 07:17:21 +00001443 QualType LHSTy = E->getLHS()->getType();
1444 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001445
1446 if (LHSTy->isAnyComplexType()) {
1447 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001448 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001449
1450 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1451 return false;
1452
1453 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1454 return false;
1455
1456 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001457 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001458 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001459 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001460 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1461
John McCalle3027922010-08-25 11:45:40 +00001462 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001463 return Success((CR_r == APFloat::cmpEqual &&
1464 CR_i == APFloat::cmpEqual), E);
1465 else {
John McCalle3027922010-08-25 11:45:40 +00001466 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001467 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001468 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001469 CR_r == APFloat::cmpLessThan ||
1470 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001471 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001472 CR_i == APFloat::cmpLessThan ||
1473 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001474 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001475 } else {
John McCalle3027922010-08-25 11:45:40 +00001476 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001477 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1478 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1479 else {
John McCalle3027922010-08-25 11:45:40 +00001480 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001481 "Invalid compex comparison.");
1482 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1483 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1484 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001485 }
1486 }
Mike Stump11289f42009-09-09 15:08:12 +00001487
Anders Carlssonacc79812008-11-16 07:17:21 +00001488 if (LHSTy->isRealFloatingType() &&
1489 RHSTy->isRealFloatingType()) {
1490 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001491
Anders Carlssonacc79812008-11-16 07:17:21 +00001492 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1493 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001494
Anders Carlssonacc79812008-11-16 07:17:21 +00001495 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1496 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001497
Anders Carlssonacc79812008-11-16 07:17:21 +00001498 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001499
Anders Carlssonacc79812008-11-16 07:17:21 +00001500 switch (E->getOpcode()) {
1501 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001502 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001503 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001504 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001505 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001506 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001507 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001508 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001509 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001510 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001511 E);
John McCalle3027922010-08-25 11:45:40 +00001512 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001513 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001514 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001515 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001516 || CR == APFloat::cmpLessThan
1517 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001518 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001519 }
Mike Stump11289f42009-09-09 15:08:12 +00001520
Eli Friedmana38da572009-04-28 19:17:36 +00001521 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001522 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001523 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001524 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1525 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001526
John McCall45d55e42010-05-07 21:00:08 +00001527 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001528 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1529 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001530
Eli Friedman334046a2009-06-14 02:17:33 +00001531 // Reject any bases from the normal codepath; we special-case comparisons
1532 // to null.
1533 if (LHSValue.getLValueBase()) {
1534 if (!E->isEqualityOp())
1535 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001536 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001537 return false;
1538 bool bres;
1539 if (!EvalPointerValueAsBool(LHSValue, bres))
1540 return false;
John McCalle3027922010-08-25 11:45:40 +00001541 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001542 } else if (RHSValue.getLValueBase()) {
1543 if (!E->isEqualityOp())
1544 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001545 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001546 return false;
1547 bool bres;
1548 if (!EvalPointerValueAsBool(RHSValue, bres))
1549 return false;
John McCalle3027922010-08-25 11:45:40 +00001550 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001551 }
Eli Friedman64004332009-03-23 04:38:34 +00001552
John McCalle3027922010-08-25 11:45:40 +00001553 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001554 QualType Type = E->getLHS()->getType();
1555 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001556
Ken Dyck02990832010-01-15 12:37:54 +00001557 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001558 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001559 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001560
Ken Dyck02990832010-01-15 12:37:54 +00001561 CharUnits Diff = LHSValue.getLValueOffset() -
1562 RHSValue.getLValueOffset();
1563 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001564 }
1565 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001566 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001567 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001568 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001569 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1570 }
1571 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001572 }
1573 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001574 if (!LHSTy->isIntegralOrEnumerationType() ||
1575 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001576 // We can't continue from here for non-integral types, and they
1577 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001578 return false;
1579 }
1580
Anders Carlsson9c181652008-07-08 14:35:21 +00001581 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001582 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001583 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001584
Eli Friedman94c25c62009-03-24 01:14:50 +00001585 APValue RHSVal;
1586 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001587 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001588
1589 // Handle cases like (unsigned long)&a + 4.
1590 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001591 CharUnits Offset = Result.getLValueOffset();
1592 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1593 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001594 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001595 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001596 else
Ken Dyck02990832010-01-15 12:37:54 +00001597 Offset -= AdditionalOffset;
1598 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001599 return true;
1600 }
1601
1602 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001603 if (E->getOpcode() == BO_Add &&
Eli Friedman94c25c62009-03-24 01:14:50 +00001604 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001605 CharUnits Offset = RHSVal.getLValueOffset();
1606 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1607 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001608 return true;
1609 }
1610
1611 // All the following cases expect both operands to be an integer
1612 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001613 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001614
Eli Friedman94c25c62009-03-24 01:14:50 +00001615 APSInt& RHS = RHSVal.getInt();
1616
Anders Carlsson9c181652008-07-08 14:35:21 +00001617 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001618 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001619 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001620 case BO_Mul: return Success(Result.getInt() * RHS, E);
1621 case BO_Add: return Success(Result.getInt() + RHS, E);
1622 case BO_Sub: return Success(Result.getInt() - RHS, E);
1623 case BO_And: return Success(Result.getInt() & RHS, E);
1624 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1625 case BO_Or: return Success(Result.getInt() | RHS, E);
1626 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001627 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001628 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001629 return Success(Result.getInt() / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001630 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001631 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001632 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001633 return Success(Result.getInt() % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001634 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001635 // During constant-folding, a negative shift is an opposite shift.
1636 if (RHS.isSigned() && RHS.isNegative()) {
1637 RHS = -RHS;
1638 goto shift_right;
1639 }
1640
1641 shift_left:
1642 unsigned SA
1643 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001644 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001645 }
John McCalle3027922010-08-25 11:45:40 +00001646 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001647 // During constant-folding, a negative shift is an opposite shift.
1648 if (RHS.isSigned() && RHS.isNegative()) {
1649 RHS = -RHS;
1650 goto shift_left;
1651 }
1652
1653 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001654 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001655 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1656 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001657 }
Mike Stump11289f42009-09-09 15:08:12 +00001658
John McCalle3027922010-08-25 11:45:40 +00001659 case BO_LT: return Success(Result.getInt() < RHS, E);
1660 case BO_GT: return Success(Result.getInt() > RHS, E);
1661 case BO_LE: return Success(Result.getInt() <= RHS, E);
1662 case BO_GE: return Success(Result.getInt() >= RHS, E);
1663 case BO_EQ: return Success(Result.getInt() == RHS, E);
1664 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001665 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001666}
1667
Ken Dyck160146e2010-01-27 17:10:57 +00001668CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001669 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1670 // the result is the size of the referenced type."
1671 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1672 // result shall be the alignment of the referenced type."
1673 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1674 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00001675
1676 // __alignof is defined to return the preferred alignment.
1677 return Info.Ctx.toCharUnitsFromBits(
1678 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001679}
1680
Ken Dyck160146e2010-01-27 17:10:57 +00001681CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001682 E = E->IgnoreParens();
1683
1684 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001685 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001686 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001687 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1688 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001689
Chris Lattner68061312009-01-24 21:53:27 +00001690 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001691 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1692 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001693
Chris Lattner24aeeab2009-01-24 21:09:06 +00001694 return GetAlignOfType(E->getType());
1695}
1696
1697
Peter Collingbournee190dee2011-03-11 19:24:49 +00001698/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1699/// a result as the expression's type.
1700bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1701 const UnaryExprOrTypeTraitExpr *E) {
1702 switch(E->getKind()) {
1703 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001704 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00001705 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001706 else
Ken Dyckdbc01912011-03-11 02:13:43 +00001707 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001708 }
Eli Friedman64004332009-03-23 04:38:34 +00001709
Peter Collingbournee190dee2011-03-11 19:24:49 +00001710 case UETT_VecStep: {
1711 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00001712
Peter Collingbournee190dee2011-03-11 19:24:49 +00001713 if (Ty->isVectorType()) {
1714 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00001715
Peter Collingbournee190dee2011-03-11 19:24:49 +00001716 // The vec_step built-in functions that take a 3-component
1717 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1718 if (n == 3)
1719 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001720
Peter Collingbournee190dee2011-03-11 19:24:49 +00001721 return Success(n, E);
1722 } else
1723 return Success(1, E);
1724 }
1725
1726 case UETT_SizeOf: {
1727 QualType SrcTy = E->getTypeOfArgument();
1728 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1729 // the result is the size of the referenced type."
1730 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1731 // result shall be the alignment of the referenced type."
1732 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1733 SrcTy = Ref->getPointeeType();
1734
1735 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1736 // extension.
1737 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1738 return Success(1, E);
1739
1740 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1741 if (!SrcTy->isConstantSizeType())
1742 return false;
1743
1744 // Get information about the size.
1745 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1746 }
1747 }
1748
1749 llvm_unreachable("unknown expr/type trait");
1750 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001751}
1752
Peter Collingbournee9200682011-05-13 03:29:01 +00001753bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00001754 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00001755 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00001756 if (n == 0)
1757 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001758 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00001759 for (unsigned i = 0; i != n; ++i) {
1760 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1761 switch (ON.getKind()) {
1762 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00001763 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00001764 APSInt IdxResult;
1765 if (!EvaluateInteger(Idx, IdxResult, Info))
1766 return false;
1767 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1768 if (!AT)
1769 return false;
1770 CurrentType = AT->getElementType();
1771 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1772 Result += IdxResult.getSExtValue() * ElementSize;
1773 break;
1774 }
1775
1776 case OffsetOfExpr::OffsetOfNode::Field: {
1777 FieldDecl *MemberDecl = ON.getField();
1778 const RecordType *RT = CurrentType->getAs<RecordType>();
1779 if (!RT)
1780 return false;
1781 RecordDecl *RD = RT->getDecl();
1782 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00001783 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00001784 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001785 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00001786 CurrentType = MemberDecl->getType().getNonReferenceType();
1787 break;
1788 }
1789
1790 case OffsetOfExpr::OffsetOfNode::Identifier:
1791 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001792 return false;
1793
1794 case OffsetOfExpr::OffsetOfNode::Base: {
1795 CXXBaseSpecifier *BaseSpec = ON.getBase();
1796 if (BaseSpec->isVirtual())
1797 return false;
1798
1799 // Find the layout of the class whose base we are looking into.
1800 const RecordType *RT = CurrentType->getAs<RecordType>();
1801 if (!RT)
1802 return false;
1803 RecordDecl *RD = RT->getDecl();
1804 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1805
1806 // Find the base class itself.
1807 CurrentType = BaseSpec->getType();
1808 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1809 if (!BaseRT)
1810 return false;
1811
1812 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00001813 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00001814 break;
1815 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001816 }
1817 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001818 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00001819}
1820
Chris Lattnere13042c2008-07-11 19:10:17 +00001821bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001822 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001823 // LNot's operand isn't necessarily an integer, so we handle it specially.
1824 bool bres;
1825 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1826 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001827 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001828 }
1829
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001830 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00001831 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001832 return false;
1833
Chris Lattnercdf34e72008-07-11 22:52:41 +00001834 // Get the operand value into 'Result'.
1835 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001836 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001837
Chris Lattnerf09ad162008-07-11 22:15:16 +00001838 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001839 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001840 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1841 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001842 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001843 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001844 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1845 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001846 return true;
John McCalle3027922010-08-25 11:45:40 +00001847 case UO_Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001848 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001849 return true;
John McCalle3027922010-08-25 11:45:40 +00001850 case UO_Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001851 if (!Result.isInt()) return false;
1852 return Success(-Result.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00001853 case UO_Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001854 if (!Result.isInt()) return false;
1855 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001856 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001857}
Mike Stump11289f42009-09-09 15:08:12 +00001858
Chris Lattner477c4be2008-07-12 01:15:53 +00001859/// HandleCast - This is used to evaluate implicit or explicit casts where the
1860/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00001861bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1862 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001863 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001864 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001865
Eli Friedmanc757de22011-03-25 00:43:55 +00001866 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00001867 case CK_BaseToDerived:
1868 case CK_DerivedToBase:
1869 case CK_UncheckedDerivedToBase:
1870 case CK_Dynamic:
1871 case CK_ToUnion:
1872 case CK_ArrayToPointerDecay:
1873 case CK_FunctionToPointerDecay:
1874 case CK_NullToPointer:
1875 case CK_NullToMemberPointer:
1876 case CK_BaseToDerivedMemberPointer:
1877 case CK_DerivedToBaseMemberPointer:
1878 case CK_ConstructorConversion:
1879 case CK_IntegralToPointer:
1880 case CK_ToVoid:
1881 case CK_VectorSplat:
1882 case CK_IntegralToFloating:
1883 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00001884 case CK_CPointerToObjCPointerCast:
1885 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001886 case CK_AnyPointerToBlockPointerCast:
1887 case CK_ObjCObjectLValueCast:
1888 case CK_FloatingRealToComplex:
1889 case CK_FloatingComplexToReal:
1890 case CK_FloatingComplexCast:
1891 case CK_FloatingComplexToIntegralComplex:
1892 case CK_IntegralRealToComplex:
1893 case CK_IntegralComplexCast:
1894 case CK_IntegralComplexToFloatingComplex:
1895 llvm_unreachable("invalid cast kind for integral value");
1896
Eli Friedman9faf2f92011-03-25 19:07:11 +00001897 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001898 case CK_Dependent:
1899 case CK_GetObjCProperty:
1900 case CK_LValueBitCast:
1901 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00001902 case CK_ARCProduceObject:
1903 case CK_ARCConsumeObject:
1904 case CK_ARCReclaimReturnedObject:
1905 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00001906 return false;
1907
1908 case CK_LValueToRValue:
1909 case CK_NoOp:
1910 return Visit(E->getSubExpr());
1911
1912 case CK_MemberPointerToBoolean:
1913 case CK_PointerToBoolean:
1914 case CK_IntegralToBoolean:
1915 case CK_FloatingToBoolean:
1916 case CK_FloatingComplexToBoolean:
1917 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00001918 bool BoolResult;
1919 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1920 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001921 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001922 }
1923
Eli Friedmanc757de22011-03-25 00:43:55 +00001924 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00001925 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001926 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001927
Eli Friedman742421e2009-02-20 01:15:07 +00001928 if (!Result.isInt()) {
1929 // Only allow casts of lvalues if they are lossless.
1930 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1931 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001932
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001933 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001934 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001935 }
Mike Stump11289f42009-09-09 15:08:12 +00001936
Eli Friedmanc757de22011-03-25 00:43:55 +00001937 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00001938 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001939 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001940 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001941
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001942 if (LV.getLValueBase()) {
1943 // Only allow based lvalue casts if they are lossless.
1944 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1945 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001946
John McCall45d55e42010-05-07 21:00:08 +00001947 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001948 return true;
1949 }
1950
Ken Dyck02990832010-01-15 12:37:54 +00001951 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1952 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001953 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001954 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001955
Eli Friedmanc757de22011-03-25 00:43:55 +00001956 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00001957 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001958 if (!EvaluateComplex(SubExpr, C, Info))
1959 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00001960 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001961 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001962
Eli Friedmanc757de22011-03-25 00:43:55 +00001963 case CK_FloatingToIntegral: {
1964 APFloat F(0.0);
1965 if (!EvaluateFloat(SubExpr, F, Info))
1966 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00001967
Eli Friedmanc757de22011-03-25 00:43:55 +00001968 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1969 }
1970 }
Mike Stump11289f42009-09-09 15:08:12 +00001971
Eli Friedmanc757de22011-03-25 00:43:55 +00001972 llvm_unreachable("unknown cast resulting in integral value");
1973 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001974}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001975
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001976bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1977 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001978 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001979 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1980 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1981 return Success(LV.getComplexIntReal(), E);
1982 }
1983
1984 return Visit(E->getSubExpr());
1985}
1986
Eli Friedman4e7a2412009-02-27 04:45:43 +00001987bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001988 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001989 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001990 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1991 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1992 return Success(LV.getComplexIntImag(), E);
1993 }
1994
Richard Smith725810a2011-10-16 21:26:27 +00001995 APValue Scratch;
1996 if (!Evaluate(Scratch, Info, E->getSubExpr()))
1997 Info.EvalStatus.HasSideEffects = true;
Eli Friedman4e7a2412009-02-27 04:45:43 +00001998 return Success(0, E);
1999}
2000
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002001bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2002 return Success(E->getPackLength(), E);
2003}
2004
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002005bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2006 return Success(E->getValue(), E);
2007}
2008
Chris Lattner05706e882008-07-11 18:11:29 +00002009//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002010// Float Evaluation
2011//===----------------------------------------------------------------------===//
2012
2013namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002014class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002015 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002016 APFloat &Result;
2017public:
2018 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002019 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002020
Peter Collingbournee9200682011-05-13 03:29:01 +00002021 bool Success(const APValue &V, const Expr *e) {
2022 Result = V.getFloat();
2023 return true;
2024 }
2025 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002026 return false;
2027 }
2028
Richard Smith4ce706a2011-10-11 21:43:33 +00002029 bool ValueInitialization(const Expr *E) {
2030 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2031 return true;
2032 }
2033
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002034 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002035
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002036 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002037 bool VisitBinaryOperator(const BinaryOperator *E);
2038 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002039 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002040
John McCallb1fb0d32010-05-07 22:08:54 +00002041 bool VisitUnaryReal(const UnaryOperator *E);
2042 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002043
John McCalla2fabff2010-10-09 01:34:31 +00002044 bool VisitDeclRefExpr(const DeclRefExpr *E);
2045
John McCallb1fb0d32010-05-07 22:08:54 +00002046 // FIXME: Missing: array subscript of vector, member of vector,
2047 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002048};
2049} // end anonymous namespace
2050
2051static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002052 assert(E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002053 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002054}
2055
Jay Foad39c79802011-01-12 09:06:06 +00002056static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002057 QualType ResultTy,
2058 const Expr *Arg,
2059 bool SNaN,
2060 llvm::APFloat &Result) {
2061 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2062 if (!S) return false;
2063
2064 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2065
2066 llvm::APInt fill;
2067
2068 // Treat empty strings as if they were zero.
2069 if (S->getString().empty())
2070 fill = llvm::APInt(32, 0);
2071 else if (S->getString().getAsInteger(0, fill))
2072 return false;
2073
2074 if (SNaN)
2075 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2076 else
2077 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2078 return true;
2079}
2080
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002081bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002082 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002083 default:
2084 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2085
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002086 case Builtin::BI__builtin_huge_val:
2087 case Builtin::BI__builtin_huge_valf:
2088 case Builtin::BI__builtin_huge_vall:
2089 case Builtin::BI__builtin_inf:
2090 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002091 case Builtin::BI__builtin_infl: {
2092 const llvm::fltSemantics &Sem =
2093 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002094 Result = llvm::APFloat::getInf(Sem);
2095 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002096 }
Mike Stump11289f42009-09-09 15:08:12 +00002097
John McCall16291492010-02-28 13:00:19 +00002098 case Builtin::BI__builtin_nans:
2099 case Builtin::BI__builtin_nansf:
2100 case Builtin::BI__builtin_nansl:
2101 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2102 true, Result);
2103
Chris Lattner0b7282e2008-10-06 06:31:58 +00002104 case Builtin::BI__builtin_nan:
2105 case Builtin::BI__builtin_nanf:
2106 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002107 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002108 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002109 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2110 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002111
2112 case Builtin::BI__builtin_fabs:
2113 case Builtin::BI__builtin_fabsf:
2114 case Builtin::BI__builtin_fabsl:
2115 if (!EvaluateFloat(E->getArg(0), Result, Info))
2116 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002117
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002118 if (Result.isNegative())
2119 Result.changeSign();
2120 return true;
2121
Mike Stump11289f42009-09-09 15:08:12 +00002122 case Builtin::BI__builtin_copysign:
2123 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002124 case Builtin::BI__builtin_copysignl: {
2125 APFloat RHS(0.);
2126 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2127 !EvaluateFloat(E->getArg(1), RHS, Info))
2128 return false;
2129 Result.copySign(RHS);
2130 return true;
2131 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002132 }
2133}
2134
John McCalla2fabff2010-10-09 01:34:31 +00002135bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002136 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2137 return true;
2138
John McCalla2fabff2010-10-09 01:34:31 +00002139 const Decl *D = E->getDecl();
2140 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2141 const VarDecl *VD = cast<VarDecl>(D);
2142
2143 // Require the qualifiers to be const and not volatile.
2144 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2145 if (!T.isConstQualified() || T.isVolatileQualified())
2146 return false;
2147
2148 const Expr *Init = VD->getAnyInitializer();
2149 if (!Init) return false;
2150
2151 if (APValue *V = VD->getEvaluatedValue()) {
2152 if (V->isFloat()) {
2153 Result = V->getFloat();
2154 return true;
2155 }
2156 return false;
2157 }
2158
2159 if (VD->isEvaluatingValue())
2160 return false;
2161
2162 VD->setEvaluatingValue();
2163
2164 Expr::EvalResult InitResult;
2165 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2166 InitResult.Val.isFloat()) {
2167 // Cache the evaluated value in the variable declaration.
2168 Result = InitResult.Val.getFloat();
2169 VD->setEvaluatedValue(InitResult.Val);
2170 return true;
2171 }
2172
2173 VD->setEvaluatedValue(APValue());
2174 return false;
2175}
2176
John McCallb1fb0d32010-05-07 22:08:54 +00002177bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002178 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2179 ComplexValue CV;
2180 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2181 return false;
2182 Result = CV.FloatReal;
2183 return true;
2184 }
2185
2186 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002187}
2188
2189bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002190 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2191 ComplexValue CV;
2192 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2193 return false;
2194 Result = CV.FloatImag;
2195 return true;
2196 }
2197
Richard Smith725810a2011-10-16 21:26:27 +00002198 APValue Scratch;
2199 if (!Evaluate(Scratch, Info, E->getSubExpr()))
2200 Info.EvalStatus.HasSideEffects = true;
Eli Friedman95719532010-08-14 20:52:13 +00002201 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2202 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002203 return true;
2204}
2205
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002206bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002207 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002208 return false;
2209
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002210 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2211 return false;
2212
2213 switch (E->getOpcode()) {
2214 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002215 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002216 return true;
John McCalle3027922010-08-25 11:45:40 +00002217 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002218 Result.changeSign();
2219 return true;
2220 }
2221}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002222
Eli Friedman24c01542008-08-22 00:06:13 +00002223bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002224 if (E->getOpcode() == BO_Comma) {
Eli Friedman141fbf32009-11-16 04:25:37 +00002225 if (!EvaluateFloat(E->getRHS(), Result, Info))
2226 return false;
2227
2228 // If we can't evaluate the LHS, it might have side effects;
2229 // conservatively mark it.
Richard Smith725810a2011-10-16 21:26:27 +00002230 APValue Scratch;
2231 if (!Evaluate(Scratch, Info, E->getLHS()))
2232 Info.EvalStatus.HasSideEffects = true;
Eli Friedman141fbf32009-11-16 04:25:37 +00002233
2234 return true;
2235 }
2236
Anders Carlssona5df61a2010-10-31 01:21:47 +00002237 // We can't evaluate pointer-to-member operations.
2238 if (E->isPtrMemOp())
2239 return false;
2240
Eli Friedman24c01542008-08-22 00:06:13 +00002241 // FIXME: Diagnostics? I really don't understand how the warnings
2242 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002243 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002244 if (!EvaluateFloat(E->getLHS(), Result, Info))
2245 return false;
2246 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2247 return false;
2248
2249 switch (E->getOpcode()) {
2250 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002251 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002252 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2253 return true;
John McCalle3027922010-08-25 11:45:40 +00002254 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002255 Result.add(RHS, APFloat::rmNearestTiesToEven);
2256 return true;
John McCalle3027922010-08-25 11:45:40 +00002257 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002258 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2259 return true;
John McCalle3027922010-08-25 11:45:40 +00002260 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002261 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2262 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002263 }
2264}
2265
2266bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2267 Result = E->getValue();
2268 return true;
2269}
2270
Peter Collingbournee9200682011-05-13 03:29:01 +00002271bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2272 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002273
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002274 switch (E->getCastKind()) {
2275 default:
2276 return false;
2277
2278 case CK_LValueToRValue:
2279 case CK_NoOp:
2280 return Visit(SubExpr);
2281
2282 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002283 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002284 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002285 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002286 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002287 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002288 return true;
2289 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002290
2291 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002292 if (!Visit(SubExpr))
2293 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002294 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2295 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002296 return true;
2297 }
John McCalld7646252010-11-14 08:17:51 +00002298
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002299 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002300 ComplexValue V;
2301 if (!EvaluateComplex(SubExpr, V, Info))
2302 return false;
2303 Result = V.getComplexFloatReal();
2304 return true;
2305 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002306 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002307
2308 return false;
2309}
2310
Eli Friedman24c01542008-08-22 00:06:13 +00002311//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002312// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002313//===----------------------------------------------------------------------===//
2314
2315namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002316class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002317 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002318 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002319
Anders Carlsson537969c2008-11-16 20:27:53 +00002320public:
John McCall93d91dc2010-05-07 17:22:02 +00002321 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002322 : ExprEvaluatorBaseTy(info), Result(Result) {}
2323
2324 bool Success(const APValue &V, const Expr *e) {
2325 Result.setFrom(V);
2326 return true;
2327 }
2328 bool Error(const Expr *E) {
2329 return false;
2330 }
Mike Stump11289f42009-09-09 15:08:12 +00002331
Anders Carlsson537969c2008-11-16 20:27:53 +00002332 //===--------------------------------------------------------------------===//
2333 // Visitor Methods
2334 //===--------------------------------------------------------------------===//
2335
Peter Collingbournee9200682011-05-13 03:29:01 +00002336 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002337
Peter Collingbournee9200682011-05-13 03:29:01 +00002338 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002339
John McCall93d91dc2010-05-07 17:22:02 +00002340 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002341 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002342 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002343};
2344} // end anonymous namespace
2345
John McCall93d91dc2010-05-07 17:22:02 +00002346static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2347 EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002348 assert(E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002349 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002350}
2351
Peter Collingbournee9200682011-05-13 03:29:01 +00002352bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2353 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002354
2355 if (SubExpr->getType()->isRealFloatingType()) {
2356 Result.makeComplexFloat();
2357 APFloat &Imag = Result.FloatImag;
2358 if (!EvaluateFloat(SubExpr, Imag, Info))
2359 return false;
2360
2361 Result.FloatReal = APFloat(Imag.getSemantics());
2362 return true;
2363 } else {
2364 assert(SubExpr->getType()->isIntegerType() &&
2365 "Unexpected imaginary literal.");
2366
2367 Result.makeComplexInt();
2368 APSInt &Imag = Result.IntImag;
2369 if (!EvaluateInteger(SubExpr, Imag, Info))
2370 return false;
2371
2372 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2373 return true;
2374 }
2375}
2376
Peter Collingbournee9200682011-05-13 03:29:01 +00002377bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002378
John McCallfcef3cf2010-12-14 17:51:41 +00002379 switch (E->getCastKind()) {
2380 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002381 case CK_BaseToDerived:
2382 case CK_DerivedToBase:
2383 case CK_UncheckedDerivedToBase:
2384 case CK_Dynamic:
2385 case CK_ToUnion:
2386 case CK_ArrayToPointerDecay:
2387 case CK_FunctionToPointerDecay:
2388 case CK_NullToPointer:
2389 case CK_NullToMemberPointer:
2390 case CK_BaseToDerivedMemberPointer:
2391 case CK_DerivedToBaseMemberPointer:
2392 case CK_MemberPointerToBoolean:
2393 case CK_ConstructorConversion:
2394 case CK_IntegralToPointer:
2395 case CK_PointerToIntegral:
2396 case CK_PointerToBoolean:
2397 case CK_ToVoid:
2398 case CK_VectorSplat:
2399 case CK_IntegralCast:
2400 case CK_IntegralToBoolean:
2401 case CK_IntegralToFloating:
2402 case CK_FloatingToIntegral:
2403 case CK_FloatingToBoolean:
2404 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002405 case CK_CPointerToObjCPointerCast:
2406 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002407 case CK_AnyPointerToBlockPointerCast:
2408 case CK_ObjCObjectLValueCast:
2409 case CK_FloatingComplexToReal:
2410 case CK_FloatingComplexToBoolean:
2411 case CK_IntegralComplexToReal:
2412 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002413 case CK_ARCProduceObject:
2414 case CK_ARCConsumeObject:
2415 case CK_ARCReclaimReturnedObject:
2416 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002417 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002418
John McCallfcef3cf2010-12-14 17:51:41 +00002419 case CK_LValueToRValue:
2420 case CK_NoOp:
2421 return Visit(E->getSubExpr());
2422
2423 case CK_Dependent:
2424 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002425 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002426 case CK_UserDefinedConversion:
2427 return false;
2428
2429 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002430 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002431 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002432 return false;
2433
John McCallfcef3cf2010-12-14 17:51:41 +00002434 Result.makeComplexFloat();
2435 Result.FloatImag = APFloat(Real.getSemantics());
2436 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002437 }
2438
John McCallfcef3cf2010-12-14 17:51:41 +00002439 case CK_FloatingComplexCast: {
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.FloatReal
2448 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2449 Result.FloatImag
2450 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2451 return true;
2452 }
2453
2454 case CK_FloatingComplexToIntegralComplex: {
2455 if (!Visit(E->getSubExpr()))
2456 return false;
2457
2458 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2459 QualType From
2460 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2461 Result.makeComplexInt();
2462 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2463 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2464 return true;
2465 }
2466
2467 case CK_IntegralRealToComplex: {
2468 APSInt &Real = Result.IntReal;
2469 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2470 return false;
2471
2472 Result.makeComplexInt();
2473 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2474 return true;
2475 }
2476
2477 case CK_IntegralComplexCast: {
2478 if (!Visit(E->getSubExpr()))
2479 return false;
2480
2481 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2482 QualType From
2483 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2484
2485 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2486 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2487 return true;
2488 }
2489
2490 case CK_IntegralComplexToFloatingComplex: {
2491 if (!Visit(E->getSubExpr()))
2492 return false;
2493
2494 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2495 QualType From
2496 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2497 Result.makeComplexFloat();
2498 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2499 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2500 return true;
2501 }
2502 }
2503
2504 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002505 return false;
2506}
2507
John McCall93d91dc2010-05-07 17:22:02 +00002508bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002509 if (E->getOpcode() == BO_Comma) {
2510 if (!Visit(E->getRHS()))
2511 return false;
2512
2513 // If we can't evaluate the LHS, it might have side effects;
2514 // conservatively mark it.
Richard Smith725810a2011-10-16 21:26:27 +00002515 APValue Scratch;
2516 if (!Evaluate(Scratch, Info, E->getLHS()))
2517 Info.EvalStatus.HasSideEffects = true;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002518
2519 return true;
2520 }
John McCall93d91dc2010-05-07 17:22:02 +00002521 if (!Visit(E->getLHS()))
2522 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002523
John McCall93d91dc2010-05-07 17:22:02 +00002524 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002525 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002526 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002527
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002528 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2529 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002530 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002531 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002532 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002533 if (Result.isComplexFloat()) {
2534 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2535 APFloat::rmNearestTiesToEven);
2536 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2537 APFloat::rmNearestTiesToEven);
2538 } else {
2539 Result.getComplexIntReal() += RHS.getComplexIntReal();
2540 Result.getComplexIntImag() += RHS.getComplexIntImag();
2541 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002542 break;
John McCalle3027922010-08-25 11:45:40 +00002543 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002544 if (Result.isComplexFloat()) {
2545 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2546 APFloat::rmNearestTiesToEven);
2547 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2548 APFloat::rmNearestTiesToEven);
2549 } else {
2550 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2551 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2552 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002553 break;
John McCalle3027922010-08-25 11:45:40 +00002554 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002555 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002556 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002557 APFloat &LHS_r = LHS.getComplexFloatReal();
2558 APFloat &LHS_i = LHS.getComplexFloatImag();
2559 APFloat &RHS_r = RHS.getComplexFloatReal();
2560 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002561
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002562 APFloat Tmp = LHS_r;
2563 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2564 Result.getComplexFloatReal() = Tmp;
2565 Tmp = LHS_i;
2566 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2567 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2568
2569 Tmp = LHS_r;
2570 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2571 Result.getComplexFloatImag() = Tmp;
2572 Tmp = LHS_i;
2573 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2574 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2575 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002576 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002577 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002578 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2579 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002580 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002581 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2582 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2583 }
2584 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002585 case BO_Div:
2586 if (Result.isComplexFloat()) {
2587 ComplexValue LHS = Result;
2588 APFloat &LHS_r = LHS.getComplexFloatReal();
2589 APFloat &LHS_i = LHS.getComplexFloatImag();
2590 APFloat &RHS_r = RHS.getComplexFloatReal();
2591 APFloat &RHS_i = RHS.getComplexFloatImag();
2592 APFloat &Res_r = Result.getComplexFloatReal();
2593 APFloat &Res_i = Result.getComplexFloatImag();
2594
2595 APFloat Den = RHS_r;
2596 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2597 APFloat Tmp = RHS_i;
2598 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2599 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2600
2601 Res_r = LHS_r;
2602 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2603 Tmp = LHS_i;
2604 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2605 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2606 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2607
2608 Res_i = LHS_i;
2609 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2610 Tmp = LHS_r;
2611 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2612 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2613 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2614 } else {
2615 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2616 // FIXME: what about diagnostics?
2617 return false;
2618 }
2619 ComplexValue LHS = Result;
2620 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2621 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2622 Result.getComplexIntReal() =
2623 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2624 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2625 Result.getComplexIntImag() =
2626 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2627 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2628 }
2629 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002630 }
2631
John McCall93d91dc2010-05-07 17:22:02 +00002632 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002633}
2634
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002635bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2636 // Get the operand value into 'Result'.
2637 if (!Visit(E->getSubExpr()))
2638 return false;
2639
2640 switch (E->getOpcode()) {
2641 default:
2642 // FIXME: what about diagnostics?
2643 return false;
2644 case UO_Extension:
2645 return true;
2646 case UO_Plus:
2647 // The result is always just the subexpr.
2648 return true;
2649 case UO_Minus:
2650 if (Result.isComplexFloat()) {
2651 Result.getComplexFloatReal().changeSign();
2652 Result.getComplexFloatImag().changeSign();
2653 }
2654 else {
2655 Result.getComplexIntReal() = -Result.getComplexIntReal();
2656 Result.getComplexIntImag() = -Result.getComplexIntImag();
2657 }
2658 return true;
2659 case UO_Not:
2660 if (Result.isComplexFloat())
2661 Result.getComplexFloatImag().changeSign();
2662 else
2663 Result.getComplexIntImag() = -Result.getComplexIntImag();
2664 return true;
2665 }
2666}
2667
Anders Carlsson537969c2008-11-16 20:27:53 +00002668//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002669// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002670//===----------------------------------------------------------------------===//
2671
Richard Smith725810a2011-10-16 21:26:27 +00002672static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00002673 if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002674 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002675 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002676 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002677 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002678 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002679 if (Result.isLValue() &&
2680 !IsGlobalLValue(Result.getLValueBase()))
John McCall11086fc2010-07-07 05:08:32 +00002681 return false;
John McCall45d55e42010-05-07 21:00:08 +00002682 } else if (E->getType()->hasPointerRepresentation()) {
2683 LValue LV;
2684 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002685 return false;
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002686 if (!IsGlobalLValue(LV.Base))
John McCall95007602010-05-10 23:27:23 +00002687 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002688 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00002689 } else if (E->getType()->isRealFloatingType()) {
2690 llvm::APFloat F(0.0);
2691 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002692 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002693
Richard Smith725810a2011-10-16 21:26:27 +00002694 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00002695 } else if (E->getType()->isAnyComplexType()) {
2696 ComplexValue C;
2697 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002698 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002699 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002700 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002701 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002702
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002703 return true;
2704}
2705
John McCallc07a0c72011-02-17 10:25:35 +00002706/// Evaluate - Return true if this is a constant which we can fold using
2707/// any crazy technique (that has nothing to do with language standards) that
2708/// we want to. If this function returns true, it returns the folded constant
2709/// in Result.
2710bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2711 EvalInfo Info(Ctx, Result);
Richard Smith725810a2011-10-16 21:26:27 +00002712 return ::Evaluate(Result.Val, Info, this);
John McCallc07a0c72011-02-17 10:25:35 +00002713}
2714
Jay Foad39c79802011-01-12 09:06:06 +00002715bool Expr::EvaluateAsBooleanCondition(bool &Result,
2716 const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00002717 EvalStatus Scratch;
John McCall1be1c632010-01-05 23:42:56 +00002718 EvalInfo Info(Ctx, Scratch);
2719
2720 return HandleConversionToBool(this, Result, Info);
2721}
2722
Richard Smithcaf33902011-10-10 18:28:20 +00002723bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00002724 EvalStatus Scratch;
Richard Smithcaf33902011-10-10 18:28:20 +00002725 EvalInfo Info(Ctx, Scratch);
2726
2727 return EvaluateInteger(this, Result, Info) && !Scratch.HasSideEffects;
2728}
2729
Jay Foad39c79802011-01-12 09:06:06 +00002730bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002731 EvalInfo Info(Ctx, Result);
2732
John McCall45d55e42010-05-07 21:00:08 +00002733 LValue LV;
John McCall95007602010-05-10 23:27:23 +00002734 if (EvaluateLValue(this, LV, Info) &&
2735 !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002736 IsGlobalLValue(LV.Base)) {
2737 LV.moveInto(Result.Val);
2738 return true;
2739 }
2740 return false;
2741}
2742
Jay Foad39c79802011-01-12 09:06:06 +00002743bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2744 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002745 EvalInfo Info(Ctx, Result);
2746
2747 LValue LV;
2748 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00002749 LV.moveInto(Result.Val);
2750 return true;
2751 }
2752 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00002753}
2754
Chris Lattner67d7b922008-11-16 21:24:15 +00002755/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002756/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00002757bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002758 EvalResult Result;
2759 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002760}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002761
Jay Foad39c79802011-01-12 09:06:06 +00002762bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00002763 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002764}
2765
Richard Smithcaf33902011-10-10 18:28:20 +00002766APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002767 EvalResult EvalResult;
2768 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002769 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002770 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002771 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002772
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002773 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002774}
John McCall864e3962010-05-07 05:32:02 +00002775
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002776 bool Expr::EvalResult::isGlobalLValue() const {
2777 assert(Val.isLValue());
2778 return IsGlobalLValue(Val.getLValueBase());
2779 }
2780
2781
John McCall864e3962010-05-07 05:32:02 +00002782/// isIntegerConstantExpr - this recursive routine will test if an expression is
2783/// an integer constant expression.
2784
2785/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2786/// comma, etc
2787///
2788/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2789/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2790/// cast+dereference.
2791
2792// CheckICE - This function does the fundamental ICE checking: the returned
2793// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2794// Note that to reduce code duplication, this helper does no evaluation
2795// itself; the caller checks whether the expression is evaluatable, and
2796// in the rare cases where CheckICE actually cares about the evaluated
2797// value, it calls into Evalute.
2798//
2799// Meanings of Val:
2800// 0: This expression is an ICE if it can be evaluated by Evaluate.
2801// 1: This expression is not an ICE, but if it isn't evaluated, it's
2802// a legal subexpression for an ICE. This return value is used to handle
2803// the comma operator in C99 mode.
2804// 2: This expression is not an ICE, and is not a legal subexpression for one.
2805
Dan Gohman28ade552010-07-26 21:25:24 +00002806namespace {
2807
John McCall864e3962010-05-07 05:32:02 +00002808struct ICEDiag {
2809 unsigned Val;
2810 SourceLocation Loc;
2811
2812 public:
2813 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2814 ICEDiag() : Val(0) {}
2815};
2816
Dan Gohman28ade552010-07-26 21:25:24 +00002817}
2818
2819static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00002820
2821static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2822 Expr::EvalResult EVResult;
2823 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2824 !EVResult.Val.isInt()) {
2825 return ICEDiag(2, E->getLocStart());
2826 }
2827 return NoDiag();
2828}
2829
2830static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2831 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00002832 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00002833 return ICEDiag(2, E->getLocStart());
2834 }
2835
2836 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00002837#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00002838#define STMT(Node, Base) case Expr::Node##Class:
2839#define EXPR(Node, Base)
2840#include "clang/AST/StmtNodes.inc"
2841 case Expr::PredefinedExprClass:
2842 case Expr::FloatingLiteralClass:
2843 case Expr::ImaginaryLiteralClass:
2844 case Expr::StringLiteralClass:
2845 case Expr::ArraySubscriptExprClass:
2846 case Expr::MemberExprClass:
2847 case Expr::CompoundAssignOperatorClass:
2848 case Expr::CompoundLiteralExprClass:
2849 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00002850 case Expr::DesignatedInitExprClass:
2851 case Expr::ImplicitValueInitExprClass:
2852 case Expr::ParenListExprClass:
2853 case Expr::VAArgExprClass:
2854 case Expr::AddrLabelExprClass:
2855 case Expr::StmtExprClass:
2856 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00002857 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00002858 case Expr::CXXDynamicCastExprClass:
2859 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00002860 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00002861 case Expr::CXXNullPtrLiteralExprClass:
2862 case Expr::CXXThisExprClass:
2863 case Expr::CXXThrowExprClass:
2864 case Expr::CXXNewExprClass:
2865 case Expr::CXXDeleteExprClass:
2866 case Expr::CXXPseudoDestructorExprClass:
2867 case Expr::UnresolvedLookupExprClass:
2868 case Expr::DependentScopeDeclRefExprClass:
2869 case Expr::CXXConstructExprClass:
2870 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00002871 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00002872 case Expr::CXXTemporaryObjectExprClass:
2873 case Expr::CXXUnresolvedConstructExprClass:
2874 case Expr::CXXDependentScopeMemberExprClass:
2875 case Expr::UnresolvedMemberExprClass:
2876 case Expr::ObjCStringLiteralClass:
2877 case Expr::ObjCEncodeExprClass:
2878 case Expr::ObjCMessageExprClass:
2879 case Expr::ObjCSelectorExprClass:
2880 case Expr::ObjCProtocolExprClass:
2881 case Expr::ObjCIvarRefExprClass:
2882 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00002883 case Expr::ObjCIsaExprClass:
2884 case Expr::ShuffleVectorExprClass:
2885 case Expr::BlockExprClass:
2886 case Expr::BlockDeclRefExprClass:
2887 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00002888 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00002889 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00002890 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00002891 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00002892 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00002893 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002894 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00002895 return ICEDiag(2, E->getLocStart());
2896
Sebastian Redl12757ab2011-09-24 17:48:14 +00002897 case Expr::InitListExprClass:
2898 if (Ctx.getLangOptions().CPlusPlus0x) {
2899 const InitListExpr *ILE = cast<InitListExpr>(E);
2900 if (ILE->getNumInits() == 0)
2901 return NoDiag();
2902 if (ILE->getNumInits() == 1)
2903 return CheckICE(ILE->getInit(0), Ctx);
2904 // Fall through for more than 1 expression.
2905 }
2906 return ICEDiag(2, E->getLocStart());
2907
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002908 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00002909 case Expr::GNUNullExprClass:
2910 // GCC considers the GNU __null value to be an integral constant expression.
2911 return NoDiag();
2912
John McCall7c454bb2011-07-15 05:09:51 +00002913 case Expr::SubstNonTypeTemplateParmExprClass:
2914 return
2915 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2916
John McCall864e3962010-05-07 05:32:02 +00002917 case Expr::ParenExprClass:
2918 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002919 case Expr::GenericSelectionExprClass:
2920 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002921 case Expr::IntegerLiteralClass:
2922 case Expr::CharacterLiteralClass:
2923 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00002924 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00002925 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002926 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00002927 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00002928 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00002929 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00002930 return NoDiag();
2931 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00002932 case Expr::CXXOperatorCallExprClass: {
John McCall864e3962010-05-07 05:32:02 +00002933 const CallExpr *CE = cast<CallExpr>(E);
2934 if (CE->isBuiltinCall(Ctx))
2935 return CheckEvalInICE(E, Ctx);
2936 return ICEDiag(2, E->getLocStart());
2937 }
2938 case Expr::DeclRefExprClass:
2939 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2940 return NoDiag();
2941 if (Ctx.getLangOptions().CPlusPlus &&
2942 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2943 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2944
2945 // Parameter variables are never constants. Without this check,
2946 // getAnyInitializer() can find a default argument, which leads
2947 // to chaos.
2948 if (isa<ParmVarDecl>(D))
2949 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2950
2951 // C++ 7.1.5.1p2
2952 // A variable of non-volatile const-qualified integral or enumeration
2953 // type initialized by an ICE can be used in ICEs.
2954 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2955 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2956 if (Quals.hasVolatile() || !Quals.hasConst())
2957 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2958
2959 // Look for a declaration of this variable that has an initializer.
2960 const VarDecl *ID = 0;
2961 const Expr *Init = Dcl->getAnyInitializer(ID);
2962 if (Init) {
2963 if (ID->isInitKnownICE()) {
2964 // We have already checked whether this subexpression is an
2965 // integral constant expression.
2966 if (ID->isInitICE())
2967 return NoDiag();
2968 else
2969 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2970 }
2971
2972 // It's an ICE whether or not the definition we found is
2973 // out-of-line. See DR 721 and the discussion in Clang PR
2974 // 6206 for details.
2975
2976 if (Dcl->isCheckingICE()) {
2977 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2978 }
2979
2980 Dcl->setCheckingICE();
2981 ICEDiag Result = CheckICE(Init, Ctx);
2982 // Cache the result of the ICE test.
2983 Dcl->setInitKnownICE(Result.Val == 0);
2984 return Result;
2985 }
2986 }
2987 }
2988 return ICEDiag(2, E->getLocStart());
2989 case Expr::UnaryOperatorClass: {
2990 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2991 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002992 case UO_PostInc:
2993 case UO_PostDec:
2994 case UO_PreInc:
2995 case UO_PreDec:
2996 case UO_AddrOf:
2997 case UO_Deref:
John McCall864e3962010-05-07 05:32:02 +00002998 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00002999 case UO_Extension:
3000 case UO_LNot:
3001 case UO_Plus:
3002 case UO_Minus:
3003 case UO_Not:
3004 case UO_Real:
3005 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003006 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003007 }
3008
3009 // OffsetOf falls through here.
3010 }
3011 case Expr::OffsetOfExprClass: {
3012 // Note that per C99, offsetof must be an ICE. And AFAIK, using
3013 // Evaluate matches the proposed gcc behavior for cases like
3014 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
3015 // compliance: we should warn earlier for offsetof expressions with
3016 // array subscripts that aren't ICEs, and if the array subscripts
3017 // are ICEs, the value of the offsetof must be an integer constant.
3018 return CheckEvalInICE(E, Ctx);
3019 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003020 case Expr::UnaryExprOrTypeTraitExprClass: {
3021 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3022 if ((Exp->getKind() == UETT_SizeOf) &&
3023 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003024 return ICEDiag(2, E->getLocStart());
3025 return NoDiag();
3026 }
3027 case Expr::BinaryOperatorClass: {
3028 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3029 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003030 case BO_PtrMemD:
3031 case BO_PtrMemI:
3032 case BO_Assign:
3033 case BO_MulAssign:
3034 case BO_DivAssign:
3035 case BO_RemAssign:
3036 case BO_AddAssign:
3037 case BO_SubAssign:
3038 case BO_ShlAssign:
3039 case BO_ShrAssign:
3040 case BO_AndAssign:
3041 case BO_XorAssign:
3042 case BO_OrAssign:
John McCall864e3962010-05-07 05:32:02 +00003043 return ICEDiag(2, E->getLocStart());
3044
John McCalle3027922010-08-25 11:45:40 +00003045 case BO_Mul:
3046 case BO_Div:
3047 case BO_Rem:
3048 case BO_Add:
3049 case BO_Sub:
3050 case BO_Shl:
3051 case BO_Shr:
3052 case BO_LT:
3053 case BO_GT:
3054 case BO_LE:
3055 case BO_GE:
3056 case BO_EQ:
3057 case BO_NE:
3058 case BO_And:
3059 case BO_Xor:
3060 case BO_Or:
3061 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003062 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3063 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003064 if (Exp->getOpcode() == BO_Div ||
3065 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00003066 // Evaluate gives an error for undefined Div/Rem, so make sure
3067 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003068 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003069 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003070 if (REval == 0)
3071 return ICEDiag(1, E->getLocStart());
3072 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003073 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003074 if (LEval.isMinSignedValue())
3075 return ICEDiag(1, E->getLocStart());
3076 }
3077 }
3078 }
John McCalle3027922010-08-25 11:45:40 +00003079 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003080 if (Ctx.getLangOptions().C99) {
3081 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3082 // if it isn't evaluated.
3083 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3084 return ICEDiag(1, E->getLocStart());
3085 } else {
3086 // In both C89 and C++, commas in ICEs are illegal.
3087 return ICEDiag(2, E->getLocStart());
3088 }
3089 }
3090 if (LHSResult.Val >= RHSResult.Val)
3091 return LHSResult;
3092 return RHSResult;
3093 }
John McCalle3027922010-08-25 11:45:40 +00003094 case BO_LAnd:
3095 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003096 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003097
3098 // C++0x [expr.const]p2:
3099 // [...] subexpressions of logical AND (5.14), logical OR
3100 // (5.15), and condi- tional (5.16) operations that are not
3101 // evaluated are not considered.
3102 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3103 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003104 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003105 return LHSResult;
3106
3107 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003108 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003109 return LHSResult;
3110 }
3111
John McCall864e3962010-05-07 05:32:02 +00003112 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3113 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3114 // Rare case where the RHS has a comma "side-effect"; we need
3115 // to actually check the condition to see whether the side
3116 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003117 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003118 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003119 return RHSResult;
3120 return NoDiag();
3121 }
3122
3123 if (LHSResult.Val >= RHSResult.Val)
3124 return LHSResult;
3125 return RHSResult;
3126 }
3127 }
3128 }
3129 case Expr::ImplicitCastExprClass:
3130 case Expr::CStyleCastExprClass:
3131 case Expr::CXXFunctionalCastExprClass:
3132 case Expr::CXXStaticCastExprClass:
3133 case Expr::CXXReinterpretCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003134 case Expr::CXXConstCastExprClass:
3135 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003136 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman76d4e432011-09-29 21:49:34 +00003137 switch (cast<CastExpr>(E)->getCastKind()) {
3138 case CK_LValueToRValue:
3139 case CK_NoOp:
3140 case CK_IntegralToBoolean:
3141 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003142 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003143 default:
3144 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3145 return NoDiag();
3146 return ICEDiag(2, E->getLocStart());
3147 }
John McCall864e3962010-05-07 05:32:02 +00003148 }
John McCallc07a0c72011-02-17 10:25:35 +00003149 case Expr::BinaryConditionalOperatorClass: {
3150 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3151 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3152 if (CommonResult.Val == 2) return CommonResult;
3153 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3154 if (FalseResult.Val == 2) return FalseResult;
3155 if (CommonResult.Val == 1) return CommonResult;
3156 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003157 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003158 return FalseResult;
3159 }
John McCall864e3962010-05-07 05:32:02 +00003160 case Expr::ConditionalOperatorClass: {
3161 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3162 // If the condition (ignoring parens) is a __builtin_constant_p call,
3163 // then only the true side is actually considered in an integer constant
3164 // expression, and it is fully evaluated. This is an important GNU
3165 // extension. See GCC PR38377 for discussion.
3166 if (const CallExpr *CallCE
3167 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3168 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3169 Expr::EvalResult EVResult;
3170 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3171 !EVResult.Val.isInt()) {
3172 return ICEDiag(2, E->getLocStart());
3173 }
3174 return NoDiag();
3175 }
3176 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003177 if (CondResult.Val == 2)
3178 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003179
3180 // C++0x [expr.const]p2:
3181 // subexpressions of [...] conditional (5.16) operations that
3182 // are not evaluated are not considered
3183 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003184 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003185 : false;
3186 ICEDiag TrueResult = NoDiag();
3187 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3188 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3189 ICEDiag FalseResult = NoDiag();
3190 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3191 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3192
John McCall864e3962010-05-07 05:32:02 +00003193 if (TrueResult.Val == 2)
3194 return TrueResult;
3195 if (FalseResult.Val == 2)
3196 return FalseResult;
3197 if (CondResult.Val == 1)
3198 return CondResult;
3199 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3200 return NoDiag();
3201 // Rare case where the diagnostics depend on which side is evaluated
3202 // Note that if we get here, CondResult is 0, and at least one of
3203 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003204 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003205 return FalseResult;
3206 }
3207 return TrueResult;
3208 }
3209 case Expr::CXXDefaultArgExprClass:
3210 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3211 case Expr::ChooseExprClass: {
3212 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3213 }
3214 }
3215
3216 // Silence a GCC warning
3217 return ICEDiag(2, E->getLocStart());
3218}
3219
3220bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3221 SourceLocation *Loc, bool isEvaluated) const {
3222 ICEDiag d = CheckICE(this, Ctx);
3223 if (d.Val != 0) {
3224 if (Loc) *Loc = d.Loc;
3225 return false;
3226 }
3227 EvalResult EvalResult;
3228 if (!Evaluate(EvalResult, Ctx))
3229 llvm_unreachable("ICE cannot be evaluated!");
3230 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3231 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3232 Result = EvalResult.Val.getInt();
3233 return true;
3234}