blob: 1be23fc990385dedb143e731f5c4a90e55c001f8 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Benjamin Kramer024e6192011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
49 /// EvalResult - Contains information about the evaluation.
50 Expr::EvalResult &EvalResult;
51
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
61 : Ctx(ctx), EvalResult(evalresult) {}
62 };
63
John McCall93d91dc2010-05-07 17:22:02 +000064 struct ComplexValue {
65 private:
66 bool IsInt;
67
68 public:
69 APSInt IntReal, IntImag;
70 APFloat FloatReal, FloatImag;
71
72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
73
74 void makeComplexFloat() { IsInt = false; }
75 bool isComplexFloat() const { return !IsInt; }
76 APFloat &getComplexFloatReal() { return FloatReal; }
77 APFloat &getComplexFloatImag() { return FloatImag; }
78
79 void makeComplexInt() { IsInt = true; }
80 bool isComplexInt() const { return IsInt; }
81 APSInt &getComplexIntReal() { return IntReal; }
82 APSInt &getComplexIntImag() { return IntImag; }
83
John McCallc07a0c72011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCallc07a0c72011-02-17 10:25:35 +000090 void setFrom(const APValue &v) {
91 assert(v.isComplexFloat() || v.isComplexInt());
92 if (v.isComplexFloat()) {
93 makeComplexFloat();
94 FloatReal = v.getComplexFloatReal();
95 FloatImag = v.getComplexFloatImag();
96 } else {
97 makeComplexInt();
98 IntReal = v.getComplexIntReal();
99 IntImag = v.getComplexIntImag();
100 }
101 }
John McCall93d91dc2010-05-07 17:22:02 +0000102 };
John McCall45d55e42010-05-07 21:00:08 +0000103
104 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000105 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000106 CharUnits Offset;
107
Peter Collingbournee9200682011-05-13 03:29:01 +0000108 const Expr *getLValueBase() { return Base; }
John McCall45d55e42010-05-07 21:00:08 +0000109 CharUnits getLValueOffset() { return Offset; }
110
John McCallc07a0c72011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCall45d55e42010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCallc07a0c72011-02-17 10:25:35 +0000114 void setFrom(const APValue &v) {
115 assert(v.isLValue());
116 Base = v.getLValueBase();
117 Offset = v.getLValueOffset();
118 }
John McCall45d55e42010-05-07 21:00:08 +0000119 };
John McCall93d91dc2010-05-07 17:22:02 +0000120}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000121
John McCallc07a0c72011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattner6c4d2552009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000136 if (!E) return true;
137
138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
139 if (isa<FunctionDecl>(DRE->getDecl()))
140 return true;
141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
142 return VD->hasGlobalStorage();
143 return false;
144 }
145
146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
147 return CLE->isFileScope();
148
149 return true;
150}
151
John McCall45d55e42010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000154
John McCalleb3e4f32010-05-07 21:34:32 +0000155 // A null base expression indicates a null pointer. These are always
156 // evaluatable, and they are false unless the offset is zero.
157 if (!Base) {
158 Result = !Value.Offset.isZero();
159 return true;
160 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000161
John McCall95007602010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000164
John McCalleb3e4f32010-05-07 21:34:32 +0000165 // We have a non-null base expression. These are generally known to
166 // be true, but if it'a decl-ref to a weak symbol it can be null at
167 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCalleb3e4f32010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman334046a2009-06-14 02:17:33 +0000181 return true;
182}
183
John McCall1be1c632010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000187 APSInt IntResult;
188 if (!EvaluateInteger(E, IntResult, Info))
189 return false;
190 Result = IntResult != 0;
191 return true;
192 } else if (E->getType()->isRealFloatingType()) {
193 APFloat FloatResult(0.0);
194 if (!EvaluateFloat(E, FloatResult, Info))
195 return false;
196 Result = !FloatResult.isZero();
197 return true;
Eli Friedman64004332009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman9a156e52008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman334046a2009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedman64004332009-03-23 04:38:34 +0000205 if (!EvaluateComplex(E, ComplexResult, Info))
206 return false;
207 if (ComplexResult.isComplexFloat()) {
208 Result = !ComplexResult.getComplexFloatReal().isZero() ||
209 !ComplexResult.getComplexFloatImag().isZero();
210 } else {
211 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
212 ComplexResult.getComplexIntImag().getBoolValue();
213 }
214 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump11289f42009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000224 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000225
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
227 uint64_t Space[4];
228 bool ignored;
229 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
230 llvm::APFloat::rmTowardZero, &ignored);
231 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
232}
233
Mike Stump11289f42009-09-09 15:08:12 +0000234static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000235 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000236 bool ignored;
237 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000238 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000239 APFloat::rmNearestTiesToEven, &ignored);
240 return Result;
241}
242
Mike Stump11289f42009-09-09 15:08:12 +0000243static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000244 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000245 unsigned DestWidth = Ctx.getIntWidth(DestType);
246 APSInt Result = Value;
247 // Figure out if this is a truncate, extend or noop cast.
248 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000249 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000250 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000251 return Result;
252}
253
Mike Stump11289f42009-09-09 15:08:12 +0000254static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000255 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000256
257 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
258 Result.convertFromAPInt(Value, Value.isSigned(),
259 APFloat::rmNearestTiesToEven);
260 return Result;
261}
262
Mike Stump876387b2009-10-27 22:09:17 +0000263namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000264class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000265 : public ConstStmtVisitor<HasSideEffect, bool> {
Mike Stump876387b2009-10-27 22:09:17 +0000266 EvalInfo &Info;
267public:
268
269 HasSideEffect(EvalInfo &info) : Info(info) {}
270
271 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000272 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000273 return true;
274 }
275
Peter Collingbournee9200682011-05-13 03:29:01 +0000276 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
277 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000278 return Visit(E->getResultExpr());
279 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000280 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000281 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000282 return true;
283 return false;
284 }
John McCall31168b02011-06-15 23:02:42 +0000285 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
286 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
287 return true;
288 return false;
289 }
290 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
291 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
292 return true;
293 return false;
294 }
295
Mike Stump876387b2009-10-27 22:09:17 +0000296 // We don't want to evaluate BlockExprs multiple times, as they generate
297 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000298 bool VisitBlockExpr(const BlockExpr *E) { return true; }
299 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
300 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000301 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000302 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
303 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
304 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
305 bool VisitStringLiteral(const StringLiteral *E) { return false; }
306 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
307 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000308 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000309 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000310 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000311 bool VisitChooseExpr(const ChooseExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000312 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000313 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
314 bool VisitBinAssign(const BinaryOperator *E) { return true; }
315 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
316 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000317 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000318 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
319 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
320 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
321 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
322 bool VisitUnaryDeref(const UnaryOperator *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000323 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000324 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000325 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000326 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000327 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000328
329 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000330 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000331 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
332 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000333 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000334 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000335 return false;
336 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000337
Peter Collingbournee9200682011-05-13 03:29:01 +0000338 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000339};
340
John McCallc07a0c72011-02-17 10:25:35 +0000341class OpaqueValueEvaluation {
342 EvalInfo &info;
343 OpaqueValueExpr *opaqueValue;
344
345public:
346 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
347 Expr *value)
348 : info(info), opaqueValue(opaqueValue) {
349
350 // If evaluation fails, fail immediately.
351 if (!Evaluate(info, value)) {
352 this->opaqueValue = 0;
353 return;
354 }
355 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
356 }
357
358 bool hasError() const { return opaqueValue == 0; }
359
360 ~OpaqueValueEvaluation() {
361 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
362 }
363};
364
Mike Stump876387b2009-10-27 22:09:17 +0000365} // end anonymous namespace
366
Eli Friedman9a156e52008-11-12 09:44:48 +0000367//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000368// Generic Evaluation
369//===----------------------------------------------------------------------===//
370namespace {
371
372template <class Derived, typename RetTy=void>
373class ExprEvaluatorBase
374 : public ConstStmtVisitor<Derived, RetTy> {
375private:
376 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
377 return static_cast<Derived*>(this)->Success(V, E);
378 }
379 RetTy DerivedError(const Expr *E) {
380 return static_cast<Derived*>(this)->Error(E);
381 }
382
383protected:
384 EvalInfo &Info;
385 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
386 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
387
388public:
389 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
390
391 RetTy VisitStmt(const Stmt *) {
392 assert(0 && "Expression evaluator should not be called on stmts");
393 return DerivedError(0);
394 }
395 RetTy VisitExpr(const Expr *E) {
396 return DerivedError(E);
397 }
398
399 RetTy VisitParenExpr(const ParenExpr *E)
400 { return StmtVisitorTy::Visit(E->getSubExpr()); }
401 RetTy VisitUnaryExtension(const UnaryOperator *E)
402 { return StmtVisitorTy::Visit(E->getSubExpr()); }
403 RetTy VisitUnaryPlus(const UnaryOperator *E)
404 { return StmtVisitorTy::Visit(E->getSubExpr()); }
405 RetTy VisitChooseExpr(const ChooseExpr *E)
406 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
407 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
408 { return StmtVisitorTy::Visit(E->getResultExpr()); }
409
410 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
411 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
412 if (opaque.hasError())
413 return DerivedError(E);
414
415 bool cond;
416 if (!HandleConversionToBool(E->getCond(), cond, Info))
417 return DerivedError(E);
418
419 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
420 }
421
422 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
423 bool BoolResult;
424 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
425 return DerivedError(E);
426
427 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
428 return StmtVisitorTy::Visit(EvalExpr);
429 }
430
431 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
432 const APValue *value = Info.getOpaqueValue(E);
433 if (!value)
434 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
435 : DerivedError(E));
436 return DerivedSuccess(*value, E);
437 }
438};
439
440}
441
442//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000443// LValue Evaluation
444//===----------------------------------------------------------------------===//
445namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000446class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000447 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000448 LValue &Result;
449
Peter Collingbournee9200682011-05-13 03:29:01 +0000450 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000451 Result.Base = E;
452 Result.Offset = CharUnits::Zero();
453 return true;
454 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000455public:
Mike Stump11289f42009-09-09 15:08:12 +0000456
John McCall45d55e42010-05-07 21:00:08 +0000457 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Peter Collingbournee9200682011-05-13 03:29:01 +0000458 ExprEvaluatorBaseTy(info), Result(Result) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000459
Peter Collingbournee9200682011-05-13 03:29:01 +0000460 bool Success(const APValue &V, const Expr *E) {
461 Result.setFrom(V);
462 return true;
463 }
464 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000465 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000466 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000467
Peter Collingbournee9200682011-05-13 03:29:01 +0000468 bool VisitDeclRefExpr(const DeclRefExpr *E);
469 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
470 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
471 bool VisitMemberExpr(const MemberExpr *E);
472 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
473 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
474 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
475 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000476
Peter Collingbournee9200682011-05-13 03:29:01 +0000477 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000478 switch (E->getCastKind()) {
479 default:
John McCall45d55e42010-05-07 21:00:08 +0000480 return false;
Anders Carlssonde55f642009-10-03 16:30:22 +0000481
John McCalle3027922010-08-25 11:45:40 +0000482 case CK_NoOp:
Anders Carlssonde55f642009-10-03 16:30:22 +0000483 return Visit(E->getSubExpr());
484 }
485 }
Eli Friedman449fe542009-03-23 04:56:01 +0000486 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000487
Eli Friedman9a156e52008-11-12 09:44:48 +0000488};
489} // end anonymous namespace
490
John McCall45d55e42010-05-07 21:00:08 +0000491static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000492 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000493}
494
Peter Collingbournee9200682011-05-13 03:29:01 +0000495bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000496 if (isa<FunctionDecl>(E->getDecl())) {
John McCall45d55e42010-05-07 21:00:08 +0000497 return Success(E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000498 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000499 if (!VD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000500 return Success(E);
Chandler Carruthe299ba62010-05-16 09:32:51 +0000501 // Reference parameters can refer to anything even if they have an
502 // "initializer" in the form of a default argument.
Peter Collingbournee9200682011-05-13 03:29:01 +0000503 if (!isa<ParmVarDecl>(VD))
504 // FIXME: Check whether VD might be overridden!
505 if (const Expr *Init = VD->getAnyInitializer())
506 return Visit(Init);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000507 }
508
Peter Collingbournee9200682011-05-13 03:29:01 +0000509 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000510}
511
Peter Collingbournee9200682011-05-13 03:29:01 +0000512bool
513LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000514 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000515}
516
Peter Collingbournee9200682011-05-13 03:29:01 +0000517bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000518 QualType Ty;
519 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000520 if (!EvaluatePointer(E->getBase(), Result, Info))
521 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000522 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000523 } else {
John McCall45d55e42010-05-07 21:00:08 +0000524 if (!Visit(E->getBase()))
525 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000526 Ty = E->getBase()->getType();
527 }
528
Peter Collingbournee9200682011-05-13 03:29:01 +0000529 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000530 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000531
Peter Collingbournee9200682011-05-13 03:29:01 +0000532 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000533 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000534 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000535
536 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000537 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000538
Eli Friedman9a156e52008-11-12 09:44:48 +0000539 // FIXME: This is linear time.
Douglas Gregor91f84212008-12-11 16:49:14 +0000540 unsigned i = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000541 for (RecordDecl::field_iterator Field = RD->field_begin(),
542 FieldEnd = RD->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +0000543 Field != FieldEnd; (void)++Field, ++i) {
544 if (*Field == FD)
Eli Friedman9a156e52008-11-12 09:44:48 +0000545 break;
546 }
547
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000548 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000549 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000550}
551
Peter Collingbournee9200682011-05-13 03:29:01 +0000552bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000553 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000554 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000555
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000556 APSInt Index;
557 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000558 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000559
Ken Dyck40775002010-01-11 17:06:35 +0000560 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000561 Result.Offset += Index.getSExtValue() * ElementSize;
562 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000563}
Eli Friedman9a156e52008-11-12 09:44:48 +0000564
Peter Collingbournee9200682011-05-13 03:29:01 +0000565bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +0000566 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000567}
568
Eli Friedman9a156e52008-11-12 09:44:48 +0000569//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000570// Pointer Evaluation
571//===----------------------------------------------------------------------===//
572
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000573namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000574class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000575 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000576 LValue &Result;
577
Peter Collingbournee9200682011-05-13 03:29:01 +0000578 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000579 Result.Base = E;
580 Result.Offset = CharUnits::Zero();
581 return true;
582 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000583public:
Mike Stump11289f42009-09-09 15:08:12 +0000584
John McCall45d55e42010-05-07 21:00:08 +0000585 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000586 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000587
Peter Collingbournee9200682011-05-13 03:29:01 +0000588 bool Success(const APValue &V, const Expr *E) {
589 Result.setFrom(V);
590 return true;
591 }
592 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +0000593 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000594 }
595
John McCall45d55e42010-05-07 21:00:08 +0000596 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000597 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +0000598 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000599 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +0000600 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000601 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000602 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000603 bool VisitCallExpr(const CallExpr *E);
604 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +0000605 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000606 return Success(E);
607 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000608 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000609 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000610 { return Success((Expr*)0); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000611 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000612 { return Success((Expr*)0); }
John McCallc07a0c72011-02-17 10:25:35 +0000613
Eli Friedman449fe542009-03-23 04:56:01 +0000614 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000615};
Chris Lattner05706e882008-07-11 18:11:29 +0000616} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000617
John McCall45d55e42010-05-07 21:00:08 +0000618static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000619 assert(E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +0000620 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +0000621}
622
John McCall45d55e42010-05-07 21:00:08 +0000623bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000624 if (E->getOpcode() != BO_Add &&
625 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +0000626 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000627
Chris Lattner05706e882008-07-11 18:11:29 +0000628 const Expr *PExp = E->getLHS();
629 const Expr *IExp = E->getRHS();
630 if (IExp->getType()->isPointerType())
631 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000632
John McCall45d55e42010-05-07 21:00:08 +0000633 if (!EvaluatePointer(PExp, Result, Info))
634 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000635
John McCall45d55e42010-05-07 21:00:08 +0000636 llvm::APSInt Offset;
637 if (!EvaluateInteger(IExp, Offset, Info))
638 return false;
639 int64_t AdditionalOffset
640 = Offset.isSigned() ? Offset.getSExtValue()
641 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +0000642
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000643 // Compute the new offset in the appropriate width.
644
645 QualType PointeeType =
646 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +0000647 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +0000648
Anders Carlssonef56fba2009-02-19 04:55:58 +0000649 // Explicitly handle GNU void* and function pointer arithmetic extensions.
650 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +0000651 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +0000652 else
John McCall45d55e42010-05-07 21:00:08 +0000653 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +0000654
John McCalle3027922010-08-25 11:45:40 +0000655 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +0000656 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000657 else
John McCall45d55e42010-05-07 21:00:08 +0000658 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000659
John McCall45d55e42010-05-07 21:00:08 +0000660 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000661}
Eli Friedman9a156e52008-11-12 09:44:48 +0000662
John McCall45d55e42010-05-07 21:00:08 +0000663bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
664 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000665}
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattner05706e882008-07-11 18:11:29 +0000667
Peter Collingbournee9200682011-05-13 03:29:01 +0000668bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
669 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000670
Eli Friedman847a2bc2009-12-27 05:43:15 +0000671 switch (E->getCastKind()) {
672 default:
673 break;
674
John McCalle3027922010-08-25 11:45:40 +0000675 case CK_NoOp:
676 case CK_BitCast:
John McCalle3027922010-08-25 11:45:40 +0000677 case CK_AnyPointerToObjCPointerCast:
678 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +0000679 return Visit(SubExpr);
680
Anders Carlsson18275092010-10-31 20:41:46 +0000681 case CK_DerivedToBase:
682 case CK_UncheckedDerivedToBase: {
683 LValue BaseLV;
684 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
685 return false;
686
687 // Now figure out the necessary offset to add to the baseLV to get from
688 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +0000689 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +0000690
691 QualType Ty = E->getSubExpr()->getType();
692 const CXXRecordDecl *DerivedDecl =
693 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
694
695 for (CastExpr::path_const_iterator PathI = E->path_begin(),
696 PathE = E->path_end(); PathI != PathE; ++PathI) {
697 const CXXBaseSpecifier *Base = *PathI;
698
699 // FIXME: If the base is virtual, we'd need to determine the type of the
700 // most derived class and we don't support that right now.
701 if (Base->isVirtual())
702 return false;
703
704 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
705 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
706
Ken Dyck02155cb2011-01-26 02:17:08 +0000707 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +0000708 DerivedDecl = BaseDecl;
709 }
710
711 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +0000712 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +0000713 return true;
714 }
715
John McCalle84af4e2010-11-13 01:35:44 +0000716 case CK_NullToPointer: {
717 Result.Base = 0;
718 Result.Offset = CharUnits::Zero();
719 return true;
720 }
721
John McCalle3027922010-08-25 11:45:40 +0000722 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +0000723 APValue Value;
724 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000725 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000726
John McCall45d55e42010-05-07 21:00:08 +0000727 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000728 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-05-07 21:00:08 +0000729 Result.Base = 0;
730 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
731 return true;
732 } else {
733 // Cast is of an lvalue, no need to change value.
734 Result.Base = Value.getLValueBase();
735 Result.Offset = Value.getLValueOffset();
736 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000737 }
738 }
John McCalle3027922010-08-25 11:45:40 +0000739 case CK_ArrayToPointerDecay:
740 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +0000741 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000742 }
743
John McCall45d55e42010-05-07 21:00:08 +0000744 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000745}
Chris Lattner05706e882008-07-11 18:11:29 +0000746
Peter Collingbournee9200682011-05-13 03:29:01 +0000747bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000748 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000749 Builtin::BI__builtin___CFStringMakeConstantString ||
750 E->isBuiltinCall(Info.Ctx) ==
751 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +0000752 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000753
Peter Collingbournee9200682011-05-13 03:29:01 +0000754 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000755}
Chris Lattner05706e882008-07-11 18:11:29 +0000756
757//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000758// Vector Evaluation
759//===----------------------------------------------------------------------===//
760
761namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000762 class VectorExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000763 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman3ae59112009-02-23 04:23:56 +0000764 APValue GetZeroVector(QualType VecType);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000765 public:
Mike Stump11289f42009-09-09 15:08:12 +0000766
Peter Collingbournee9200682011-05-13 03:29:01 +0000767 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump11289f42009-09-09 15:08:12 +0000768
Peter Collingbournee9200682011-05-13 03:29:01 +0000769 APValue Success(const APValue &V, const Expr *E) { return V; }
770 APValue Error(const Expr *E) { return APValue(); }
Mike Stump11289f42009-09-09 15:08:12 +0000771
Eli Friedman3ae59112009-02-23 04:23:56 +0000772 APValue VisitUnaryReal(const UnaryOperator *E)
773 { return Visit(E->getSubExpr()); }
774 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
775 { return GetZeroVector(E->getType()); }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000776 APValue VisitCastExpr(const CastExpr* E);
777 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
778 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000779 APValue VisitUnaryImag(const UnaryOperator *E);
780 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000781 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000782 // shufflevector, ExtVectorElementExpr
783 // (Note that these require implementing conversions
784 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000785 };
786} // end anonymous namespace
787
788static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
789 if (!E->getType()->isVectorType())
790 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +0000791 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000792 return !Result.isUninit();
793}
794
795APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall9dd450b2009-09-21 23:43:11 +0000796 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000797 QualType EltTy = VTy->getElementType();
798 unsigned NElts = VTy->getNumElements();
799 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000800
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000801 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000802 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000803
Eli Friedmanc757de22011-03-25 00:43:55 +0000804 switch (E->getCastKind()) {
805 case CK_VectorSplat: {
806 APValue Result = APValue();
807 if (SETy->isIntegerType()) {
808 APSInt IntResult;
809 if (!EvaluateInteger(SE, IntResult, Info))
810 return APValue();
811 Result = APValue(IntResult);
812 } else if (SETy->isRealFloatingType()) {
813 APFloat F(0.0);
814 if (!EvaluateFloat(SE, F, Info))
815 return APValue();
816 Result = APValue(F);
817 } else {
Anders Carlsson6fc22042011-03-25 11:22:47 +0000818 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000819 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000820
821 // Splat and create vector APValue.
822 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
823 return APValue(&Elts[0], Elts.size());
Nate Begeman2ffd3842009-06-26 18:22:18 +0000824 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000825 case CK_BitCast: {
826 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +0000827 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000828
Eli Friedmanc757de22011-03-25 00:43:55 +0000829 if (!SETy->isIntegerType())
Anders Carlsson6fc22042011-03-25 11:22:47 +0000830 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000831
Eli Friedmanc757de22011-03-25 00:43:55 +0000832 APSInt Init;
833 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000834 return APValue();
835
Eli Friedmanc757de22011-03-25 00:43:55 +0000836 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
837 "Vectors must be composed of ints or floats");
838
839 llvm::SmallVector<APValue, 4> Elts;
840 for (unsigned i = 0; i != NElts; ++i) {
841 APSInt Tmp = Init.extOrTrunc(EltWidth);
842
843 if (EltTy->isIntegerType())
844 Elts.push_back(APValue(Tmp));
845 else
846 Elts.push_back(APValue(APFloat(Tmp)));
847
848 Init >>= EltWidth;
849 }
850 return APValue(&Elts[0], Elts.size());
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000851 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000852 case CK_LValueToRValue:
853 case CK_NoOp:
Peter Collingbournee9200682011-05-13 03:29:01 +0000854 return Visit(SE);
Eli Friedmanc757de22011-03-25 00:43:55 +0000855 default:
Anders Carlsson6fc22042011-03-25 11:22:47 +0000856 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000857 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000858}
859
Mike Stump11289f42009-09-09 15:08:12 +0000860APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000861VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000862 return this->Visit(E->getInitializer());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000863}
864
Mike Stump11289f42009-09-09 15:08:12 +0000865APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000866VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall9dd450b2009-09-21 23:43:11 +0000867 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000868 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000869 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000870
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000871 QualType EltTy = VT->getElementType();
872 llvm::SmallVector<APValue, 4> Elements;
873
John McCall875679e2010-06-11 17:54:15 +0000874 // If a vector is initialized with a single element, that value
875 // becomes every element of the vector, not just the first.
876 // This is the behavior described in the IBM AltiVec documentation.
877 if (NumInits == 1) {
Tanya Lattner5ac257d2011-04-15 22:42:59 +0000878
879 // Handle the case where the vector is initialized by a another
880 // vector (OpenCL 6.1.6).
881 if (E->getInit(0)->getType()->isVectorType())
882 return this->Visit(const_cast<Expr*>(E->getInit(0)));
883
John McCall875679e2010-06-11 17:54:15 +0000884 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000885 if (EltTy->isIntegerType()) {
886 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +0000887 if (!EvaluateInteger(E->getInit(0), sInt, Info))
888 return APValue();
889 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000890 } else {
891 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +0000892 if (!EvaluateFloat(E->getInit(0), f, Info))
893 return APValue();
894 InitValue = APValue(f);
895 }
896 for (unsigned i = 0; i < NumElements; i++) {
897 Elements.push_back(InitValue);
898 }
899 } else {
900 for (unsigned i = 0; i < NumElements; i++) {
901 if (EltTy->isIntegerType()) {
902 llvm::APSInt sInt(32);
903 if (i < NumInits) {
904 if (!EvaluateInteger(E->getInit(i), sInt, Info))
905 return APValue();
906 } else {
907 sInt = Info.Ctx.MakeIntValue(0, EltTy);
908 }
909 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +0000910 } else {
John McCall875679e2010-06-11 17:54:15 +0000911 llvm::APFloat f(0.0);
912 if (i < NumInits) {
913 if (!EvaluateFloat(E->getInit(i), f, Info))
914 return APValue();
915 } else {
916 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
917 }
918 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +0000919 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000920 }
921 }
922 return APValue(&Elements[0], Elements.size());
923}
924
Mike Stump11289f42009-09-09 15:08:12 +0000925APValue
Eli Friedman3ae59112009-02-23 04:23:56 +0000926VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +0000927 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +0000928 QualType EltTy = VT->getElementType();
929 APValue ZeroElement;
930 if (EltTy->isIntegerType())
931 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
932 else
933 ZeroElement =
934 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
935
936 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
937 return APValue(&Elements[0], Elements.size());
938}
939
Eli Friedman3ae59112009-02-23 04:23:56 +0000940APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
941 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
942 Info.EvalResult.HasSideEffects = true;
943 return GetZeroVector(E->getType());
944}
945
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000946//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000947// Integer Evaluation
948//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000949
950namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000951class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000952 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000953 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000954public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000955 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000956 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000957
Abramo Bagnara2caedf42011-06-30 09:36:05 +0000958 bool Success(const llvm::APSInt &SI, QualType Ty) {
959 assert(Ty->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +0000960 "Invalid evaluation result.");
Abramo Bagnara2caedf42011-06-30 09:36:05 +0000961 assert(SI.isSigned() == Ty->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000962 "Invalid evaluation result.");
Abramo Bagnara2caedf42011-06-30 09:36:05 +0000963 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(Ty) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000964 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000965 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000966 return true;
967 }
968
Abramo Bagnara2caedf42011-06-30 09:36:05 +0000969 bool Success(const llvm::APSInt &SI, const Expr *E) {
970 return Success(SI, E->getType());
971 }
972
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000973 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000974 assert(E->getType()->isIntegralOrEnumerationType() &&
975 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000976 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000977 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000978 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000979 Result.getInt().setIsUnsigned(
980 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000981 return true;
982 }
983
984 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000985 assert(E->getType()->isIntegralOrEnumerationType() &&
986 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000987 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000988 return true;
989 }
990
Ken Dyckdbc01912011-03-11 02:13:43 +0000991 bool Success(CharUnits Size, const Expr *E) {
992 return Success(Size.getQuantity(), E);
993 }
994
995
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000996 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000997 // Take the first error.
Anders Carlssonbd1df8e2008-11-30 16:38:33 +0000998 if (Info.EvalResult.Diag == 0) {
999 Info.EvalResult.DiagLoc = L;
1000 Info.EvalResult.Diag = D;
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001001 Info.EvalResult.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001002 }
Chris Lattner99415702008-07-12 00:14:42 +00001003 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001004 }
Mike Stump11289f42009-09-09 15:08:12 +00001005
Peter Collingbournee9200682011-05-13 03:29:01 +00001006 bool Success(const APValue &V, const Expr *E) {
1007 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001008 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001009 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001010 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001011 }
Mike Stump11289f42009-09-09 15:08:12 +00001012
Peter Collingbournee9200682011-05-13 03:29:01 +00001013 //===--------------------------------------------------------------------===//
1014 // Visitor Methods
1015 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001016
Chris Lattner7174bf32008-07-12 00:38:25 +00001017 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001018 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001019 }
1020 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001021 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001022 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001023
1024 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1025 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001026 if (CheckReferencedDecl(E, E->getDecl()))
1027 return true;
1028
1029 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001030 }
1031 bool VisitMemberExpr(const MemberExpr *E) {
1032 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1033 // Conservatively assume a MemberExpr will have side-effects
1034 Info.EvalResult.HasSideEffects = true;
1035 return true;
1036 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001037
1038 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001039 }
1040
Peter Collingbournee9200682011-05-13 03:29:01 +00001041 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001042 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001043 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001044 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001045
Peter Collingbournee9200682011-05-13 03:29:01 +00001046 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001047 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001048
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001049 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001050 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001051 }
Mike Stump11289f42009-09-09 15:08:12 +00001052
Anders Carlsson39def3a2008-12-21 22:39:40 +00001053 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001054 return Success(0, E);
Anders Carlsson39def3a2008-12-21 22:39:40 +00001055 }
Mike Stump11289f42009-09-09 15:08:12 +00001056
Douglas Gregor747eb782010-07-08 06:14:04 +00001057 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001058 return Success(0, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001059 }
1060
Eli Friedman4e7a2412009-02-27 04:45:43 +00001061 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1062 return Success(0, E);
1063 }
1064
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001065 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001066 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001067 }
1068
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001069 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1070 return Success(E->getValue(), E);
1071 }
1072
John Wiegley6242b6a2011-04-28 00:16:57 +00001073 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1074 return Success(E->getValue(), E);
1075 }
1076
John Wiegleyf9f65842011-04-25 06:54:41 +00001077 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1078 return Success(E->getValue(), E);
1079 }
1080
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001081 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001082 bool VisitUnaryImag(const UnaryOperator *E);
1083
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001084 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001085 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1086
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001087private:
Ken Dyck160146e2010-01-27 17:10:57 +00001088 CharUnits GetAlignOfExpr(const Expr *E);
1089 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001090 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001091 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001092 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001093};
Chris Lattner05706e882008-07-11 18:11:29 +00001094} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001095
Daniel Dunbarce399542009-02-20 18:22:23 +00001096static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001097 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001098 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001099}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001100
Daniel Dunbarce399542009-02-20 18:22:23 +00001101static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001102 assert(E->getType()->isIntegralOrEnumerationType());
John McCallf0c4f352010-05-07 05:46:35 +00001103
Daniel Dunbarce399542009-02-20 18:22:23 +00001104 APValue Val;
1105 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1106 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001107 Result = Val.getInt();
1108 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001109}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001110
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001111bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001112 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001113 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
1114 // Note: provide the type of ECD (rather than that of E),
1115 // so that signedness/width will match the ECD init value.
1116 return Success(ECD->getInitVal(), ECD->getType());
1117 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001118
1119 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +00001120 // In C, they can also be folded, although they are not ICEs.
Douglas Gregor0840cc02009-11-01 20:32:48 +00001121 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1122 == Qualifiers::Const) {
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001123
1124 if (isa<ParmVarDecl>(D))
Peter Collingbournee9200682011-05-13 03:29:01 +00001125 return false;
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001126
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001127 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001128 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedman1d6fb162009-12-03 20:31:57 +00001129 if (APValue *V = VD->getEvaluatedValue()) {
1130 if (V->isInt())
1131 return Success(V->getInt(), E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001132 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001133 }
1134
1135 if (VD->isEvaluatingValue())
Peter Collingbournee9200682011-05-13 03:29:01 +00001136 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001137
1138 VD->setEvaluatingValue();
1139
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001140 Expr::EvalResult EResult;
1141 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1142 EResult.Val.isInt()) {
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001143 // Cache the evaluated value in the variable declaration.
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001144 Result = EResult.Val;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001145 VD->setEvaluatedValue(Result);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001146 return true;
1147 }
1148
Eli Friedman1d6fb162009-12-03 20:31:57 +00001149 VD->setEvaluatedValue(APValue());
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001150 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001151 }
1152 }
1153
Chris Lattner7174bf32008-07-12 00:38:25 +00001154 // Otherwise, random variable references are not constants.
Peter Collingbournee9200682011-05-13 03:29:01 +00001155 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001156}
1157
Chris Lattner86ee2862008-10-06 06:40:35 +00001158/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1159/// as GCC.
1160static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1161 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001162 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001163 enum gcc_type_class {
1164 no_type_class = -1,
1165 void_type_class, integer_type_class, char_type_class,
1166 enumeral_type_class, boolean_type_class,
1167 pointer_type_class, reference_type_class, offset_type_class,
1168 real_type_class, complex_type_class,
1169 function_type_class, method_type_class,
1170 record_type_class, union_type_class,
1171 array_type_class, string_type_class,
1172 lang_type_class
1173 };
Mike Stump11289f42009-09-09 15:08:12 +00001174
1175 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001176 // ideal, however it is what gcc does.
1177 if (E->getNumArgs() == 0)
1178 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001179
Chris Lattner86ee2862008-10-06 06:40:35 +00001180 QualType ArgTy = E->getArg(0)->getType();
1181 if (ArgTy->isVoidType())
1182 return void_type_class;
1183 else if (ArgTy->isEnumeralType())
1184 return enumeral_type_class;
1185 else if (ArgTy->isBooleanType())
1186 return boolean_type_class;
1187 else if (ArgTy->isCharType())
1188 return string_type_class; // gcc doesn't appear to use char_type_class
1189 else if (ArgTy->isIntegerType())
1190 return integer_type_class;
1191 else if (ArgTy->isPointerType())
1192 return pointer_type_class;
1193 else if (ArgTy->isReferenceType())
1194 return reference_type_class;
1195 else if (ArgTy->isRealType())
1196 return real_type_class;
1197 else if (ArgTy->isComplexType())
1198 return complex_type_class;
1199 else if (ArgTy->isFunctionType())
1200 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001201 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001202 return record_type_class;
1203 else if (ArgTy->isUnionType())
1204 return union_type_class;
1205 else if (ArgTy->isArrayType())
1206 return array_type_class;
1207 else if (ArgTy->isUnionType())
1208 return union_type_class;
1209 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1210 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1211 return -1;
1212}
1213
John McCall95007602010-05-10 23:27:23 +00001214/// Retrieves the "underlying object type" of the given expression,
1215/// as used by __builtin_object_size.
1216QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1217 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1218 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1219 return VD->getType();
1220 } else if (isa<CompoundLiteralExpr>(E)) {
1221 return E->getType();
1222 }
1223
1224 return QualType();
1225}
1226
Peter Collingbournee9200682011-05-13 03:29:01 +00001227bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001228 // TODO: Perhaps we should let LLVM lower this?
1229 LValue Base;
1230 if (!EvaluatePointer(E->getArg(0), Base, Info))
1231 return false;
1232
1233 // If we can prove the base is null, lower to zero now.
1234 const Expr *LVBase = Base.getLValueBase();
1235 if (!LVBase) return Success(0, E);
1236
1237 QualType T = GetObjectType(LVBase);
1238 if (T.isNull() ||
1239 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001240 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001241 T->isVariablyModifiedType() ||
1242 T->isDependentType())
1243 return false;
1244
1245 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1246 CharUnits Offset = Base.getLValueOffset();
1247
1248 if (!Offset.isNegative() && Offset <= Size)
1249 Size -= Offset;
1250 else
1251 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001252 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001253}
1254
Peter Collingbournee9200682011-05-13 03:29:01 +00001255bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001256 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001257 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001258 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001259
1260 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001261 if (TryEvaluateBuiltinObjectSize(E))
1262 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001263
Eric Christopher99469702010-01-19 22:58:35 +00001264 // If evaluating the argument has side-effects we can't determine
1265 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001266 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer0128f662010-01-03 18:18:37 +00001267 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001268 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001269 return Success(0, E);
1270 }
Mike Stump876387b2009-10-27 22:09:17 +00001271
Mike Stump722cedf2009-10-26 18:35:08 +00001272 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1273 }
1274
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001275 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001276 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001277
Anders Carlsson4c76e932008-11-24 04:21:33 +00001278 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001279 // __builtin_constant_p always has one operand: it returns true if that
1280 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001281 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001282
1283 case Builtin::BI__builtin_eh_return_data_regno: {
1284 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1285 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1286 return Success(Operand, E);
1287 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001288
1289 case Builtin::BI__builtin_expect:
1290 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001291
1292 case Builtin::BIstrlen:
1293 case Builtin::BI__builtin_strlen:
1294 // As an extension, we support strlen() and __builtin_strlen() as constant
1295 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001296 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001297 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1298 // The string literal may have embedded null characters. Find the first
1299 // one and truncate there.
1300 llvm::StringRef Str = S->getString();
1301 llvm::StringRef::size_type Pos = Str.find(0);
1302 if (Pos != llvm::StringRef::npos)
1303 Str = Str.substr(0, Pos);
1304
1305 return Success(Str.size(), E);
1306 }
1307
1308 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001309 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001310}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001311
Chris Lattnere13042c2008-07-11 19:10:17 +00001312bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001313 if (E->getOpcode() == BO_Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001314 if (!Visit(E->getRHS()))
1315 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001316
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001317 // If we can't evaluate the LHS, it might have side effects;
1318 // conservatively mark it.
1319 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1320 Info.EvalResult.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001321
Anders Carlsson564730a2008-12-01 02:07:06 +00001322 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001323 }
1324
1325 if (E->isLogicalOp()) {
1326 // These need to be handled specially because the operands aren't
1327 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001328 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001329
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001330 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001331 // We were able to evaluate the LHS, see if we can get away with not
1332 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001333 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001334 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001335
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001336 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001337 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001338 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001339 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001340 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001341 }
1342 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001343 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001344 // We can't evaluate the LHS; however, sometimes the result
1345 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001346 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1347 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001348 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001349 // must have had side effects.
1350 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001351
1352 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001353 }
1354 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001355 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001356
Eli Friedman5a332ea2008-11-13 06:09:17 +00001357 return false;
1358 }
1359
Anders Carlssonacc79812008-11-16 07:17:21 +00001360 QualType LHSTy = E->getLHS()->getType();
1361 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001362
1363 if (LHSTy->isAnyComplexType()) {
1364 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001365 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001366
1367 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1368 return false;
1369
1370 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1371 return false;
1372
1373 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001374 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001375 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001376 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001377 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1378
John McCalle3027922010-08-25 11:45:40 +00001379 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001380 return Success((CR_r == APFloat::cmpEqual &&
1381 CR_i == APFloat::cmpEqual), E);
1382 else {
John McCalle3027922010-08-25 11:45:40 +00001383 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001384 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001385 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001386 CR_r == APFloat::cmpLessThan ||
1387 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001388 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001389 CR_i == APFloat::cmpLessThan ||
1390 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001391 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001392 } else {
John McCalle3027922010-08-25 11:45:40 +00001393 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001394 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1395 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1396 else {
John McCalle3027922010-08-25 11:45:40 +00001397 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001398 "Invalid compex comparison.");
1399 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1400 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1401 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001402 }
1403 }
Mike Stump11289f42009-09-09 15:08:12 +00001404
Anders Carlssonacc79812008-11-16 07:17:21 +00001405 if (LHSTy->isRealFloatingType() &&
1406 RHSTy->isRealFloatingType()) {
1407 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001408
Anders Carlssonacc79812008-11-16 07:17:21 +00001409 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1410 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001411
Anders Carlssonacc79812008-11-16 07:17:21 +00001412 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1413 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001414
Anders Carlssonacc79812008-11-16 07:17:21 +00001415 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001416
Anders Carlssonacc79812008-11-16 07:17:21 +00001417 switch (E->getOpcode()) {
1418 default:
1419 assert(0 && "Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001420 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001421 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001422 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001423 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001424 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001425 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001426 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001427 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001428 E);
John McCalle3027922010-08-25 11:45:40 +00001429 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001430 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001431 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001432 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001433 || CR == APFloat::cmpLessThan
1434 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001435 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001436 }
Mike Stump11289f42009-09-09 15:08:12 +00001437
Eli Friedmana38da572009-04-28 19:17:36 +00001438 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001439 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001440 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001441 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1442 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001443
John McCall45d55e42010-05-07 21:00:08 +00001444 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001445 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1446 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001447
Eli Friedman334046a2009-06-14 02:17:33 +00001448 // Reject any bases from the normal codepath; we special-case comparisons
1449 // to null.
1450 if (LHSValue.getLValueBase()) {
1451 if (!E->isEqualityOp())
1452 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001453 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001454 return false;
1455 bool bres;
1456 if (!EvalPointerValueAsBool(LHSValue, bres))
1457 return false;
John McCalle3027922010-08-25 11:45:40 +00001458 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001459 } else if (RHSValue.getLValueBase()) {
1460 if (!E->isEqualityOp())
1461 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001462 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001463 return false;
1464 bool bres;
1465 if (!EvalPointerValueAsBool(RHSValue, bres))
1466 return false;
John McCalle3027922010-08-25 11:45:40 +00001467 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001468 }
Eli Friedman64004332009-03-23 04:38:34 +00001469
John McCalle3027922010-08-25 11:45:40 +00001470 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001471 QualType Type = E->getLHS()->getType();
1472 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001473
Ken Dyck02990832010-01-15 12:37:54 +00001474 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001475 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001476 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001477
Ken Dyck02990832010-01-15 12:37:54 +00001478 CharUnits Diff = LHSValue.getLValueOffset() -
1479 RHSValue.getLValueOffset();
1480 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001481 }
1482 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001483 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001484 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001485 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001486 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1487 }
1488 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001489 }
1490 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001491 if (!LHSTy->isIntegralOrEnumerationType() ||
1492 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001493 // We can't continue from here for non-integral types, and they
1494 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001495 return false;
1496 }
1497
Anders Carlsson9c181652008-07-08 14:35:21 +00001498 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001499 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001500 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001501
Eli Friedman94c25c62009-03-24 01:14:50 +00001502 APValue RHSVal;
1503 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001504 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001505
1506 // Handle cases like (unsigned long)&a + 4.
1507 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001508 CharUnits Offset = Result.getLValueOffset();
1509 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1510 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001511 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001512 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001513 else
Ken Dyck02990832010-01-15 12:37:54 +00001514 Offset -= AdditionalOffset;
1515 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001516 return true;
1517 }
1518
1519 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001520 if (E->getOpcode() == BO_Add &&
Eli Friedman94c25c62009-03-24 01:14:50 +00001521 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001522 CharUnits Offset = RHSVal.getLValueOffset();
1523 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1524 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001525 return true;
1526 }
1527
1528 // All the following cases expect both operands to be an integer
1529 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001530 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001531
Eli Friedman94c25c62009-03-24 01:14:50 +00001532 APSInt& RHS = RHSVal.getInt();
1533
Anders Carlsson9c181652008-07-08 14:35:21 +00001534 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001535 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001536 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001537 case BO_Mul: return Success(Result.getInt() * RHS, E);
1538 case BO_Add: return Success(Result.getInt() + RHS, E);
1539 case BO_Sub: return Success(Result.getInt() - RHS, E);
1540 case BO_And: return Success(Result.getInt() & RHS, E);
1541 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1542 case BO_Or: return Success(Result.getInt() | RHS, E);
1543 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001544 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001545 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001546 return Success(Result.getInt() / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001547 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001548 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001549 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001550 return Success(Result.getInt() % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001551 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001552 // During constant-folding, a negative shift is an opposite shift.
1553 if (RHS.isSigned() && RHS.isNegative()) {
1554 RHS = -RHS;
1555 goto shift_right;
1556 }
1557
1558 shift_left:
1559 unsigned SA
1560 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001561 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001562 }
John McCalle3027922010-08-25 11:45:40 +00001563 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001564 // During constant-folding, a negative shift is an opposite shift.
1565 if (RHS.isSigned() && RHS.isNegative()) {
1566 RHS = -RHS;
1567 goto shift_left;
1568 }
1569
1570 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001571 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001572 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1573 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001574 }
Mike Stump11289f42009-09-09 15:08:12 +00001575
John McCalle3027922010-08-25 11:45:40 +00001576 case BO_LT: return Success(Result.getInt() < RHS, E);
1577 case BO_GT: return Success(Result.getInt() > RHS, E);
1578 case BO_LE: return Success(Result.getInt() <= RHS, E);
1579 case BO_GE: return Success(Result.getInt() >= RHS, E);
1580 case BO_EQ: return Success(Result.getInt() == RHS, E);
1581 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001582 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001583}
1584
Ken Dyck160146e2010-01-27 17:10:57 +00001585CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001586 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1587 // the result is the size of the referenced type."
1588 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1589 // result shall be the alignment of the referenced type."
1590 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1591 T = Ref->getPointeeType();
1592
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001593 // __alignof is defined to return the preferred alignment.
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001594 return Info.Ctx.toCharUnitsFromBits(
1595 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001596}
1597
Ken Dyck160146e2010-01-27 17:10:57 +00001598CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001599 E = E->IgnoreParens();
1600
1601 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001602 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001603 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001604 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1605 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001606
Chris Lattner68061312009-01-24 21:53:27 +00001607 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001608 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1609 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001610
Chris Lattner24aeeab2009-01-24 21:09:06 +00001611 return GetAlignOfType(E->getType());
1612}
1613
1614
Peter Collingbournee190dee2011-03-11 19:24:49 +00001615/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1616/// a result as the expression's type.
1617bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1618 const UnaryExprOrTypeTraitExpr *E) {
1619 switch(E->getKind()) {
1620 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001621 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00001622 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001623 else
Ken Dyckdbc01912011-03-11 02:13:43 +00001624 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001625 }
Eli Friedman64004332009-03-23 04:38:34 +00001626
Peter Collingbournee190dee2011-03-11 19:24:49 +00001627 case UETT_VecStep: {
1628 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00001629
Peter Collingbournee190dee2011-03-11 19:24:49 +00001630 if (Ty->isVectorType()) {
1631 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00001632
Peter Collingbournee190dee2011-03-11 19:24:49 +00001633 // The vec_step built-in functions that take a 3-component
1634 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1635 if (n == 3)
1636 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001637
Peter Collingbournee190dee2011-03-11 19:24:49 +00001638 return Success(n, E);
1639 } else
1640 return Success(1, E);
1641 }
1642
1643 case UETT_SizeOf: {
1644 QualType SrcTy = E->getTypeOfArgument();
1645 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1646 // the result is the size of the referenced type."
1647 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1648 // result shall be the alignment of the referenced type."
1649 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1650 SrcTy = Ref->getPointeeType();
1651
1652 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1653 // extension.
1654 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1655 return Success(1, E);
1656
1657 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1658 if (!SrcTy->isConstantSizeType())
1659 return false;
1660
1661 // Get information about the size.
1662 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1663 }
1664 }
1665
1666 llvm_unreachable("unknown expr/type trait");
1667 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001668}
1669
Peter Collingbournee9200682011-05-13 03:29:01 +00001670bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00001671 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00001672 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00001673 if (n == 0)
1674 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001675 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00001676 for (unsigned i = 0; i != n; ++i) {
1677 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1678 switch (ON.getKind()) {
1679 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00001680 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00001681 APSInt IdxResult;
1682 if (!EvaluateInteger(Idx, IdxResult, Info))
1683 return false;
1684 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1685 if (!AT)
1686 return false;
1687 CurrentType = AT->getElementType();
1688 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1689 Result += IdxResult.getSExtValue() * ElementSize;
1690 break;
1691 }
1692
1693 case OffsetOfExpr::OffsetOfNode::Field: {
1694 FieldDecl *MemberDecl = ON.getField();
1695 const RecordType *RT = CurrentType->getAs<RecordType>();
1696 if (!RT)
1697 return false;
1698 RecordDecl *RD = RT->getDecl();
1699 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00001700 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00001701 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001702 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00001703 CurrentType = MemberDecl->getType().getNonReferenceType();
1704 break;
1705 }
1706
1707 case OffsetOfExpr::OffsetOfNode::Identifier:
1708 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001709 return false;
1710
1711 case OffsetOfExpr::OffsetOfNode::Base: {
1712 CXXBaseSpecifier *BaseSpec = ON.getBase();
1713 if (BaseSpec->isVirtual())
1714 return false;
1715
1716 // Find the layout of the class whose base we are looking into.
1717 const RecordType *RT = CurrentType->getAs<RecordType>();
1718 if (!RT)
1719 return false;
1720 RecordDecl *RD = RT->getDecl();
1721 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1722
1723 // Find the base class itself.
1724 CurrentType = BaseSpec->getType();
1725 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1726 if (!BaseRT)
1727 return false;
1728
1729 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00001730 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00001731 break;
1732 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001733 }
1734 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001735 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00001736}
1737
Chris Lattnere13042c2008-07-11 19:10:17 +00001738bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001739 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001740 // LNot's operand isn't necessarily an integer, so we handle it specially.
1741 bool bres;
1742 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1743 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001744 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001745 }
1746
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001747 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00001748 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001749 return false;
1750
Chris Lattnercdf34e72008-07-11 22:52:41 +00001751 // Get the operand value into 'Result'.
1752 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001753 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001754
Chris Lattnerf09ad162008-07-11 22:15:16 +00001755 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001756 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001757 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1758 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001759 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001760 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001761 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1762 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001763 return true;
John McCalle3027922010-08-25 11:45:40 +00001764 case UO_Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001765 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001766 return true;
John McCalle3027922010-08-25 11:45:40 +00001767 case UO_Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001768 if (!Result.isInt()) return false;
1769 return Success(-Result.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00001770 case UO_Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001771 if (!Result.isInt()) return false;
1772 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001773 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001774}
Mike Stump11289f42009-09-09 15:08:12 +00001775
Chris Lattner477c4be2008-07-12 01:15:53 +00001776/// HandleCast - This is used to evaluate implicit or explicit casts where the
1777/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00001778bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1779 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001780 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001781 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001782
Eli Friedmanc757de22011-03-25 00:43:55 +00001783 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00001784 case CK_BaseToDerived:
1785 case CK_DerivedToBase:
1786 case CK_UncheckedDerivedToBase:
1787 case CK_Dynamic:
1788 case CK_ToUnion:
1789 case CK_ArrayToPointerDecay:
1790 case CK_FunctionToPointerDecay:
1791 case CK_NullToPointer:
1792 case CK_NullToMemberPointer:
1793 case CK_BaseToDerivedMemberPointer:
1794 case CK_DerivedToBaseMemberPointer:
1795 case CK_ConstructorConversion:
1796 case CK_IntegralToPointer:
1797 case CK_ToVoid:
1798 case CK_VectorSplat:
1799 case CK_IntegralToFloating:
1800 case CK_FloatingCast:
1801 case CK_AnyPointerToObjCPointerCast:
1802 case CK_AnyPointerToBlockPointerCast:
1803 case CK_ObjCObjectLValueCast:
1804 case CK_FloatingRealToComplex:
1805 case CK_FloatingComplexToReal:
1806 case CK_FloatingComplexCast:
1807 case CK_FloatingComplexToIntegralComplex:
1808 case CK_IntegralRealToComplex:
1809 case CK_IntegralComplexCast:
1810 case CK_IntegralComplexToFloatingComplex:
1811 llvm_unreachable("invalid cast kind for integral value");
1812
Eli Friedman9faf2f92011-03-25 19:07:11 +00001813 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001814 case CK_Dependent:
1815 case CK_GetObjCProperty:
1816 case CK_LValueBitCast:
1817 case CK_UserDefinedConversion:
John McCall31168b02011-06-15 23:02:42 +00001818 case CK_ObjCProduceObject:
1819 case CK_ObjCConsumeObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00001820 return false;
1821
1822 case CK_LValueToRValue:
1823 case CK_NoOp:
1824 return Visit(E->getSubExpr());
1825
1826 case CK_MemberPointerToBoolean:
1827 case CK_PointerToBoolean:
1828 case CK_IntegralToBoolean:
1829 case CK_FloatingToBoolean:
1830 case CK_FloatingComplexToBoolean:
1831 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00001832 bool BoolResult;
1833 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1834 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001835 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001836 }
1837
Eli Friedmanc757de22011-03-25 00:43:55 +00001838 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00001839 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001840 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001841
Eli Friedman742421e2009-02-20 01:15:07 +00001842 if (!Result.isInt()) {
1843 // Only allow casts of lvalues if they are lossless.
1844 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1845 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001846
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001847 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001848 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001849 }
Mike Stump11289f42009-09-09 15:08:12 +00001850
Eli Friedmanc757de22011-03-25 00:43:55 +00001851 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00001852 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001853 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001854 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001855
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001856 if (LV.getLValueBase()) {
1857 // Only allow based lvalue casts if they are lossless.
1858 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1859 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001860
John McCall45d55e42010-05-07 21:00:08 +00001861 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001862 return true;
1863 }
1864
Ken Dyck02990832010-01-15 12:37:54 +00001865 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1866 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001867 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001868 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001869
Eli Friedmanc757de22011-03-25 00:43:55 +00001870 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00001871 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001872 if (!EvaluateComplex(SubExpr, C, Info))
1873 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00001874 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001875 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001876
Eli Friedmanc757de22011-03-25 00:43:55 +00001877 case CK_FloatingToIntegral: {
1878 APFloat F(0.0);
1879 if (!EvaluateFloat(SubExpr, F, Info))
1880 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00001881
Eli Friedmanc757de22011-03-25 00:43:55 +00001882 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1883 }
1884 }
Mike Stump11289f42009-09-09 15:08:12 +00001885
Eli Friedmanc757de22011-03-25 00:43:55 +00001886 llvm_unreachable("unknown cast resulting in integral value");
1887 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001888}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001889
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001890bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1891 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001892 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001893 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1894 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1895 return Success(LV.getComplexIntReal(), E);
1896 }
1897
1898 return Visit(E->getSubExpr());
1899}
1900
Eli Friedman4e7a2412009-02-27 04:45:43 +00001901bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001902 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001903 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001904 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1905 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1906 return Success(LV.getComplexIntImag(), E);
1907 }
1908
Eli Friedman4e7a2412009-02-27 04:45:43 +00001909 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1910 Info.EvalResult.HasSideEffects = true;
1911 return Success(0, E);
1912}
1913
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001914bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1915 return Success(E->getPackLength(), E);
1916}
1917
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001918bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1919 return Success(E->getValue(), E);
1920}
1921
Chris Lattner05706e882008-07-11 18:11:29 +00001922//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00001923// Float Evaluation
1924//===----------------------------------------------------------------------===//
1925
1926namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001927class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001928 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00001929 APFloat &Result;
1930public:
1931 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001932 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00001933
Peter Collingbournee9200682011-05-13 03:29:01 +00001934 bool Success(const APValue &V, const Expr *e) {
1935 Result = V.getFloat();
1936 return true;
1937 }
1938 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00001939 return false;
1940 }
1941
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001942 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001943
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001944 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001945 bool VisitBinaryOperator(const BinaryOperator *E);
1946 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001947 bool VisitCastExpr(const CastExpr *E);
1948 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00001949
John McCallb1fb0d32010-05-07 22:08:54 +00001950 bool VisitUnaryReal(const UnaryOperator *E);
1951 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00001952
John McCalla2fabff2010-10-09 01:34:31 +00001953 bool VisitDeclRefExpr(const DeclRefExpr *E);
1954
John McCallb1fb0d32010-05-07 22:08:54 +00001955 // FIXME: Missing: array subscript of vector, member of vector,
1956 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00001957};
1958} // end anonymous namespace
1959
1960static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00001961 assert(E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001962 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00001963}
1964
Jay Foad39c79802011-01-12 09:06:06 +00001965static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00001966 QualType ResultTy,
1967 const Expr *Arg,
1968 bool SNaN,
1969 llvm::APFloat &Result) {
1970 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1971 if (!S) return false;
1972
1973 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1974
1975 llvm::APInt fill;
1976
1977 // Treat empty strings as if they were zero.
1978 if (S->getString().empty())
1979 fill = llvm::APInt(32, 0);
1980 else if (S->getString().getAsInteger(0, fill))
1981 return false;
1982
1983 if (SNaN)
1984 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1985 else
1986 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1987 return true;
1988}
1989
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001990bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001991 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001992 default:
1993 return ExprEvaluatorBaseTy::VisitCallExpr(E);
1994
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001995 case Builtin::BI__builtin_huge_val:
1996 case Builtin::BI__builtin_huge_valf:
1997 case Builtin::BI__builtin_huge_vall:
1998 case Builtin::BI__builtin_inf:
1999 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002000 case Builtin::BI__builtin_infl: {
2001 const llvm::fltSemantics &Sem =
2002 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002003 Result = llvm::APFloat::getInf(Sem);
2004 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002005 }
Mike Stump11289f42009-09-09 15:08:12 +00002006
John McCall16291492010-02-28 13:00:19 +00002007 case Builtin::BI__builtin_nans:
2008 case Builtin::BI__builtin_nansf:
2009 case Builtin::BI__builtin_nansl:
2010 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2011 true, Result);
2012
Chris Lattner0b7282e2008-10-06 06:31:58 +00002013 case Builtin::BI__builtin_nan:
2014 case Builtin::BI__builtin_nanf:
2015 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002016 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002017 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002018 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2019 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002020
2021 case Builtin::BI__builtin_fabs:
2022 case Builtin::BI__builtin_fabsf:
2023 case Builtin::BI__builtin_fabsl:
2024 if (!EvaluateFloat(E->getArg(0), Result, Info))
2025 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002026
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002027 if (Result.isNegative())
2028 Result.changeSign();
2029 return true;
2030
Mike Stump11289f42009-09-09 15:08:12 +00002031 case Builtin::BI__builtin_copysign:
2032 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002033 case Builtin::BI__builtin_copysignl: {
2034 APFloat RHS(0.);
2035 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2036 !EvaluateFloat(E->getArg(1), RHS, Info))
2037 return false;
2038 Result.copySign(RHS);
2039 return true;
2040 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002041 }
2042}
2043
John McCalla2fabff2010-10-09 01:34:31 +00002044bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002045 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2046 return true;
2047
John McCalla2fabff2010-10-09 01:34:31 +00002048 const Decl *D = E->getDecl();
2049 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2050 const VarDecl *VD = cast<VarDecl>(D);
2051
2052 // Require the qualifiers to be const and not volatile.
2053 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2054 if (!T.isConstQualified() || T.isVolatileQualified())
2055 return false;
2056
2057 const Expr *Init = VD->getAnyInitializer();
2058 if (!Init) return false;
2059
2060 if (APValue *V = VD->getEvaluatedValue()) {
2061 if (V->isFloat()) {
2062 Result = V->getFloat();
2063 return true;
2064 }
2065 return false;
2066 }
2067
2068 if (VD->isEvaluatingValue())
2069 return false;
2070
2071 VD->setEvaluatingValue();
2072
2073 Expr::EvalResult InitResult;
2074 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2075 InitResult.Val.isFloat()) {
2076 // Cache the evaluated value in the variable declaration.
2077 Result = InitResult.Val.getFloat();
2078 VD->setEvaluatedValue(InitResult.Val);
2079 return true;
2080 }
2081
2082 VD->setEvaluatedValue(APValue());
2083 return false;
2084}
2085
John McCallb1fb0d32010-05-07 22:08:54 +00002086bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002087 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2088 ComplexValue CV;
2089 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2090 return false;
2091 Result = CV.FloatReal;
2092 return true;
2093 }
2094
2095 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002096}
2097
2098bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002099 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2100 ComplexValue CV;
2101 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2102 return false;
2103 Result = CV.FloatImag;
2104 return true;
2105 }
2106
2107 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2108 Info.EvalResult.HasSideEffects = true;
2109 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2110 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002111 return true;
2112}
2113
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002114bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002115 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002116 return false;
2117
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002118 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2119 return false;
2120
2121 switch (E->getOpcode()) {
2122 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002123 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002124 return true;
John McCalle3027922010-08-25 11:45:40 +00002125 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002126 Result.changeSign();
2127 return true;
2128 }
2129}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002130
Eli Friedman24c01542008-08-22 00:06:13 +00002131bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002132 if (E->getOpcode() == BO_Comma) {
Eli Friedman141fbf32009-11-16 04:25:37 +00002133 if (!EvaluateFloat(E->getRHS(), Result, Info))
2134 return false;
2135
2136 // If we can't evaluate the LHS, it might have side effects;
2137 // conservatively mark it.
2138 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2139 Info.EvalResult.HasSideEffects = true;
2140
2141 return true;
2142 }
2143
Anders Carlssona5df61a2010-10-31 01:21:47 +00002144 // We can't evaluate pointer-to-member operations.
2145 if (E->isPtrMemOp())
2146 return false;
2147
Eli Friedman24c01542008-08-22 00:06:13 +00002148 // FIXME: Diagnostics? I really don't understand how the warnings
2149 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002150 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002151 if (!EvaluateFloat(E->getLHS(), Result, Info))
2152 return false;
2153 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2154 return false;
2155
2156 switch (E->getOpcode()) {
2157 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002158 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002159 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2160 return true;
John McCalle3027922010-08-25 11:45:40 +00002161 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002162 Result.add(RHS, APFloat::rmNearestTiesToEven);
2163 return true;
John McCalle3027922010-08-25 11:45:40 +00002164 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002165 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2166 return true;
John McCalle3027922010-08-25 11:45:40 +00002167 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002168 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2169 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002170 }
2171}
2172
2173bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2174 Result = E->getValue();
2175 return true;
2176}
2177
Peter Collingbournee9200682011-05-13 03:29:01 +00002178bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2179 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002180
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002181 switch (E->getCastKind()) {
2182 default:
2183 return false;
2184
2185 case CK_LValueToRValue:
2186 case CK_NoOp:
2187 return Visit(SubExpr);
2188
2189 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002190 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002191 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002192 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002193 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002194 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002195 return true;
2196 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002197
2198 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002199 if (!Visit(SubExpr))
2200 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002201 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2202 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002203 return true;
2204 }
John McCalld7646252010-11-14 08:17:51 +00002205
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002206 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002207 ComplexValue V;
2208 if (!EvaluateComplex(SubExpr, V, Info))
2209 return false;
2210 Result = V.getComplexFloatReal();
2211 return true;
2212 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002213 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002214
2215 return false;
2216}
2217
Peter Collingbournee9200682011-05-13 03:29:01 +00002218bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +00002219 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2220 return true;
2221}
2222
Eli Friedman24c01542008-08-22 00:06:13 +00002223//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002224// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002225//===----------------------------------------------------------------------===//
2226
2227namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002228class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002229 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002230 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002231
Anders Carlsson537969c2008-11-16 20:27:53 +00002232public:
John McCall93d91dc2010-05-07 17:22:02 +00002233 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002234 : ExprEvaluatorBaseTy(info), Result(Result) {}
2235
2236 bool Success(const APValue &V, const Expr *e) {
2237 Result.setFrom(V);
2238 return true;
2239 }
2240 bool Error(const Expr *E) {
2241 return false;
2242 }
Mike Stump11289f42009-09-09 15:08:12 +00002243
Anders Carlsson537969c2008-11-16 20:27:53 +00002244 //===--------------------------------------------------------------------===//
2245 // Visitor Methods
2246 //===--------------------------------------------------------------------===//
2247
Peter Collingbournee9200682011-05-13 03:29:01 +00002248 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002249
Peter Collingbournee9200682011-05-13 03:29:01 +00002250 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002251
John McCall93d91dc2010-05-07 17:22:02 +00002252 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002253 bool VisitUnaryOperator(const UnaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002254 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002255};
2256} // end anonymous namespace
2257
John McCall93d91dc2010-05-07 17:22:02 +00002258static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2259 EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002260 assert(E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002261 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002262}
2263
Peter Collingbournee9200682011-05-13 03:29:01 +00002264bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2265 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002266
2267 if (SubExpr->getType()->isRealFloatingType()) {
2268 Result.makeComplexFloat();
2269 APFloat &Imag = Result.FloatImag;
2270 if (!EvaluateFloat(SubExpr, Imag, Info))
2271 return false;
2272
2273 Result.FloatReal = APFloat(Imag.getSemantics());
2274 return true;
2275 } else {
2276 assert(SubExpr->getType()->isIntegerType() &&
2277 "Unexpected imaginary literal.");
2278
2279 Result.makeComplexInt();
2280 APSInt &Imag = Result.IntImag;
2281 if (!EvaluateInteger(SubExpr, Imag, Info))
2282 return false;
2283
2284 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2285 return true;
2286 }
2287}
2288
Peter Collingbournee9200682011-05-13 03:29:01 +00002289bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002290
John McCallfcef3cf2010-12-14 17:51:41 +00002291 switch (E->getCastKind()) {
2292 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002293 case CK_BaseToDerived:
2294 case CK_DerivedToBase:
2295 case CK_UncheckedDerivedToBase:
2296 case CK_Dynamic:
2297 case CK_ToUnion:
2298 case CK_ArrayToPointerDecay:
2299 case CK_FunctionToPointerDecay:
2300 case CK_NullToPointer:
2301 case CK_NullToMemberPointer:
2302 case CK_BaseToDerivedMemberPointer:
2303 case CK_DerivedToBaseMemberPointer:
2304 case CK_MemberPointerToBoolean:
2305 case CK_ConstructorConversion:
2306 case CK_IntegralToPointer:
2307 case CK_PointerToIntegral:
2308 case CK_PointerToBoolean:
2309 case CK_ToVoid:
2310 case CK_VectorSplat:
2311 case CK_IntegralCast:
2312 case CK_IntegralToBoolean:
2313 case CK_IntegralToFloating:
2314 case CK_FloatingToIntegral:
2315 case CK_FloatingToBoolean:
2316 case CK_FloatingCast:
2317 case CK_AnyPointerToObjCPointerCast:
2318 case CK_AnyPointerToBlockPointerCast:
2319 case CK_ObjCObjectLValueCast:
2320 case CK_FloatingComplexToReal:
2321 case CK_FloatingComplexToBoolean:
2322 case CK_IntegralComplexToReal:
2323 case CK_IntegralComplexToBoolean:
John McCall31168b02011-06-15 23:02:42 +00002324 case CK_ObjCProduceObject:
2325 case CK_ObjCConsumeObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002326 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002327
John McCallfcef3cf2010-12-14 17:51:41 +00002328 case CK_LValueToRValue:
2329 case CK_NoOp:
2330 return Visit(E->getSubExpr());
2331
2332 case CK_Dependent:
2333 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002334 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002335 case CK_UserDefinedConversion:
2336 return false;
2337
2338 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002339 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002340 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002341 return false;
2342
John McCallfcef3cf2010-12-14 17:51:41 +00002343 Result.makeComplexFloat();
2344 Result.FloatImag = APFloat(Real.getSemantics());
2345 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002346 }
2347
John McCallfcef3cf2010-12-14 17:51:41 +00002348 case CK_FloatingComplexCast: {
2349 if (!Visit(E->getSubExpr()))
2350 return false;
2351
2352 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2353 QualType From
2354 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2355
2356 Result.FloatReal
2357 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2358 Result.FloatImag
2359 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2360 return true;
2361 }
2362
2363 case CK_FloatingComplexToIntegralComplex: {
2364 if (!Visit(E->getSubExpr()))
2365 return false;
2366
2367 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2368 QualType From
2369 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2370 Result.makeComplexInt();
2371 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2372 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2373 return true;
2374 }
2375
2376 case CK_IntegralRealToComplex: {
2377 APSInt &Real = Result.IntReal;
2378 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2379 return false;
2380
2381 Result.makeComplexInt();
2382 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2383 return true;
2384 }
2385
2386 case CK_IntegralComplexCast: {
2387 if (!Visit(E->getSubExpr()))
2388 return false;
2389
2390 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2391 QualType From
2392 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2393
2394 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2395 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2396 return true;
2397 }
2398
2399 case CK_IntegralComplexToFloatingComplex: {
2400 if (!Visit(E->getSubExpr()))
2401 return false;
2402
2403 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2404 QualType From
2405 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2406 Result.makeComplexFloat();
2407 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2408 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2409 return true;
2410 }
2411 }
2412
2413 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002414 return false;
2415}
2416
John McCall93d91dc2010-05-07 17:22:02 +00002417bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002418 if (E->getOpcode() == BO_Comma) {
2419 if (!Visit(E->getRHS()))
2420 return false;
2421
2422 // If we can't evaluate the LHS, it might have side effects;
2423 // conservatively mark it.
2424 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2425 Info.EvalResult.HasSideEffects = true;
2426
2427 return true;
2428 }
John McCall93d91dc2010-05-07 17:22:02 +00002429 if (!Visit(E->getLHS()))
2430 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002431
John McCall93d91dc2010-05-07 17:22:02 +00002432 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002433 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002434 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002435
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002436 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2437 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002438 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002439 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002440 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002441 if (Result.isComplexFloat()) {
2442 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2443 APFloat::rmNearestTiesToEven);
2444 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2445 APFloat::rmNearestTiesToEven);
2446 } else {
2447 Result.getComplexIntReal() += RHS.getComplexIntReal();
2448 Result.getComplexIntImag() += RHS.getComplexIntImag();
2449 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002450 break;
John McCalle3027922010-08-25 11:45:40 +00002451 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002452 if (Result.isComplexFloat()) {
2453 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2454 APFloat::rmNearestTiesToEven);
2455 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2456 APFloat::rmNearestTiesToEven);
2457 } else {
2458 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2459 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2460 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002461 break;
John McCalle3027922010-08-25 11:45:40 +00002462 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002463 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002464 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002465 APFloat &LHS_r = LHS.getComplexFloatReal();
2466 APFloat &LHS_i = LHS.getComplexFloatImag();
2467 APFloat &RHS_r = RHS.getComplexFloatReal();
2468 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002469
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002470 APFloat Tmp = LHS_r;
2471 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2472 Result.getComplexFloatReal() = Tmp;
2473 Tmp = LHS_i;
2474 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2475 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2476
2477 Tmp = LHS_r;
2478 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2479 Result.getComplexFloatImag() = Tmp;
2480 Tmp = LHS_i;
2481 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2482 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2483 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002484 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002485 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002486 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2487 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002488 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002489 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2490 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2491 }
2492 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002493 case BO_Div:
2494 if (Result.isComplexFloat()) {
2495 ComplexValue LHS = Result;
2496 APFloat &LHS_r = LHS.getComplexFloatReal();
2497 APFloat &LHS_i = LHS.getComplexFloatImag();
2498 APFloat &RHS_r = RHS.getComplexFloatReal();
2499 APFloat &RHS_i = RHS.getComplexFloatImag();
2500 APFloat &Res_r = Result.getComplexFloatReal();
2501 APFloat &Res_i = Result.getComplexFloatImag();
2502
2503 APFloat Den = RHS_r;
2504 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2505 APFloat Tmp = RHS_i;
2506 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2507 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2508
2509 Res_r = LHS_r;
2510 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2511 Tmp = LHS_i;
2512 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2513 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2514 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2515
2516 Res_i = LHS_i;
2517 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2518 Tmp = LHS_r;
2519 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2520 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2521 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2522 } else {
2523 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2524 // FIXME: what about diagnostics?
2525 return false;
2526 }
2527 ComplexValue LHS = Result;
2528 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2529 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2530 Result.getComplexIntReal() =
2531 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2532 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2533 Result.getComplexIntImag() =
2534 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2535 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2536 }
2537 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002538 }
2539
John McCall93d91dc2010-05-07 17:22:02 +00002540 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002541}
2542
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002543bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2544 // Get the operand value into 'Result'.
2545 if (!Visit(E->getSubExpr()))
2546 return false;
2547
2548 switch (E->getOpcode()) {
2549 default:
2550 // FIXME: what about diagnostics?
2551 return false;
2552 case UO_Extension:
2553 return true;
2554 case UO_Plus:
2555 // The result is always just the subexpr.
2556 return true;
2557 case UO_Minus:
2558 if (Result.isComplexFloat()) {
2559 Result.getComplexFloatReal().changeSign();
2560 Result.getComplexFloatImag().changeSign();
2561 }
2562 else {
2563 Result.getComplexIntReal() = -Result.getComplexIntReal();
2564 Result.getComplexIntImag() = -Result.getComplexIntImag();
2565 }
2566 return true;
2567 case UO_Not:
2568 if (Result.isComplexFloat())
2569 Result.getComplexFloatImag().changeSign();
2570 else
2571 Result.getComplexIntImag() = -Result.getComplexIntImag();
2572 return true;
2573 }
2574}
2575
Anders Carlsson537969c2008-11-16 20:27:53 +00002576//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002577// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002578//===----------------------------------------------------------------------===//
2579
John McCallc07a0c72011-02-17 10:25:35 +00002580static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00002581 if (E->getType()->isVectorType()) {
2582 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002583 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002584 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002585 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002586 return false;
John McCallc07a0c72011-02-17 10:25:35 +00002587 if (Info.EvalResult.Val.isLValue() &&
2588 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall11086fc2010-07-07 05:08:32 +00002589 return false;
John McCall45d55e42010-05-07 21:00:08 +00002590 } else if (E->getType()->hasPointerRepresentation()) {
2591 LValue LV;
2592 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002593 return false;
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002594 if (!IsGlobalLValue(LV.Base))
John McCall95007602010-05-10 23:27:23 +00002595 return false;
John McCall45d55e42010-05-07 21:00:08 +00002596 LV.moveInto(Info.EvalResult.Val);
2597 } else if (E->getType()->isRealFloatingType()) {
2598 llvm::APFloat F(0.0);
2599 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002600 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002601
John McCall45d55e42010-05-07 21:00:08 +00002602 Info.EvalResult.Val = APValue(F);
2603 } else if (E->getType()->isAnyComplexType()) {
2604 ComplexValue C;
2605 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002606 return false;
John McCall45d55e42010-05-07 21:00:08 +00002607 C.moveInto(Info.EvalResult.Val);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002608 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002609 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002610
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002611 return true;
2612}
2613
John McCallc07a0c72011-02-17 10:25:35 +00002614/// Evaluate - Return true if this is a constant which we can fold using
2615/// any crazy technique (that has nothing to do with language standards) that
2616/// we want to. If this function returns true, it returns the folded constant
2617/// in Result.
2618bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2619 EvalInfo Info(Ctx, Result);
2620 return ::Evaluate(Info, this);
2621}
2622
Jay Foad39c79802011-01-12 09:06:06 +00002623bool Expr::EvaluateAsBooleanCondition(bool &Result,
2624 const ASTContext &Ctx) const {
John McCall1be1c632010-01-05 23:42:56 +00002625 EvalResult Scratch;
2626 EvalInfo Info(Ctx, Scratch);
2627
2628 return HandleConversionToBool(this, Result, Info);
2629}
2630
Jay Foad39c79802011-01-12 09:06:06 +00002631bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002632 EvalInfo Info(Ctx, Result);
2633
John McCall45d55e42010-05-07 21:00:08 +00002634 LValue LV;
John McCall95007602010-05-10 23:27:23 +00002635 if (EvaluateLValue(this, LV, Info) &&
2636 !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002637 IsGlobalLValue(LV.Base)) {
2638 LV.moveInto(Result.Val);
2639 return true;
2640 }
2641 return false;
2642}
2643
Jay Foad39c79802011-01-12 09:06:06 +00002644bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2645 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002646 EvalInfo Info(Ctx, Result);
2647
2648 LValue LV;
2649 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00002650 LV.moveInto(Result.Val);
2651 return true;
2652 }
2653 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00002654}
2655
Chris Lattner67d7b922008-11-16 21:24:15 +00002656/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002657/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00002658bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002659 EvalResult Result;
2660 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002661}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002662
Jay Foad39c79802011-01-12 09:06:06 +00002663bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002664 Expr::EvalResult Result;
2665 EvalInfo Info(Ctx, Result);
Peter Collingbournee9200682011-05-13 03:29:01 +00002666 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002667}
2668
Jay Foad39c79802011-01-12 09:06:06 +00002669APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002670 EvalResult EvalResult;
2671 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002672 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002673 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002674 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002675
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002676 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002677}
John McCall864e3962010-05-07 05:32:02 +00002678
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002679 bool Expr::EvalResult::isGlobalLValue() const {
2680 assert(Val.isLValue());
2681 return IsGlobalLValue(Val.getLValueBase());
2682 }
2683
2684
John McCall864e3962010-05-07 05:32:02 +00002685/// isIntegerConstantExpr - this recursive routine will test if an expression is
2686/// an integer constant expression.
2687
2688/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2689/// comma, etc
2690///
2691/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2692/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2693/// cast+dereference.
2694
2695// CheckICE - This function does the fundamental ICE checking: the returned
2696// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2697// Note that to reduce code duplication, this helper does no evaluation
2698// itself; the caller checks whether the expression is evaluatable, and
2699// in the rare cases where CheckICE actually cares about the evaluated
2700// value, it calls into Evalute.
2701//
2702// Meanings of Val:
2703// 0: This expression is an ICE if it can be evaluated by Evaluate.
2704// 1: This expression is not an ICE, but if it isn't evaluated, it's
2705// a legal subexpression for an ICE. This return value is used to handle
2706// the comma operator in C99 mode.
2707// 2: This expression is not an ICE, and is not a legal subexpression for one.
2708
Dan Gohman28ade552010-07-26 21:25:24 +00002709namespace {
2710
John McCall864e3962010-05-07 05:32:02 +00002711struct ICEDiag {
2712 unsigned Val;
2713 SourceLocation Loc;
2714
2715 public:
2716 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2717 ICEDiag() : Val(0) {}
2718};
2719
Dan Gohman28ade552010-07-26 21:25:24 +00002720}
2721
2722static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00002723
2724static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2725 Expr::EvalResult EVResult;
2726 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2727 !EVResult.Val.isInt()) {
2728 return ICEDiag(2, E->getLocStart());
2729 }
2730 return NoDiag();
2731}
2732
2733static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2734 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00002735 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00002736 return ICEDiag(2, E->getLocStart());
2737 }
2738
2739 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00002740#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00002741#define STMT(Node, Base) case Expr::Node##Class:
2742#define EXPR(Node, Base)
2743#include "clang/AST/StmtNodes.inc"
2744 case Expr::PredefinedExprClass:
2745 case Expr::FloatingLiteralClass:
2746 case Expr::ImaginaryLiteralClass:
2747 case Expr::StringLiteralClass:
2748 case Expr::ArraySubscriptExprClass:
2749 case Expr::MemberExprClass:
2750 case Expr::CompoundAssignOperatorClass:
2751 case Expr::CompoundLiteralExprClass:
2752 case Expr::ExtVectorElementExprClass:
2753 case Expr::InitListExprClass:
2754 case Expr::DesignatedInitExprClass:
2755 case Expr::ImplicitValueInitExprClass:
2756 case Expr::ParenListExprClass:
2757 case Expr::VAArgExprClass:
2758 case Expr::AddrLabelExprClass:
2759 case Expr::StmtExprClass:
2760 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00002761 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00002762 case Expr::CXXDynamicCastExprClass:
2763 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00002764 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00002765 case Expr::CXXNullPtrLiteralExprClass:
2766 case Expr::CXXThisExprClass:
2767 case Expr::CXXThrowExprClass:
2768 case Expr::CXXNewExprClass:
2769 case Expr::CXXDeleteExprClass:
2770 case Expr::CXXPseudoDestructorExprClass:
2771 case Expr::UnresolvedLookupExprClass:
2772 case Expr::DependentScopeDeclRefExprClass:
2773 case Expr::CXXConstructExprClass:
2774 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00002775 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00002776 case Expr::CXXTemporaryObjectExprClass:
2777 case Expr::CXXUnresolvedConstructExprClass:
2778 case Expr::CXXDependentScopeMemberExprClass:
2779 case Expr::UnresolvedMemberExprClass:
2780 case Expr::ObjCStringLiteralClass:
2781 case Expr::ObjCEncodeExprClass:
2782 case Expr::ObjCMessageExprClass:
2783 case Expr::ObjCSelectorExprClass:
2784 case Expr::ObjCProtocolExprClass:
2785 case Expr::ObjCIvarRefExprClass:
2786 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00002787 case Expr::ObjCIsaExprClass:
2788 case Expr::ShuffleVectorExprClass:
2789 case Expr::BlockExprClass:
2790 case Expr::BlockDeclRefExprClass:
2791 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00002792 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00002793 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00002794 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00002795 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00002796 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00002797 case Expr::MaterializeTemporaryExprClass:
John McCall864e3962010-05-07 05:32:02 +00002798 return ICEDiag(2, E->getLocStart());
2799
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002800 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00002801 case Expr::GNUNullExprClass:
2802 // GCC considers the GNU __null value to be an integral constant expression.
2803 return NoDiag();
2804
2805 case Expr::ParenExprClass:
2806 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002807 case Expr::GenericSelectionExprClass:
2808 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002809 case Expr::IntegerLiteralClass:
2810 case Expr::CharacterLiteralClass:
2811 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00002812 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00002813 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002814 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00002815 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00002816 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00002817 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00002818 return NoDiag();
2819 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00002820 case Expr::CXXOperatorCallExprClass: {
John McCall864e3962010-05-07 05:32:02 +00002821 const CallExpr *CE = cast<CallExpr>(E);
2822 if (CE->isBuiltinCall(Ctx))
2823 return CheckEvalInICE(E, Ctx);
2824 return ICEDiag(2, E->getLocStart());
2825 }
2826 case Expr::DeclRefExprClass:
2827 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2828 return NoDiag();
2829 if (Ctx.getLangOptions().CPlusPlus &&
2830 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2831 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2832
2833 // Parameter variables are never constants. Without this check,
2834 // getAnyInitializer() can find a default argument, which leads
2835 // to chaos.
2836 if (isa<ParmVarDecl>(D))
2837 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2838
2839 // C++ 7.1.5.1p2
2840 // A variable of non-volatile const-qualified integral or enumeration
2841 // type initialized by an ICE can be used in ICEs.
2842 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2843 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2844 if (Quals.hasVolatile() || !Quals.hasConst())
2845 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2846
2847 // Look for a declaration of this variable that has an initializer.
2848 const VarDecl *ID = 0;
2849 const Expr *Init = Dcl->getAnyInitializer(ID);
2850 if (Init) {
2851 if (ID->isInitKnownICE()) {
2852 // We have already checked whether this subexpression is an
2853 // integral constant expression.
2854 if (ID->isInitICE())
2855 return NoDiag();
2856 else
2857 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2858 }
2859
2860 // It's an ICE whether or not the definition we found is
2861 // out-of-line. See DR 721 and the discussion in Clang PR
2862 // 6206 for details.
2863
2864 if (Dcl->isCheckingICE()) {
2865 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2866 }
2867
2868 Dcl->setCheckingICE();
2869 ICEDiag Result = CheckICE(Init, Ctx);
2870 // Cache the result of the ICE test.
2871 Dcl->setInitKnownICE(Result.Val == 0);
2872 return Result;
2873 }
2874 }
2875 }
2876 return ICEDiag(2, E->getLocStart());
2877 case Expr::UnaryOperatorClass: {
2878 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2879 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002880 case UO_PostInc:
2881 case UO_PostDec:
2882 case UO_PreInc:
2883 case UO_PreDec:
2884 case UO_AddrOf:
2885 case UO_Deref:
John McCall864e3962010-05-07 05:32:02 +00002886 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00002887 case UO_Extension:
2888 case UO_LNot:
2889 case UO_Plus:
2890 case UO_Minus:
2891 case UO_Not:
2892 case UO_Real:
2893 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00002894 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002895 }
2896
2897 // OffsetOf falls through here.
2898 }
2899 case Expr::OffsetOfExprClass: {
2900 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2901 // Evaluate matches the proposed gcc behavior for cases like
2902 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2903 // compliance: we should warn earlier for offsetof expressions with
2904 // array subscripts that aren't ICEs, and if the array subscripts
2905 // are ICEs, the value of the offsetof must be an integer constant.
2906 return CheckEvalInICE(E, Ctx);
2907 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002908 case Expr::UnaryExprOrTypeTraitExprClass: {
2909 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2910 if ((Exp->getKind() == UETT_SizeOf) &&
2911 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00002912 return ICEDiag(2, E->getLocStart());
2913 return NoDiag();
2914 }
2915 case Expr::BinaryOperatorClass: {
2916 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2917 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002918 case BO_PtrMemD:
2919 case BO_PtrMemI:
2920 case BO_Assign:
2921 case BO_MulAssign:
2922 case BO_DivAssign:
2923 case BO_RemAssign:
2924 case BO_AddAssign:
2925 case BO_SubAssign:
2926 case BO_ShlAssign:
2927 case BO_ShrAssign:
2928 case BO_AndAssign:
2929 case BO_XorAssign:
2930 case BO_OrAssign:
John McCall864e3962010-05-07 05:32:02 +00002931 return ICEDiag(2, E->getLocStart());
2932
John McCalle3027922010-08-25 11:45:40 +00002933 case BO_Mul:
2934 case BO_Div:
2935 case BO_Rem:
2936 case BO_Add:
2937 case BO_Sub:
2938 case BO_Shl:
2939 case BO_Shr:
2940 case BO_LT:
2941 case BO_GT:
2942 case BO_LE:
2943 case BO_GE:
2944 case BO_EQ:
2945 case BO_NE:
2946 case BO_And:
2947 case BO_Xor:
2948 case BO_Or:
2949 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00002950 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2951 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00002952 if (Exp->getOpcode() == BO_Div ||
2953 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00002954 // Evaluate gives an error for undefined Div/Rem, so make sure
2955 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00002956 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCall864e3962010-05-07 05:32:02 +00002957 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2958 if (REval == 0)
2959 return ICEDiag(1, E->getLocStart());
2960 if (REval.isSigned() && REval.isAllOnesValue()) {
2961 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2962 if (LEval.isMinSignedValue())
2963 return ICEDiag(1, E->getLocStart());
2964 }
2965 }
2966 }
John McCalle3027922010-08-25 11:45:40 +00002967 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00002968 if (Ctx.getLangOptions().C99) {
2969 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2970 // if it isn't evaluated.
2971 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2972 return ICEDiag(1, E->getLocStart());
2973 } else {
2974 // In both C89 and C++, commas in ICEs are illegal.
2975 return ICEDiag(2, E->getLocStart());
2976 }
2977 }
2978 if (LHSResult.Val >= RHSResult.Val)
2979 return LHSResult;
2980 return RHSResult;
2981 }
John McCalle3027922010-08-25 11:45:40 +00002982 case BO_LAnd:
2983 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00002984 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00002985
2986 // C++0x [expr.const]p2:
2987 // [...] subexpressions of logical AND (5.14), logical OR
2988 // (5.15), and condi- tional (5.16) operations that are not
2989 // evaluated are not considered.
2990 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
2991 if (Exp->getOpcode() == BO_LAnd &&
2992 Exp->getLHS()->EvaluateAsInt(Ctx) == 0)
2993 return LHSResult;
2994
2995 if (Exp->getOpcode() == BO_LOr &&
2996 Exp->getLHS()->EvaluateAsInt(Ctx) != 0)
2997 return LHSResult;
2998 }
2999
John McCall864e3962010-05-07 05:32:02 +00003000 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3001 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3002 // Rare case where the RHS has a comma "side-effect"; we need
3003 // to actually check the condition to see whether the side
3004 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003005 if ((Exp->getOpcode() == BO_LAnd) !=
John McCall864e3962010-05-07 05:32:02 +00003006 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3007 return RHSResult;
3008 return NoDiag();
3009 }
3010
3011 if (LHSResult.Val >= RHSResult.Val)
3012 return LHSResult;
3013 return RHSResult;
3014 }
3015 }
3016 }
3017 case Expr::ImplicitCastExprClass:
3018 case Expr::CStyleCastExprClass:
3019 case Expr::CXXFunctionalCastExprClass:
3020 case Expr::CXXStaticCastExprClass:
3021 case Expr::CXXReinterpretCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003022 case Expr::CXXConstCastExprClass:
3023 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003024 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregorb90df602010-06-16 00:17:44 +00003025 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCall864e3962010-05-07 05:32:02 +00003026 return CheckICE(SubExpr, Ctx);
3027 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3028 return NoDiag();
3029 return ICEDiag(2, E->getLocStart());
3030 }
John McCallc07a0c72011-02-17 10:25:35 +00003031 case Expr::BinaryConditionalOperatorClass: {
3032 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3033 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3034 if (CommonResult.Val == 2) return CommonResult;
3035 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3036 if (FalseResult.Val == 2) return FalseResult;
3037 if (CommonResult.Val == 1) return CommonResult;
3038 if (FalseResult.Val == 1 &&
3039 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3040 return FalseResult;
3041 }
John McCall864e3962010-05-07 05:32:02 +00003042 case Expr::ConditionalOperatorClass: {
3043 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3044 // If the condition (ignoring parens) is a __builtin_constant_p call,
3045 // then only the true side is actually considered in an integer constant
3046 // expression, and it is fully evaluated. This is an important GNU
3047 // extension. See GCC PR38377 for discussion.
3048 if (const CallExpr *CallCE
3049 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3050 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3051 Expr::EvalResult EVResult;
3052 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3053 !EVResult.Val.isInt()) {
3054 return ICEDiag(2, E->getLocStart());
3055 }
3056 return NoDiag();
3057 }
3058 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003059 if (CondResult.Val == 2)
3060 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003061
3062 // C++0x [expr.const]p2:
3063 // subexpressions of [...] conditional (5.16) operations that
3064 // are not evaluated are not considered
3065 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
3066 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0
3067 : false;
3068 ICEDiag TrueResult = NoDiag();
3069 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3070 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3071 ICEDiag FalseResult = NoDiag();
3072 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3073 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3074
John McCall864e3962010-05-07 05:32:02 +00003075 if (TrueResult.Val == 2)
3076 return TrueResult;
3077 if (FalseResult.Val == 2)
3078 return FalseResult;
3079 if (CondResult.Val == 1)
3080 return CondResult;
3081 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3082 return NoDiag();
3083 // Rare case where the diagnostics depend on which side is evaluated
3084 // Note that if we get here, CondResult is 0, and at least one of
3085 // TrueResult and FalseResult is non-zero.
3086 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3087 return FalseResult;
3088 }
3089 return TrueResult;
3090 }
3091 case Expr::CXXDefaultArgExprClass:
3092 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3093 case Expr::ChooseExprClass: {
3094 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3095 }
3096 }
3097
3098 // Silence a GCC warning
3099 return ICEDiag(2, E->getLocStart());
3100}
3101
3102bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3103 SourceLocation *Loc, bool isEvaluated) const {
3104 ICEDiag d = CheckICE(this, Ctx);
3105 if (d.Val != 0) {
3106 if (Loc) *Loc = d.Loc;
3107 return false;
3108 }
3109 EvalResult EvalResult;
3110 if (!Evaluate(EvalResult, Ctx))
3111 llvm_unreachable("ICE cannot be evaluated!");
3112 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3113 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3114 Result = EvalResult.Val.getInt();
3115 return true;
3116}