blob: 0ec122dc353a141fd38e1f99579d36a69de611c3 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Benjamin Kramerc54061a2011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
49 /// EvalResult - Contains information about the evaluation.
50 Expr::EvalResult &EvalResult;
51
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
61 : Ctx(ctx), EvalResult(evalresult) {}
62 };
63
John McCallf4cf1a12010-05-07 17:22:02 +000064 struct ComplexValue {
65 private:
66 bool IsInt;
67
68 public:
69 APSInt IntReal, IntImag;
70 APFloat FloatReal, FloatImag;
71
72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
73
74 void makeComplexFloat() { IsInt = false; }
75 bool isComplexFloat() const { return !IsInt; }
76 APFloat &getComplexFloatReal() { return FloatReal; }
77 APFloat &getComplexFloatImag() { return FloatImag; }
78
79 void makeComplexInt() { IsInt = true; }
80 bool isComplexInt() const { return IsInt; }
81 APSInt &getComplexIntReal() { return IntReal; }
82 APSInt &getComplexIntImag() { return IntImag; }
83
John McCall56ca35d2011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCall56ca35d2011-02-17 10:25:35 +000090 void setFrom(const APValue &v) {
91 assert(v.isComplexFloat() || v.isComplexInt());
92 if (v.isComplexFloat()) {
93 makeComplexFloat();
94 FloatReal = v.getComplexFloatReal();
95 FloatImag = v.getComplexFloatImag();
96 } else {
97 makeComplexInt();
98 IntReal = v.getComplexIntReal();
99 IntImag = v.getComplexIntImag();
100 }
101 }
John McCallf4cf1a12010-05-07 17:22:02 +0000102 };
John McCallefdb83e2010-05-07 21:00:08 +0000103
104 struct LValue {
105 Expr *Base;
106 CharUnits Offset;
107
108 Expr *getLValueBase() { return Base; }
109 CharUnits getLValueOffset() { return Offset; }
110
John McCall56ca35d2011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCallefdb83e2010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCall56ca35d2011-02-17 10:25:35 +0000114 void setFrom(const APValue &v) {
115 assert(v.isLValue());
116 Base = v.getLValueBase();
117 Offset = v.getLValueOffset();
118 }
John McCallefdb83e2010-05-07 21:00:08 +0000119 };
John McCallf4cf1a12010-05-07 17:22:02 +0000120}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000121
John McCall56ca35d2011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000136 if (!E) return true;
137
138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
139 if (isa<FunctionDecl>(DRE->getDecl()))
140 return true;
141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
142 return VD->hasGlobalStorage();
143 return false;
144 }
145
146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
147 return CLE->isFileScope();
148
149 return true;
150}
151
John McCallefdb83e2010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000154
John McCall35542832010-05-07 21:34:32 +0000155 // A null base expression indicates a null pointer. These are always
156 // evaluatable, and they are false unless the offset is zero.
157 if (!Base) {
158 Result = !Value.Offset.isZero();
159 return true;
160 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000161
John McCall42c8f872010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000164
John McCall35542832010-05-07 21:34:32 +0000165 // We have a non-null base expression. These are generally known to
166 // be true, but if it'a decl-ref to a weak symbol it can be null at
167 // runtime.
John McCall35542832010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCall35542832010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman5bc86102009-06-14 02:17:33 +0000181 return true;
182}
183
John McCallcd7a4452010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000187 APSInt IntResult;
188 if (!EvaluateInteger(E, IntResult, Info))
189 return false;
190 Result = IntResult != 0;
191 return true;
192 } else if (E->getType()->isRealFloatingType()) {
193 APFloat FloatResult(0.0);
194 if (!EvaluateFloat(E, FloatResult, Info))
195 return false;
196 Result = !FloatResult.isZero();
197 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000205 if (!EvaluateComplex(E, ComplexResult, Info))
206 return false;
207 if (ComplexResult.isComplexFloat()) {
208 Result = !ComplexResult.getComplexFloatReal().isZero() ||
209 !ComplexResult.getComplexFloatImag().isZero();
210 } else {
211 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
212 ComplexResult.getComplexIntImag().getBoolValue();
213 }
214 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump1eb44332009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
224 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Daniel Dunbara2cfd342009-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 Stump1eb44332009-09-09 15:08:12 +0000234static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000235 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000236 bool ignored;
237 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000238 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000239 APFloat::rmNearestTiesToEven, &ignored);
240 return Result;
241}
242
Mike Stump1eb44332009-09-09 15:08:12 +0000243static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000244 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-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 Foad9f71a8f2010-12-07 08:25:34 +0000249 Result = Result.extOrTrunc(DestWidth);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000250 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
251 return Result;
252}
253
Mike Stump1eb44332009-09-09 15:08:12 +0000254static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000255 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-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 Stumpc4c90452009-10-27 22:09:17 +0000263namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000264class HasSideEffect
Mike Stumpc4c90452009-10-27 22:09:17 +0000265 : public StmtVisitor<HasSideEffect, bool> {
266 EvalInfo &Info;
267public:
268
269 HasSideEffect(EvalInfo &info) : Info(info) {}
270
271 // Unhandled nodes conservatively default to having side effects.
272 bool VisitStmt(Stmt *S) {
273 return true;
274 }
275
276 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000277 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
278 return Visit(E->getResultExpr());
279 }
Mike Stumpc4c90452009-10-27 22:09:17 +0000280 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000281 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000282 return true;
283 return false;
284 }
285 // We don't want to evaluate BlockExprs multiple times, as they generate
286 // a ton of code.
287 bool VisitBlockExpr(BlockExpr *E) { return true; }
288 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
289 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
290 { return Visit(E->getInitializer()); }
291 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
292 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
293 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
294 bool VisitStringLiteral(StringLiteral *E) { return false; }
295 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000296 bool VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E)
297 { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000298 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000299 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000300 bool VisitChooseExpr(ChooseExpr *E)
301 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
302 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
303 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stump3f0147e2009-10-29 23:34:20 +0000304 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stump980ca222009-10-29 20:48:09 +0000305 bool VisitBinaryOperator(BinaryOperator *E)
306 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000307 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
308 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
309 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
310 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
311 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000312 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000313 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000314 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000315 }
316 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000317
318 // Has side effects if any element does.
319 bool VisitInitListExpr(InitListExpr *E) {
320 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
321 if (Visit(E->getInit(i))) return true;
322 return false;
323 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000324
325 bool VisitSizeOfPackExpr(SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000326};
327
John McCall56ca35d2011-02-17 10:25:35 +0000328class OpaqueValueEvaluation {
329 EvalInfo &info;
330 OpaqueValueExpr *opaqueValue;
331
332public:
333 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
334 Expr *value)
335 : info(info), opaqueValue(opaqueValue) {
336
337 // If evaluation fails, fail immediately.
338 if (!Evaluate(info, value)) {
339 this->opaqueValue = 0;
340 return;
341 }
342 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
343 }
344
345 bool hasError() const { return opaqueValue == 0; }
346
347 ~OpaqueValueEvaluation() {
348 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
349 }
350};
351
Mike Stumpc4c90452009-10-27 22:09:17 +0000352} // end anonymous namespace
353
Eli Friedman4efaa272008-11-12 09:44:48 +0000354//===----------------------------------------------------------------------===//
355// LValue Evaluation
356//===----------------------------------------------------------------------===//
357namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000358class LValueExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000359 : public StmtVisitor<LValueExprEvaluator, bool> {
Eli Friedman4efaa272008-11-12 09:44:48 +0000360 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000361 LValue &Result;
362
363 bool Success(Expr *E) {
364 Result.Base = E;
365 Result.Offset = CharUnits::Zero();
366 return true;
367 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000368public:
Mike Stump1eb44332009-09-09 15:08:12 +0000369
John McCallefdb83e2010-05-07 21:00:08 +0000370 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
371 Info(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000372
John McCallefdb83e2010-05-07 21:00:08 +0000373 bool VisitStmt(Stmt *S) {
374 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000375 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000376
John McCallefdb83e2010-05-07 21:00:08 +0000377 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000378 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
379 return Visit(E->getResultExpr());
380 }
John McCallefdb83e2010-05-07 21:00:08 +0000381 bool VisitDeclRefExpr(DeclRefExpr *E);
382 bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); }
383 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
384 bool VisitMemberExpr(MemberExpr *E);
385 bool VisitStringLiteral(StringLiteral *E) { return Success(E); }
386 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); }
387 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E);
388 bool VisitUnaryDeref(UnaryOperator *E);
389 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000390 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000391 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000392 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlsson26bc2202009-10-03 16:30:22 +0000393
John McCallefdb83e2010-05-07 21:00:08 +0000394 bool VisitCastExpr(CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000395 switch (E->getCastKind()) {
396 default:
John McCallefdb83e2010-05-07 21:00:08 +0000397 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000398
John McCall2de56d12010-08-25 11:45:40 +0000399 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000400 return Visit(E->getSubExpr());
401 }
402 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000403 // FIXME: Missing: __real__, __imag__
Eli Friedman4efaa272008-11-12 09:44:48 +0000404};
405} // end anonymous namespace
406
John McCallefdb83e2010-05-07 21:00:08 +0000407static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
408 return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Eli Friedman4efaa272008-11-12 09:44:48 +0000409}
410
John McCallefdb83e2010-05-07 21:00:08 +0000411bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000412 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000413 return Success(E);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000414 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
415 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000416 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000417 // Reference parameters can refer to anything even if they have an
418 // "initializer" in the form of a default argument.
419 if (isa<ParmVarDecl>(VD))
420 return false;
Eli Friedmand933a012009-08-29 19:09:59 +0000421 // FIXME: Check whether VD might be overridden!
Sebastian Redl31310a22010-02-01 20:16:42 +0000422 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000423 return Visit(const_cast<Expr *>(Init));
Eli Friedman50c39ea2009-05-27 06:04:58 +0000424 }
425
John McCallefdb83e2010-05-07 21:00:08 +0000426 return false;
Anders Carlsson35873c42008-11-24 04:41:22 +0000427}
428
John McCallefdb83e2010-05-07 21:00:08 +0000429bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000430 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000431}
432
John McCallefdb83e2010-05-07 21:00:08 +0000433bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000434 QualType Ty;
435 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000436 if (!EvaluatePointer(E->getBase(), Result, Info))
437 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000438 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000439 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000440 if (!Visit(E->getBase()))
441 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000442 Ty = E->getBase()->getType();
443 }
444
Ted Kremenek6217b802009-07-29 21:53:49 +0000445 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000446 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000447
448 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
449 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000450 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000451
452 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000453 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000454
Eli Friedman4efaa272008-11-12 09:44:48 +0000455 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000456 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000457 for (RecordDecl::field_iterator Field = RD->field_begin(),
458 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000459 Field != FieldEnd; (void)++Field, ++i) {
460 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000461 break;
462 }
463
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000464 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000465 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000466}
467
John McCallefdb83e2010-05-07 21:00:08 +0000468bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000469 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000470 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Anders Carlsson3068d112008-11-16 19:01:22 +0000472 APSInt Index;
473 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000474 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000475
Ken Dyck199c3d62010-01-11 17:06:35 +0000476 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000477 Result.Offset += Index.getSExtValue() * ElementSize;
478 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000479}
Eli Friedman4efaa272008-11-12 09:44:48 +0000480
John McCallefdb83e2010-05-07 21:00:08 +0000481bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
482 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000483}
484
Eli Friedman4efaa272008-11-12 09:44:48 +0000485//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000486// Pointer Evaluation
487//===----------------------------------------------------------------------===//
488
Anders Carlssonc754aa62008-07-08 05:13:58 +0000489namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000490class PointerExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000491 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000492 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000493 LValue &Result;
494
495 bool Success(Expr *E) {
496 Result.Base = E;
497 Result.Offset = CharUnits::Zero();
498 return true;
499 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000500public:
Mike Stump1eb44332009-09-09 15:08:12 +0000501
John McCallefdb83e2010-05-07 21:00:08 +0000502 PointerExprEvaluator(EvalInfo &info, LValue &Result)
503 : Info(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000504
John McCallefdb83e2010-05-07 21:00:08 +0000505 bool VisitStmt(Stmt *S) {
506 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000507 }
508
John McCallefdb83e2010-05-07 21:00:08 +0000509 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000510 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
511 return Visit(E->getResultExpr());
512 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000513
John McCallefdb83e2010-05-07 21:00:08 +0000514 bool VisitBinaryOperator(const BinaryOperator *E);
515 bool VisitCastExpr(CastExpr* E);
516 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman2217c872009-02-22 11:46:18 +0000517 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000518 bool VisitUnaryAddrOf(const UnaryOperator *E);
519 bool VisitObjCStringLiteral(ObjCStringLiteral *E)
520 { return Success(E); }
521 bool VisitAddrLabelExpr(AddrLabelExpr *E)
522 { return Success(E); }
523 bool VisitCallExpr(CallExpr *E);
524 bool VisitBlockExpr(BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000525 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000526 return Success(E);
527 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000528 }
John McCallefdb83e2010-05-07 21:00:08 +0000529 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
530 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000531 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
John McCallefdb83e2010-05-07 21:00:08 +0000532 bool VisitConditionalOperator(ConditionalOperator *E);
533 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000534 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallefdb83e2010-05-07 21:00:08 +0000535 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
536 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000537
538 bool VisitOpaqueValueExpr(OpaqueValueExpr *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000539 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000540};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000541} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000542
John McCallefdb83e2010-05-07 21:00:08 +0000543static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000544 assert(E->getType()->hasPointerRepresentation());
John McCallefdb83e2010-05-07 21:00:08 +0000545 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000546}
547
John McCallefdb83e2010-05-07 21:00:08 +0000548bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000549 if (E->getOpcode() != BO_Add &&
550 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000551 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000553 const Expr *PExp = E->getLHS();
554 const Expr *IExp = E->getRHS();
555 if (IExp->getType()->isPointerType())
556 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000557
John McCallefdb83e2010-05-07 21:00:08 +0000558 if (!EvaluatePointer(PExp, Result, Info))
559 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000560
John McCallefdb83e2010-05-07 21:00:08 +0000561 llvm::APSInt Offset;
562 if (!EvaluateInteger(IExp, Offset, Info))
563 return false;
564 int64_t AdditionalOffset
565 = Offset.isSigned() ? Offset.getSExtValue()
566 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000567
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000568 // Compute the new offset in the appropriate width.
569
570 QualType PointeeType =
571 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000572 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000574 // Explicitly handle GNU void* and function pointer arithmetic extensions.
575 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000576 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000577 else
John McCallefdb83e2010-05-07 21:00:08 +0000578 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000579
John McCall2de56d12010-08-25 11:45:40 +0000580 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000581 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000582 else
John McCallefdb83e2010-05-07 21:00:08 +0000583 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000584
John McCallefdb83e2010-05-07 21:00:08 +0000585 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000586}
Eli Friedman4efaa272008-11-12 09:44:48 +0000587
John McCallefdb83e2010-05-07 21:00:08 +0000588bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
589 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000590}
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000592
John McCallefdb83e2010-05-07 21:00:08 +0000593bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000594 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000595
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000596 switch (E->getCastKind()) {
597 default:
598 break;
599
John McCall2de56d12010-08-25 11:45:40 +0000600 case CK_NoOp:
601 case CK_BitCast:
John McCall2de56d12010-08-25 11:45:40 +0000602 case CK_AnyPointerToObjCPointerCast:
603 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000604 return Visit(SubExpr);
605
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000606 case CK_DerivedToBase:
607 case CK_UncheckedDerivedToBase: {
608 LValue BaseLV;
609 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
610 return false;
611
612 // Now figure out the necessary offset to add to the baseLV to get from
613 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000614 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000615
616 QualType Ty = E->getSubExpr()->getType();
617 const CXXRecordDecl *DerivedDecl =
618 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
619
620 for (CastExpr::path_const_iterator PathI = E->path_begin(),
621 PathE = E->path_end(); PathI != PathE; ++PathI) {
622 const CXXBaseSpecifier *Base = *PathI;
623
624 // FIXME: If the base is virtual, we'd need to determine the type of the
625 // most derived class and we don't support that right now.
626 if (Base->isVirtual())
627 return false;
628
629 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
630 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
631
Ken Dyck7c7f8202011-01-26 02:17:08 +0000632 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000633 DerivedDecl = BaseDecl;
634 }
635
636 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000637 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000638 return true;
639 }
640
John McCall404cd162010-11-13 01:35:44 +0000641 case CK_NullToPointer: {
642 Result.Base = 0;
643 Result.Offset = CharUnits::Zero();
644 return true;
645 }
646
John McCall2de56d12010-08-25 11:45:40 +0000647 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000648 APValue Value;
649 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000650 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000651
John McCallefdb83e2010-05-07 21:00:08 +0000652 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000653 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000654 Result.Base = 0;
655 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
656 return true;
657 } else {
658 // Cast is of an lvalue, no need to change value.
659 Result.Base = Value.getLValueBase();
660 Result.Offset = Value.getLValueOffset();
661 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000662 }
663 }
John McCall2de56d12010-08-25 11:45:40 +0000664 case CK_ArrayToPointerDecay:
665 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000666 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000667 }
668
John McCallefdb83e2010-05-07 21:00:08 +0000669 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000670}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000671
John McCallefdb83e2010-05-07 21:00:08 +0000672bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000673 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000674 Builtin::BI__builtin___CFStringMakeConstantString ||
675 E->isBuiltinCall(Info.Ctx) ==
676 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000677 return Success(E);
678 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000679}
680
John McCall56ca35d2011-02-17 10:25:35 +0000681bool PointerExprEvaluator::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
682 const APValue *value = Info.getOpaqueValue(e);
683 if (!value)
684 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
685 Result.setFrom(*value);
686 return true;
687}
688
689bool PointerExprEvaluator::
690VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
691 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
692 if (opaque.hasError()) return false;
693
694 bool cond;
695 if (!HandleConversionToBool(e->getCond(), cond, Info))
696 return false;
697
698 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
699}
700
John McCallefdb83e2010-05-07 21:00:08 +0000701bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000702 bool BoolResult;
703 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000704 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000705
706 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000707 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000708}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000709
710//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000711// Vector Evaluation
712//===----------------------------------------------------------------------===//
713
714namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000715 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000716 : public StmtVisitor<VectorExprEvaluator, APValue> {
717 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000718 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000719 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Nate Begeman59b5da62009-01-18 03:20:47 +0000721 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Nate Begeman59b5da62009-01-18 03:20:47 +0000723 APValue VisitStmt(Stmt *S) {
724 return APValue();
725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Eli Friedman91110ee2009-02-23 04:23:56 +0000727 APValue VisitParenExpr(ParenExpr *E)
728 { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000729 APValue VisitGenericSelectionExpr(GenericSelectionExpr *E)
730 { return Visit(E->getResultExpr()); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000731 APValue VisitUnaryExtension(const UnaryOperator *E)
732 { return Visit(E->getSubExpr()); }
733 APValue VisitUnaryPlus(const UnaryOperator *E)
734 { return Visit(E->getSubExpr()); }
735 APValue VisitUnaryReal(const UnaryOperator *E)
736 { return Visit(E->getSubExpr()); }
737 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
738 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000739 APValue VisitCastExpr(const CastExpr* E);
740 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
741 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000742 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000743 APValue VisitChooseExpr(const ChooseExpr *E)
744 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000745 APValue VisitUnaryImag(const UnaryOperator *E);
746 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000747 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000748 // shufflevector, ExtVectorElementExpr
749 // (Note that these require implementing conversions
750 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000751 };
752} // end anonymous namespace
753
754static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
755 if (!E->getType()->isVectorType())
756 return false;
757 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
758 return !Result.isUninit();
759}
760
761APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000762 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000763 QualType EltTy = VTy->getElementType();
764 unsigned NElts = VTy->getNumElements();
765 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Nate Begeman59b5da62009-01-18 03:20:47 +0000767 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000768 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000769
Eli Friedman46a52322011-03-25 00:43:55 +0000770 switch (E->getCastKind()) {
771 case CK_VectorSplat: {
772 APValue Result = APValue();
773 if (SETy->isIntegerType()) {
774 APSInt IntResult;
775 if (!EvaluateInteger(SE, IntResult, Info))
776 return APValue();
777 Result = APValue(IntResult);
778 } else if (SETy->isRealFloatingType()) {
779 APFloat F(0.0);
780 if (!EvaluateFloat(SE, F, Info))
781 return APValue();
782 Result = APValue(F);
783 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000784 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000785 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000786
787 // Splat and create vector APValue.
788 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
789 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000790 }
Eli Friedman46a52322011-03-25 00:43:55 +0000791 case CK_BitCast: {
792 if (SETy->isVectorType())
793 return Visit(const_cast<Expr*>(SE));
Nate Begemanc0b8b192009-07-01 07:50:47 +0000794
Eli Friedman46a52322011-03-25 00:43:55 +0000795 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000796 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Eli Friedman46a52322011-03-25 00:43:55 +0000798 APSInt Init;
799 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000800 return APValue();
801
Eli Friedman46a52322011-03-25 00:43:55 +0000802 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
803 "Vectors must be composed of ints or floats");
804
805 llvm::SmallVector<APValue, 4> Elts;
806 for (unsigned i = 0; i != NElts; ++i) {
807 APSInt Tmp = Init.extOrTrunc(EltWidth);
808
809 if (EltTy->isIntegerType())
810 Elts.push_back(APValue(Tmp));
811 else
812 Elts.push_back(APValue(APFloat(Tmp)));
813
814 Init >>= EltWidth;
815 }
816 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000817 }
Eli Friedman46a52322011-03-25 00:43:55 +0000818 case CK_LValueToRValue:
819 case CK_NoOp:
820 return Visit(const_cast<Expr*>(SE));
821 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000822 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000823 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000824}
825
Mike Stump1eb44332009-09-09 15:08:12 +0000826APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000827VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
828 return this->Visit(const_cast<Expr*>(E->getInitializer()));
829}
830
Mike Stump1eb44332009-09-09 15:08:12 +0000831APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000832VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000833 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000834 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000835 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Nate Begeman59b5da62009-01-18 03:20:47 +0000837 QualType EltTy = VT->getElementType();
838 llvm::SmallVector<APValue, 4> Elements;
839
John McCalla7d6c222010-06-11 17:54:15 +0000840 // If a vector is initialized with a single element, that value
841 // becomes every element of the vector, not just the first.
842 // This is the behavior described in the IBM AltiVec documentation.
843 if (NumInits == 1) {
844 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000845 if (EltTy->isIntegerType()) {
846 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000847 if (!EvaluateInteger(E->getInit(0), sInt, Info))
848 return APValue();
849 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000850 } else {
851 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000852 if (!EvaluateFloat(E->getInit(0), f, Info))
853 return APValue();
854 InitValue = APValue(f);
855 }
856 for (unsigned i = 0; i < NumElements; i++) {
857 Elements.push_back(InitValue);
858 }
859 } else {
860 for (unsigned i = 0; i < NumElements; i++) {
861 if (EltTy->isIntegerType()) {
862 llvm::APSInt sInt(32);
863 if (i < NumInits) {
864 if (!EvaluateInteger(E->getInit(i), sInt, Info))
865 return APValue();
866 } else {
867 sInt = Info.Ctx.MakeIntValue(0, EltTy);
868 }
869 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000870 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000871 llvm::APFloat f(0.0);
872 if (i < NumInits) {
873 if (!EvaluateFloat(E->getInit(i), f, Info))
874 return APValue();
875 } else {
876 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
877 }
878 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000879 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000880 }
881 }
882 return APValue(&Elements[0], Elements.size());
883}
884
Mike Stump1eb44332009-09-09 15:08:12 +0000885APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000886VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000887 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000888 QualType EltTy = VT->getElementType();
889 APValue ZeroElement;
890 if (EltTy->isIntegerType())
891 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
892 else
893 ZeroElement =
894 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
895
896 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
897 return APValue(&Elements[0], Elements.size());
898}
899
900APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
901 bool BoolResult;
902 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
903 return APValue();
904
905 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
906
907 APValue Result;
908 if (EvaluateVector(EvalExpr, Result, Info))
909 return Result;
910 return APValue();
911}
912
Eli Friedman91110ee2009-02-23 04:23:56 +0000913APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
914 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
915 Info.EvalResult.HasSideEffects = true;
916 return GetZeroVector(E->getType());
917}
918
Nate Begeman59b5da62009-01-18 03:20:47 +0000919//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000920// Integer Evaluation
921//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000922
923namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000924class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000925 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000926 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000927 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000928public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000929 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000930 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000931
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000932 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000933 assert(E->getType()->isIntegralOrEnumerationType() &&
934 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000935 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000936 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000937 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000938 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000939 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000940 return true;
941 }
942
Daniel Dunbar131eb432009-02-19 09:06:44 +0000943 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000944 assert(E->getType()->isIntegralOrEnumerationType() &&
945 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000946 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000947 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000948 Result = APValue(APSInt(I));
949 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000950 return true;
951 }
952
953 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000954 assert(E->getType()->isIntegralOrEnumerationType() &&
955 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000956 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000957 return true;
958 }
959
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000960 bool Success(CharUnits Size, const Expr *E) {
961 return Success(Size.getQuantity(), E);
962 }
963
964
Anders Carlsson82206e22008-11-30 18:14:57 +0000965 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000966 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000967 if (Info.EvalResult.Diag == 0) {
968 Info.EvalResult.DiagLoc = L;
969 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000970 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000971 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000972 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000973 }
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Anders Carlssonc754aa62008-07-08 05:13:58 +0000975 //===--------------------------------------------------------------------===//
976 // Visitor Methods
977 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattner32fea9d2008-11-12 07:43:42 +0000979 bool VisitStmt(Stmt *) {
980 assert(0 && "This should be called on integers, stmts are not integers");
981 return false;
982 }
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Chris Lattner32fea9d2008-11-12 07:43:42 +0000984 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000985 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000986 }
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Chris Lattnerb542afe2008-07-11 19:10:17 +0000988 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000989 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
990 return Visit(E->getResultExpr());
991 }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000992
Chris Lattner4c4867e2008-07-12 00:38:25 +0000993 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000994 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000995 }
996 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000997 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000998 }
Eli Friedman04309752009-11-24 05:28:59 +0000999
John McCall56ca35d2011-02-17 10:25:35 +00001000 bool VisitOpaqueValueExpr(OpaqueValueExpr *e) {
1001 const APValue *value = Info.getOpaqueValue(e);
1002 if (!value) {
1003 if (e->getSourceExpr()) return Visit(e->getSourceExpr());
1004 return Error(e->getExprLoc(), diag::note_invalid_subexpr_in_ice, e);
1005 }
1006 return Success(value->getInt(), e);
1007 }
1008
Eli Friedman04309752009-11-24 05:28:59 +00001009 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1010 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1011 return CheckReferencedDecl(E, E->getDecl());
1012 }
1013 bool VisitMemberExpr(const MemberExpr *E) {
1014 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1015 // Conservatively assume a MemberExpr will have side-effects
1016 Info.EvalResult.HasSideEffects = true;
1017 return true;
1018 }
1019 return false;
1020 }
1021
Eli Friedmanc4a26382010-02-13 00:10:10 +00001022 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001023 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001024 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001025 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001026 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001027 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001028
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001029 bool VisitCastExpr(CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001030 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001031
Anders Carlsson3068d112008-11-16 19:01:22 +00001032 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001033 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001034 }
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Anders Carlsson3f704562008-12-21 22:39:40 +00001036 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001037 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001038 }
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Douglas Gregored8abf12010-07-08 06:14:04 +00001040 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001041 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001042 }
1043
Eli Friedman664a1042009-02-27 04:45:43 +00001044 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1045 return Success(0, E);
1046 }
1047
Sebastian Redl64b45f72009-01-05 20:52:13 +00001048 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001049 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001050 }
1051
Francois Pichet6ad6f282010-12-07 00:08:36 +00001052 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1053 return Success(E->getValue(), E);
1054 }
1055
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001056 bool VisitChooseExpr(const ChooseExpr *E) {
1057 return Visit(E->getChosenSubExpr(Info.Ctx));
1058 }
1059
Eli Friedman722c7172009-02-28 03:59:05 +00001060 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001061 bool VisitUnaryImag(const UnaryOperator *E);
1062
Sebastian Redl295995c2010-09-10 20:55:47 +00001063 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001064 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1065
Chris Lattnerfcee0012008-07-11 21:24:13 +00001066private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001067 CharUnits GetAlignOfExpr(const Expr *E);
1068 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001069 static QualType GetObjectType(const Expr *E);
1070 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001071 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001072};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001073} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001074
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001075static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001076 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001077 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1078}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001079
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001080static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001081 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001082
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001083 APValue Val;
1084 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1085 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001086 Result = Val.getInt();
1087 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001088}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001089
Eli Friedman04309752009-11-24 05:28:59 +00001090bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001091 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +00001092 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1093 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001094
1095 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001096 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001097 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1098 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001099
1100 if (isa<ParmVarDecl>(D))
1101 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1102
Eli Friedman04309752009-11-24 05:28:59 +00001103 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001104 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001105 if (APValue *V = VD->getEvaluatedValue()) {
1106 if (V->isInt())
1107 return Success(V->getInt(), E);
1108 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1109 }
1110
1111 if (VD->isEvaluatingValue())
1112 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1113
1114 VD->setEvaluatingValue();
1115
Eli Friedmana7dedf72010-09-06 00:10:32 +00001116 Expr::EvalResult EResult;
1117 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1118 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001119 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001120 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001121 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001122 return true;
1123 }
1124
Eli Friedmanc0131182009-12-03 20:31:57 +00001125 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001126 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001127 }
1128 }
1129
Chris Lattner4c4867e2008-07-12 00:38:25 +00001130 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001131 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001132}
1133
Chris Lattnera4d55d82008-10-06 06:40:35 +00001134/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1135/// as GCC.
1136static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1137 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001138 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001139 enum gcc_type_class {
1140 no_type_class = -1,
1141 void_type_class, integer_type_class, char_type_class,
1142 enumeral_type_class, boolean_type_class,
1143 pointer_type_class, reference_type_class, offset_type_class,
1144 real_type_class, complex_type_class,
1145 function_type_class, method_type_class,
1146 record_type_class, union_type_class,
1147 array_type_class, string_type_class,
1148 lang_type_class
1149 };
Mike Stump1eb44332009-09-09 15:08:12 +00001150
1151 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001152 // ideal, however it is what gcc does.
1153 if (E->getNumArgs() == 0)
1154 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Chris Lattnera4d55d82008-10-06 06:40:35 +00001156 QualType ArgTy = E->getArg(0)->getType();
1157 if (ArgTy->isVoidType())
1158 return void_type_class;
1159 else if (ArgTy->isEnumeralType())
1160 return enumeral_type_class;
1161 else if (ArgTy->isBooleanType())
1162 return boolean_type_class;
1163 else if (ArgTy->isCharType())
1164 return string_type_class; // gcc doesn't appear to use char_type_class
1165 else if (ArgTy->isIntegerType())
1166 return integer_type_class;
1167 else if (ArgTy->isPointerType())
1168 return pointer_type_class;
1169 else if (ArgTy->isReferenceType())
1170 return reference_type_class;
1171 else if (ArgTy->isRealType())
1172 return real_type_class;
1173 else if (ArgTy->isComplexType())
1174 return complex_type_class;
1175 else if (ArgTy->isFunctionType())
1176 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001177 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001178 return record_type_class;
1179 else if (ArgTy->isUnionType())
1180 return union_type_class;
1181 else if (ArgTy->isArrayType())
1182 return array_type_class;
1183 else if (ArgTy->isUnionType())
1184 return union_type_class;
1185 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1186 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1187 return -1;
1188}
1189
John McCall42c8f872010-05-10 23:27:23 +00001190/// Retrieves the "underlying object type" of the given expression,
1191/// as used by __builtin_object_size.
1192QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1193 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1194 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1195 return VD->getType();
1196 } else if (isa<CompoundLiteralExpr>(E)) {
1197 return E->getType();
1198 }
1199
1200 return QualType();
1201}
1202
1203bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1204 // TODO: Perhaps we should let LLVM lower this?
1205 LValue Base;
1206 if (!EvaluatePointer(E->getArg(0), Base, Info))
1207 return false;
1208
1209 // If we can prove the base is null, lower to zero now.
1210 const Expr *LVBase = Base.getLValueBase();
1211 if (!LVBase) return Success(0, E);
1212
1213 QualType T = GetObjectType(LVBase);
1214 if (T.isNull() ||
1215 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001216 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001217 T->isVariablyModifiedType() ||
1218 T->isDependentType())
1219 return false;
1220
1221 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1222 CharUnits Offset = Base.getLValueOffset();
1223
1224 if (!Offset.isNegative() && Offset <= Size)
1225 Size -= Offset;
1226 else
1227 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001228 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001229}
1230
Eli Friedmanc4a26382010-02-13 00:10:10 +00001231bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001232 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001233 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001234 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001235
1236 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001237 if (TryEvaluateBuiltinObjectSize(E))
1238 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001239
Eric Christopherb2aaf512010-01-19 22:58:35 +00001240 // If evaluating the argument has side-effects we can't determine
1241 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001242 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001243 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001244 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001245 return Success(0, E);
1246 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001247
Mike Stump64eda9e2009-10-26 18:35:08 +00001248 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1249 }
1250
Chris Lattner019f4e82008-10-06 05:28:25 +00001251 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001252 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001254 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001255 // __builtin_constant_p always has one operand: it returns true if that
1256 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001257 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001258
1259 case Builtin::BI__builtin_eh_return_data_regno: {
1260 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1261 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1262 return Success(Operand, E);
1263 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001264
1265 case Builtin::BI__builtin_expect:
1266 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001267
1268 case Builtin::BIstrlen:
1269 case Builtin::BI__builtin_strlen:
1270 // As an extension, we support strlen() and __builtin_strlen() as constant
1271 // expressions when the argument is a string literal.
1272 if (StringLiteral *S
1273 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1274 // The string literal may have embedded null characters. Find the first
1275 // one and truncate there.
1276 llvm::StringRef Str = S->getString();
1277 llvm::StringRef::size_type Pos = Str.find(0);
1278 if (Pos != llvm::StringRef::npos)
1279 Str = Str.substr(0, Pos);
1280
1281 return Success(Str.size(), E);
1282 }
1283
1284 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001285 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001286}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001287
Chris Lattnerb542afe2008-07-11 19:10:17 +00001288bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001289 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001290 if (!Visit(E->getRHS()))
1291 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001292
Eli Friedman33ef1452009-02-26 10:19:36 +00001293 // If we can't evaluate the LHS, it might have side effects;
1294 // conservatively mark it.
1295 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1296 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001297
Anders Carlsson027f62e2008-12-01 02:07:06 +00001298 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001299 }
1300
1301 if (E->isLogicalOp()) {
1302 // These need to be handled specially because the operands aren't
1303 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001304 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001306 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001307 // We were able to evaluate the LHS, see if we can get away with not
1308 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001309 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001310 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001311
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001312 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001313 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001314 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001315 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001316 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001317 }
1318 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001319 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001320 // We can't evaluate the LHS; however, sometimes the result
1321 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001322 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1323 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001324 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001325 // must have had side effects.
1326 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001327
1328 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001329 }
1330 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001331 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001332
Eli Friedmana6afa762008-11-13 06:09:17 +00001333 return false;
1334 }
1335
Anders Carlsson286f85e2008-11-16 07:17:21 +00001336 QualType LHSTy = E->getLHS()->getType();
1337 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001338
1339 if (LHSTy->isAnyComplexType()) {
1340 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001341 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001342
1343 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1344 return false;
1345
1346 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1347 return false;
1348
1349 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001350 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001351 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001352 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001353 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1354
John McCall2de56d12010-08-25 11:45:40 +00001355 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001356 return Success((CR_r == APFloat::cmpEqual &&
1357 CR_i == APFloat::cmpEqual), E);
1358 else {
John McCall2de56d12010-08-25 11:45:40 +00001359 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001360 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001361 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001362 CR_r == APFloat::cmpLessThan ||
1363 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001364 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001365 CR_i == APFloat::cmpLessThan ||
1366 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001367 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001368 } else {
John McCall2de56d12010-08-25 11:45:40 +00001369 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001370 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1371 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1372 else {
John McCall2de56d12010-08-25 11:45:40 +00001373 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001374 "Invalid compex comparison.");
1375 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1376 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1377 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001378 }
1379 }
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Anders Carlsson286f85e2008-11-16 07:17:21 +00001381 if (LHSTy->isRealFloatingType() &&
1382 RHSTy->isRealFloatingType()) {
1383 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Anders Carlsson286f85e2008-11-16 07:17:21 +00001385 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1386 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Anders Carlsson286f85e2008-11-16 07:17:21 +00001388 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1389 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Anders Carlsson286f85e2008-11-16 07:17:21 +00001391 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001392
Anders Carlsson286f85e2008-11-16 07:17:21 +00001393 switch (E->getOpcode()) {
1394 default:
1395 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001396 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001397 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001398 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001399 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001400 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001401 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001402 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001403 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001404 E);
John McCall2de56d12010-08-25 11:45:40 +00001405 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001406 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001407 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001408 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001409 || CR == APFloat::cmpLessThan
1410 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001411 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001412 }
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001414 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001415 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001416 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001417 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1418 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001419
John McCallefdb83e2010-05-07 21:00:08 +00001420 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001421 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1422 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001423
Eli Friedman5bc86102009-06-14 02:17:33 +00001424 // Reject any bases from the normal codepath; we special-case comparisons
1425 // to null.
1426 if (LHSValue.getLValueBase()) {
1427 if (!E->isEqualityOp())
1428 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001429 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001430 return false;
1431 bool bres;
1432 if (!EvalPointerValueAsBool(LHSValue, bres))
1433 return false;
John McCall2de56d12010-08-25 11:45:40 +00001434 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001435 } else if (RHSValue.getLValueBase()) {
1436 if (!E->isEqualityOp())
1437 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001438 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001439 return false;
1440 bool bres;
1441 if (!EvalPointerValueAsBool(RHSValue, bres))
1442 return false;
John McCall2de56d12010-08-25 11:45:40 +00001443 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001444 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001445
John McCall2de56d12010-08-25 11:45:40 +00001446 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001447 QualType Type = E->getLHS()->getType();
1448 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001449
Ken Dycka7305832010-01-15 12:37:54 +00001450 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001451 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001452 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001453
Ken Dycka7305832010-01-15 12:37:54 +00001454 CharUnits Diff = LHSValue.getLValueOffset() -
1455 RHSValue.getLValueOffset();
1456 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001457 }
1458 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001459 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001460 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001461 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001462 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1463 }
1464 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001465 }
1466 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001467 if (!LHSTy->isIntegralOrEnumerationType() ||
1468 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001469 // We can't continue from here for non-integral types, and they
1470 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001471 return false;
1472 }
1473
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001474 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001475 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001476 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001477
Eli Friedman42edd0d2009-03-24 01:14:50 +00001478 APValue RHSVal;
1479 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001480 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001481
1482 // Handle cases like (unsigned long)&a + 4.
1483 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001484 CharUnits Offset = Result.getLValueOffset();
1485 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1486 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001487 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001488 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001489 else
Ken Dycka7305832010-01-15 12:37:54 +00001490 Offset -= AdditionalOffset;
1491 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001492 return true;
1493 }
1494
1495 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001496 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001497 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001498 CharUnits Offset = RHSVal.getLValueOffset();
1499 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1500 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001501 return true;
1502 }
1503
1504 // All the following cases expect both operands to be an integer
1505 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001506 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001507
Eli Friedman42edd0d2009-03-24 01:14:50 +00001508 APSInt& RHS = RHSVal.getInt();
1509
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001510 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001511 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001512 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001513 case BO_Mul: return Success(Result.getInt() * RHS, E);
1514 case BO_Add: return Success(Result.getInt() + RHS, E);
1515 case BO_Sub: return Success(Result.getInt() - RHS, E);
1516 case BO_And: return Success(Result.getInt() & RHS, E);
1517 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1518 case BO_Or: return Success(Result.getInt() | RHS, E);
1519 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001520 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001521 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001522 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001523 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001524 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001525 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001526 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001527 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001528 // During constant-folding, a negative shift is an opposite shift.
1529 if (RHS.isSigned() && RHS.isNegative()) {
1530 RHS = -RHS;
1531 goto shift_right;
1532 }
1533
1534 shift_left:
1535 unsigned SA
1536 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001537 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001538 }
John McCall2de56d12010-08-25 11:45:40 +00001539 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001540 // During constant-folding, a negative shift is an opposite shift.
1541 if (RHS.isSigned() && RHS.isNegative()) {
1542 RHS = -RHS;
1543 goto shift_left;
1544 }
1545
1546 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001547 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001548 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1549 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001550 }
Mike Stump1eb44332009-09-09 15:08:12 +00001551
John McCall2de56d12010-08-25 11:45:40 +00001552 case BO_LT: return Success(Result.getInt() < RHS, E);
1553 case BO_GT: return Success(Result.getInt() > RHS, E);
1554 case BO_LE: return Success(Result.getInt() <= RHS, E);
1555 case BO_GE: return Success(Result.getInt() >= RHS, E);
1556 case BO_EQ: return Success(Result.getInt() == RHS, E);
1557 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001558 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001559}
1560
John McCall56ca35d2011-02-17 10:25:35 +00001561bool IntExprEvaluator::
1562VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
1563 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
1564 if (opaque.hasError()) return false;
1565
1566 bool cond;
1567 if (!HandleConversionToBool(e->getCond(), cond, Info))
1568 return false;
1569
1570 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
1571}
1572
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001573bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001574 bool Cond;
1575 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001576 return false;
1577
Nuno Lopesa25bd552008-11-16 22:06:39 +00001578 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001579}
1580
Ken Dyck8b752f12010-01-27 17:10:57 +00001581CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001582 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1583 // the result is the size of the referenced type."
1584 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1585 // result shall be the alignment of the referenced type."
1586 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1587 T = Ref->getPointeeType();
1588
Eli Friedman2be58612009-05-30 21:09:44 +00001589 // __alignof is defined to return the preferred alignment.
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001590 return Info.Ctx.toCharUnitsFromBits(
1591 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001592}
1593
Ken Dyck8b752f12010-01-27 17:10:57 +00001594CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001595 E = E->IgnoreParens();
1596
1597 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001598 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001599 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001600 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1601 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001602
Chris Lattneraf707ab2009-01-24 21:53:27 +00001603 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001604 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1605 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001606
Chris Lattnere9feb472009-01-24 21:09:06 +00001607 return GetAlignOfType(E->getType());
1608}
1609
1610
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001611/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1612/// a result as the expression's type.
1613bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1614 const UnaryExprOrTypeTraitExpr *E) {
1615 switch(E->getKind()) {
1616 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001617 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001618 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001619 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001620 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001621 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001622
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001623 case UETT_VecStep: {
1624 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001625
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001626 if (Ty->isVectorType()) {
1627 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001628
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001629 // The vec_step built-in functions that take a 3-component
1630 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1631 if (n == 3)
1632 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001633
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001634 return Success(n, E);
1635 } else
1636 return Success(1, E);
1637 }
1638
1639 case UETT_SizeOf: {
1640 QualType SrcTy = E->getTypeOfArgument();
1641 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1642 // the result is the size of the referenced type."
1643 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1644 // result shall be the alignment of the referenced type."
1645 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1646 SrcTy = Ref->getPointeeType();
1647
1648 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1649 // extension.
1650 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1651 return Success(1, E);
1652
1653 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1654 if (!SrcTy->isConstantSizeType())
1655 return false;
1656
1657 // Get information about the size.
1658 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1659 }
1660 }
1661
1662 llvm_unreachable("unknown expr/type trait");
1663 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001664}
1665
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001666bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1667 CharUnits Result;
1668 unsigned n = E->getNumComponents();
1669 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1670 if (n == 0)
1671 return false;
1672 QualType CurrentType = E->getTypeSourceInfo()->getType();
1673 for (unsigned i = 0; i != n; ++i) {
1674 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1675 switch (ON.getKind()) {
1676 case OffsetOfExpr::OffsetOfNode::Array: {
1677 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1678 APSInt IdxResult;
1679 if (!EvaluateInteger(Idx, IdxResult, Info))
1680 return false;
1681 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1682 if (!AT)
1683 return false;
1684 CurrentType = AT->getElementType();
1685 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1686 Result += IdxResult.getSExtValue() * ElementSize;
1687 break;
1688 }
1689
1690 case OffsetOfExpr::OffsetOfNode::Field: {
1691 FieldDecl *MemberDecl = ON.getField();
1692 const RecordType *RT = CurrentType->getAs<RecordType>();
1693 if (!RT)
1694 return false;
1695 RecordDecl *RD = RT->getDecl();
1696 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001697 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001698 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001699 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001700 CurrentType = MemberDecl->getType().getNonReferenceType();
1701 break;
1702 }
1703
1704 case OffsetOfExpr::OffsetOfNode::Identifier:
1705 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001706 return false;
1707
1708 case OffsetOfExpr::OffsetOfNode::Base: {
1709 CXXBaseSpecifier *BaseSpec = ON.getBase();
1710 if (BaseSpec->isVirtual())
1711 return false;
1712
1713 // Find the layout of the class whose base we are looking into.
1714 const RecordType *RT = CurrentType->getAs<RecordType>();
1715 if (!RT)
1716 return false;
1717 RecordDecl *RD = RT->getDecl();
1718 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1719
1720 // Find the base class itself.
1721 CurrentType = BaseSpec->getType();
1722 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1723 if (!BaseRT)
1724 return false;
1725
1726 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001727 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001728 break;
1729 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001730 }
1731 }
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001732 return Success(Result, E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001733}
1734
Chris Lattnerb542afe2008-07-11 19:10:17 +00001735bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001736 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001737 // LNot's operand isn't necessarily an integer, so we handle it specially.
1738 bool bres;
1739 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1740 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001741 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001742 }
1743
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001744 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001745 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001746 return false;
1747
Chris Lattner87eae5e2008-07-11 22:52:41 +00001748 // Get the operand value into 'Result'.
1749 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001750 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001751
Chris Lattner75a48812008-07-11 22:15:16 +00001752 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001753 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001754 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1755 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001756 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001757 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001758 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1759 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001760 return true;
John McCall2de56d12010-08-25 11:45:40 +00001761 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001762 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001763 return true;
John McCall2de56d12010-08-25 11:45:40 +00001764 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001765 if (!Result.isInt()) return false;
1766 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001767 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001768 if (!Result.isInt()) return false;
1769 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001770 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001771}
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Chris Lattner732b2232008-07-12 01:15:53 +00001773/// HandleCast - This is used to evaluate implicit or explicit casts where the
1774/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001775bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001776 Expr *SubExpr = E->getSubExpr();
1777 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001778 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001779
Eli Friedman46a52322011-03-25 00:43:55 +00001780 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001781 case CK_BaseToDerived:
1782 case CK_DerivedToBase:
1783 case CK_UncheckedDerivedToBase:
1784 case CK_Dynamic:
1785 case CK_ToUnion:
1786 case CK_ArrayToPointerDecay:
1787 case CK_FunctionToPointerDecay:
1788 case CK_NullToPointer:
1789 case CK_NullToMemberPointer:
1790 case CK_BaseToDerivedMemberPointer:
1791 case CK_DerivedToBaseMemberPointer:
1792 case CK_ConstructorConversion:
1793 case CK_IntegralToPointer:
1794 case CK_ToVoid:
1795 case CK_VectorSplat:
1796 case CK_IntegralToFloating:
1797 case CK_FloatingCast:
1798 case CK_AnyPointerToObjCPointerCast:
1799 case CK_AnyPointerToBlockPointerCast:
1800 case CK_ObjCObjectLValueCast:
1801 case CK_FloatingRealToComplex:
1802 case CK_FloatingComplexToReal:
1803 case CK_FloatingComplexCast:
1804 case CK_FloatingComplexToIntegralComplex:
1805 case CK_IntegralRealToComplex:
1806 case CK_IntegralComplexCast:
1807 case CK_IntegralComplexToFloatingComplex:
1808 llvm_unreachable("invalid cast kind for integral value");
1809
Eli Friedmane50c2972011-03-25 19:07:11 +00001810 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001811 case CK_Dependent:
1812 case CK_GetObjCProperty:
1813 case CK_LValueBitCast:
1814 case CK_UserDefinedConversion:
1815 return false;
1816
1817 case CK_LValueToRValue:
1818 case CK_NoOp:
1819 return Visit(E->getSubExpr());
1820
1821 case CK_MemberPointerToBoolean:
1822 case CK_PointerToBoolean:
1823 case CK_IntegralToBoolean:
1824 case CK_FloatingToBoolean:
1825 case CK_FloatingComplexToBoolean:
1826 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001827 bool BoolResult;
1828 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1829 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001830 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001831 }
1832
Eli Friedman46a52322011-03-25 00:43:55 +00001833 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001834 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001835 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001836
Eli Friedmanbe265702009-02-20 01:15:07 +00001837 if (!Result.isInt()) {
1838 // Only allow casts of lvalues if they are lossless.
1839 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1840 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001841
Daniel Dunbardd211642009-02-19 22:24:01 +00001842 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001843 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Eli Friedman46a52322011-03-25 00:43:55 +00001846 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001847 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001848 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001849 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001850
Daniel Dunbardd211642009-02-19 22:24:01 +00001851 if (LV.getLValueBase()) {
1852 // Only allow based lvalue casts if they are lossless.
1853 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1854 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001855
John McCallefdb83e2010-05-07 21:00:08 +00001856 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001857 return true;
1858 }
1859
Ken Dycka7305832010-01-15 12:37:54 +00001860 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1861 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001862 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001863 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001864
Eli Friedman46a52322011-03-25 00:43:55 +00001865 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001866 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001867 if (!EvaluateComplex(SubExpr, C, Info))
1868 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001869 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001870 }
Eli Friedman2217c872009-02-22 11:46:18 +00001871
Eli Friedman46a52322011-03-25 00:43:55 +00001872 case CK_FloatingToIntegral: {
1873 APFloat F(0.0);
1874 if (!EvaluateFloat(SubExpr, F, Info))
1875 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001876
Eli Friedman46a52322011-03-25 00:43:55 +00001877 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1878 }
1879 }
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Eli Friedman46a52322011-03-25 00:43:55 +00001881 llvm_unreachable("unknown cast resulting in integral value");
1882 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001883}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001884
Eli Friedman722c7172009-02-28 03:59:05 +00001885bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1886 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001887 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001888 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1889 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1890 return Success(LV.getComplexIntReal(), E);
1891 }
1892
1893 return Visit(E->getSubExpr());
1894}
1895
Eli Friedman664a1042009-02-27 04:45:43 +00001896bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001897 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001898 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001899 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1900 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1901 return Success(LV.getComplexIntImag(), E);
1902 }
1903
Eli Friedman664a1042009-02-27 04:45:43 +00001904 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1905 Info.EvalResult.HasSideEffects = true;
1906 return Success(0, E);
1907}
1908
Douglas Gregoree8aff02011-01-04 17:33:58 +00001909bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1910 return Success(E->getPackLength(), E);
1911}
1912
Sebastian Redl295995c2010-09-10 20:55:47 +00001913bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1914 return Success(E->getValue(), E);
1915}
1916
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001917//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001918// Float Evaluation
1919//===----------------------------------------------------------------------===//
1920
1921namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001922class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001923 : public StmtVisitor<FloatExprEvaluator, bool> {
1924 EvalInfo &Info;
1925 APFloat &Result;
1926public:
1927 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1928 : Info(info), Result(result) {}
1929
1930 bool VisitStmt(Stmt *S) {
1931 return false;
1932 }
1933
1934 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +00001935 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
1936 return Visit(E->getResultExpr());
1937 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001938 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001939
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001940 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001941 bool VisitBinaryOperator(const BinaryOperator *E);
1942 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001943 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001944 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001945 bool VisitConditionalOperator(ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001946 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001947
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001948 bool VisitChooseExpr(const ChooseExpr *E)
1949 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1950 bool VisitUnaryExtension(const UnaryOperator *E)
1951 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001952 bool VisitUnaryReal(const UnaryOperator *E);
1953 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001954
John McCall189d6ef2010-10-09 01:34:31 +00001955 bool VisitDeclRefExpr(const DeclRefExpr *E);
1956
John McCall56ca35d2011-02-17 10:25:35 +00001957 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
1958 const APValue *value = Info.getOpaqueValue(e);
1959 if (!value)
1960 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
1961 Result = value->getFloat();
1962 return true;
1963 }
1964
John McCallabd3a852010-05-07 22:08:54 +00001965 // FIXME: Missing: array subscript of vector, member of vector,
1966 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001967};
1968} // end anonymous namespace
1969
1970static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001971 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001972 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1973}
1974
Jay Foad4ba2a172011-01-12 09:06:06 +00001975static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001976 QualType ResultTy,
1977 const Expr *Arg,
1978 bool SNaN,
1979 llvm::APFloat &Result) {
1980 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1981 if (!S) return false;
1982
1983 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1984
1985 llvm::APInt fill;
1986
1987 // Treat empty strings as if they were zero.
1988 if (S->getString().empty())
1989 fill = llvm::APInt(32, 0);
1990 else if (S->getString().getAsInteger(0, fill))
1991 return false;
1992
1993 if (SNaN)
1994 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1995 else
1996 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1997 return true;
1998}
1999
Chris Lattner019f4e82008-10-06 05:28:25 +00002000bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00002001 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00002002 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00002003 case Builtin::BI__builtin_huge_val:
2004 case Builtin::BI__builtin_huge_valf:
2005 case Builtin::BI__builtin_huge_vall:
2006 case Builtin::BI__builtin_inf:
2007 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002008 case Builtin::BI__builtin_infl: {
2009 const llvm::fltSemantics &Sem =
2010 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002011 Result = llvm::APFloat::getInf(Sem);
2012 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002013 }
Mike Stump1eb44332009-09-09 15:08:12 +00002014
John McCalldb7b72a2010-02-28 13:00:19 +00002015 case Builtin::BI__builtin_nans:
2016 case Builtin::BI__builtin_nansf:
2017 case Builtin::BI__builtin_nansl:
2018 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2019 true, Result);
2020
Chris Lattner9e621712008-10-06 06:31:58 +00002021 case Builtin::BI__builtin_nan:
2022 case Builtin::BI__builtin_nanf:
2023 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002024 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002025 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002026 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2027 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002028
2029 case Builtin::BI__builtin_fabs:
2030 case Builtin::BI__builtin_fabsf:
2031 case Builtin::BI__builtin_fabsl:
2032 if (!EvaluateFloat(E->getArg(0), Result, Info))
2033 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002035 if (Result.isNegative())
2036 Result.changeSign();
2037 return true;
2038
Mike Stump1eb44332009-09-09 15:08:12 +00002039 case Builtin::BI__builtin_copysign:
2040 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002041 case Builtin::BI__builtin_copysignl: {
2042 APFloat RHS(0.);
2043 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2044 !EvaluateFloat(E->getArg(1), RHS, Info))
2045 return false;
2046 Result.copySign(RHS);
2047 return true;
2048 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002049 }
2050}
2051
John McCall189d6ef2010-10-09 01:34:31 +00002052bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2053 const Decl *D = E->getDecl();
2054 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2055 const VarDecl *VD = cast<VarDecl>(D);
2056
2057 // Require the qualifiers to be const and not volatile.
2058 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2059 if (!T.isConstQualified() || T.isVolatileQualified())
2060 return false;
2061
2062 const Expr *Init = VD->getAnyInitializer();
2063 if (!Init) return false;
2064
2065 if (APValue *V = VD->getEvaluatedValue()) {
2066 if (V->isFloat()) {
2067 Result = V->getFloat();
2068 return true;
2069 }
2070 return false;
2071 }
2072
2073 if (VD->isEvaluatingValue())
2074 return false;
2075
2076 VD->setEvaluatingValue();
2077
2078 Expr::EvalResult InitResult;
2079 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2080 InitResult.Val.isFloat()) {
2081 // Cache the evaluated value in the variable declaration.
2082 Result = InitResult.Val.getFloat();
2083 VD->setEvaluatedValue(InitResult.Val);
2084 return true;
2085 }
2086
2087 VD->setEvaluatedValue(APValue());
2088 return false;
2089}
2090
John McCallabd3a852010-05-07 22:08:54 +00002091bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002092 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2093 ComplexValue CV;
2094 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2095 return false;
2096 Result = CV.FloatReal;
2097 return true;
2098 }
2099
2100 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002101}
2102
2103bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002104 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2105 ComplexValue CV;
2106 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2107 return false;
2108 Result = CV.FloatImag;
2109 return true;
2110 }
2111
2112 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2113 Info.EvalResult.HasSideEffects = true;
2114 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2115 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002116 return true;
2117}
2118
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002119bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002120 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002121 return false;
2122
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002123 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2124 return false;
2125
2126 switch (E->getOpcode()) {
2127 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002128 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002129 return true;
John McCall2de56d12010-08-25 11:45:40 +00002130 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002131 Result.changeSign();
2132 return true;
2133 }
2134}
Chris Lattner019f4e82008-10-06 05:28:25 +00002135
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002136bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002137 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002138 if (!EvaluateFloat(E->getRHS(), Result, Info))
2139 return false;
2140
2141 // If we can't evaluate the LHS, it might have side effects;
2142 // conservatively mark it.
2143 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2144 Info.EvalResult.HasSideEffects = true;
2145
2146 return true;
2147 }
2148
Anders Carlsson96e93662010-10-31 01:21:47 +00002149 // We can't evaluate pointer-to-member operations.
2150 if (E->isPtrMemOp())
2151 return false;
2152
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002153 // FIXME: Diagnostics? I really don't understand how the warnings
2154 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002155 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002156 if (!EvaluateFloat(E->getLHS(), Result, Info))
2157 return false;
2158 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2159 return false;
2160
2161 switch (E->getOpcode()) {
2162 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002163 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002164 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2165 return true;
John McCall2de56d12010-08-25 11:45:40 +00002166 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002167 Result.add(RHS, APFloat::rmNearestTiesToEven);
2168 return true;
John McCall2de56d12010-08-25 11:45:40 +00002169 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002170 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2171 return true;
John McCall2de56d12010-08-25 11:45:40 +00002172 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002173 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2174 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002175 }
2176}
2177
2178bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2179 Result = E->getValue();
2180 return true;
2181}
2182
Eli Friedman4efaa272008-11-12 09:44:48 +00002183bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2184 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Eli Friedman2a523ee2011-03-25 00:54:52 +00002186 switch (E->getCastKind()) {
2187 default:
2188 return false;
2189
2190 case CK_LValueToRValue:
2191 case CK_NoOp:
2192 return Visit(SubExpr);
2193
2194 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002195 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002196 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002197 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002198 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002199 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002200 return true;
2201 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002202
2203 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002204 if (!Visit(SubExpr))
2205 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002206 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2207 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002208 return true;
2209 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002210
Eli Friedman2a523ee2011-03-25 00:54:52 +00002211 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002212 ComplexValue V;
2213 if (!EvaluateComplex(SubExpr, V, Info))
2214 return false;
2215 Result = V.getComplexFloatReal();
2216 return true;
2217 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002218 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002219
2220 return false;
2221}
2222
Douglas Gregored8abf12010-07-08 06:14:04 +00002223bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002224 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2225 return true;
2226}
2227
John McCall56ca35d2011-02-17 10:25:35 +00002228bool FloatExprEvaluator::
2229VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
2230 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2231 if (opaque.hasError()) return false;
2232
2233 bool cond;
2234 if (!HandleConversionToBool(e->getCond(), cond, Info))
2235 return false;
2236
2237 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2238}
2239
Eli Friedman67f85fc2009-12-04 02:12:53 +00002240bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2241 bool Cond;
2242 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2243 return false;
2244
2245 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2246}
2247
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002248//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002249// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002250//===----------------------------------------------------------------------===//
2251
2252namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002253class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00002254 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002255 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00002256 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002258public:
John McCallf4cf1a12010-05-07 17:22:02 +00002259 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2260 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002262 //===--------------------------------------------------------------------===//
2263 // Visitor Methods
2264 //===--------------------------------------------------------------------===//
2265
John McCallf4cf1a12010-05-07 17:22:02 +00002266 bool VisitStmt(Stmt *S) {
2267 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002268 }
Mike Stump1eb44332009-09-09 15:08:12 +00002269
John McCallf4cf1a12010-05-07 17:22:02 +00002270 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +00002271 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
2272 return Visit(E->getResultExpr());
2273 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002274
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002275 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002276
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002277 bool VisitCastExpr(CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002278
John McCallf4cf1a12010-05-07 17:22:02 +00002279 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002280 bool VisitUnaryOperator(const UnaryOperator *E);
2281 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00002282 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
John McCallf4cf1a12010-05-07 17:22:02 +00002283 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002284 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002285 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002286 { return Visit(E->getSubExpr()); }
John McCall56ca35d2011-02-17 10:25:35 +00002287 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
2288 const APValue *value = Info.getOpaqueValue(e);
2289 if (!value)
2290 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
2291 Result.setFrom(*value);
2292 return true;
2293 }
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002294 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002295};
2296} // end anonymous namespace
2297
John McCallf4cf1a12010-05-07 17:22:02 +00002298static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2299 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002300 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002301 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002302}
2303
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002304bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2305 Expr* SubExpr = E->getSubExpr();
2306
2307 if (SubExpr->getType()->isRealFloatingType()) {
2308 Result.makeComplexFloat();
2309 APFloat &Imag = Result.FloatImag;
2310 if (!EvaluateFloat(SubExpr, Imag, Info))
2311 return false;
2312
2313 Result.FloatReal = APFloat(Imag.getSemantics());
2314 return true;
2315 } else {
2316 assert(SubExpr->getType()->isIntegerType() &&
2317 "Unexpected imaginary literal.");
2318
2319 Result.makeComplexInt();
2320 APSInt &Imag = Result.IntImag;
2321 if (!EvaluateInteger(SubExpr, Imag, Info))
2322 return false;
2323
2324 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2325 return true;
2326 }
2327}
2328
2329bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002330
John McCall8786da72010-12-14 17:51:41 +00002331 switch (E->getCastKind()) {
2332 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002333 case CK_BaseToDerived:
2334 case CK_DerivedToBase:
2335 case CK_UncheckedDerivedToBase:
2336 case CK_Dynamic:
2337 case CK_ToUnion:
2338 case CK_ArrayToPointerDecay:
2339 case CK_FunctionToPointerDecay:
2340 case CK_NullToPointer:
2341 case CK_NullToMemberPointer:
2342 case CK_BaseToDerivedMemberPointer:
2343 case CK_DerivedToBaseMemberPointer:
2344 case CK_MemberPointerToBoolean:
2345 case CK_ConstructorConversion:
2346 case CK_IntegralToPointer:
2347 case CK_PointerToIntegral:
2348 case CK_PointerToBoolean:
2349 case CK_ToVoid:
2350 case CK_VectorSplat:
2351 case CK_IntegralCast:
2352 case CK_IntegralToBoolean:
2353 case CK_IntegralToFloating:
2354 case CK_FloatingToIntegral:
2355 case CK_FloatingToBoolean:
2356 case CK_FloatingCast:
2357 case CK_AnyPointerToObjCPointerCast:
2358 case CK_AnyPointerToBlockPointerCast:
2359 case CK_ObjCObjectLValueCast:
2360 case CK_FloatingComplexToReal:
2361 case CK_FloatingComplexToBoolean:
2362 case CK_IntegralComplexToReal:
2363 case CK_IntegralComplexToBoolean:
2364 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002365
John McCall8786da72010-12-14 17:51:41 +00002366 case CK_LValueToRValue:
2367 case CK_NoOp:
2368 return Visit(E->getSubExpr());
2369
2370 case CK_Dependent:
2371 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002372 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002373 case CK_UserDefinedConversion:
2374 return false;
2375
2376 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002377 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002378 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002379 return false;
2380
John McCall8786da72010-12-14 17:51:41 +00002381 Result.makeComplexFloat();
2382 Result.FloatImag = APFloat(Real.getSemantics());
2383 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002384 }
2385
John McCall8786da72010-12-14 17:51:41 +00002386 case CK_FloatingComplexCast: {
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.FloatReal
2395 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2396 Result.FloatImag
2397 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2398 return true;
2399 }
2400
2401 case CK_FloatingComplexToIntegralComplex: {
2402 if (!Visit(E->getSubExpr()))
2403 return false;
2404
2405 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2406 QualType From
2407 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2408 Result.makeComplexInt();
2409 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2410 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2411 return true;
2412 }
2413
2414 case CK_IntegralRealToComplex: {
2415 APSInt &Real = Result.IntReal;
2416 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2417 return false;
2418
2419 Result.makeComplexInt();
2420 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2421 return true;
2422 }
2423
2424 case CK_IntegralComplexCast: {
2425 if (!Visit(E->getSubExpr()))
2426 return false;
2427
2428 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2429 QualType From
2430 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2431
2432 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2433 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2434 return true;
2435 }
2436
2437 case CK_IntegralComplexToFloatingComplex: {
2438 if (!Visit(E->getSubExpr()))
2439 return false;
2440
2441 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2442 QualType From
2443 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2444 Result.makeComplexFloat();
2445 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2446 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2447 return true;
2448 }
2449 }
2450
2451 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002452 return false;
2453}
2454
John McCallf4cf1a12010-05-07 17:22:02 +00002455bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002456 if (E->getOpcode() == BO_Comma) {
2457 if (!Visit(E->getRHS()))
2458 return false;
2459
2460 // If we can't evaluate the LHS, it might have side effects;
2461 // conservatively mark it.
2462 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2463 Info.EvalResult.HasSideEffects = true;
2464
2465 return true;
2466 }
John McCallf4cf1a12010-05-07 17:22:02 +00002467 if (!Visit(E->getLHS()))
2468 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002469
John McCallf4cf1a12010-05-07 17:22:02 +00002470 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002471 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002472 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002473
Daniel Dunbar3f279872009-01-29 01:32:56 +00002474 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2475 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002476 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002477 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002478 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002479 if (Result.isComplexFloat()) {
2480 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2481 APFloat::rmNearestTiesToEven);
2482 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2483 APFloat::rmNearestTiesToEven);
2484 } else {
2485 Result.getComplexIntReal() += RHS.getComplexIntReal();
2486 Result.getComplexIntImag() += RHS.getComplexIntImag();
2487 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002488 break;
John McCall2de56d12010-08-25 11:45:40 +00002489 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002490 if (Result.isComplexFloat()) {
2491 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2492 APFloat::rmNearestTiesToEven);
2493 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2494 APFloat::rmNearestTiesToEven);
2495 } else {
2496 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2497 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2498 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002499 break;
John McCall2de56d12010-08-25 11:45:40 +00002500 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002501 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002502 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002503 APFloat &LHS_r = LHS.getComplexFloatReal();
2504 APFloat &LHS_i = LHS.getComplexFloatImag();
2505 APFloat &RHS_r = RHS.getComplexFloatReal();
2506 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002507
Daniel Dunbar3f279872009-01-29 01:32:56 +00002508 APFloat Tmp = LHS_r;
2509 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2510 Result.getComplexFloatReal() = Tmp;
2511 Tmp = LHS_i;
2512 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2513 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2514
2515 Tmp = LHS_r;
2516 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2517 Result.getComplexFloatImag() = Tmp;
2518 Tmp = LHS_i;
2519 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2520 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2521 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002522 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002523 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002524 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2525 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002526 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002527 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2528 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2529 }
2530 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002531 case BO_Div:
2532 if (Result.isComplexFloat()) {
2533 ComplexValue LHS = Result;
2534 APFloat &LHS_r = LHS.getComplexFloatReal();
2535 APFloat &LHS_i = LHS.getComplexFloatImag();
2536 APFloat &RHS_r = RHS.getComplexFloatReal();
2537 APFloat &RHS_i = RHS.getComplexFloatImag();
2538 APFloat &Res_r = Result.getComplexFloatReal();
2539 APFloat &Res_i = Result.getComplexFloatImag();
2540
2541 APFloat Den = RHS_r;
2542 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2543 APFloat Tmp = RHS_i;
2544 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2545 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2546
2547 Res_r = LHS_r;
2548 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2549 Tmp = LHS_i;
2550 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2551 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2552 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2553
2554 Res_i = LHS_i;
2555 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2556 Tmp = LHS_r;
2557 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2558 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2559 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2560 } else {
2561 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2562 // FIXME: what about diagnostics?
2563 return false;
2564 }
2565 ComplexValue LHS = Result;
2566 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2567 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2568 Result.getComplexIntReal() =
2569 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2570 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2571 Result.getComplexIntImag() =
2572 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2573 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2574 }
2575 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002576 }
2577
John McCallf4cf1a12010-05-07 17:22:02 +00002578 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002579}
2580
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002581bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2582 // Get the operand value into 'Result'.
2583 if (!Visit(E->getSubExpr()))
2584 return false;
2585
2586 switch (E->getOpcode()) {
2587 default:
2588 // FIXME: what about diagnostics?
2589 return false;
2590 case UO_Extension:
2591 return true;
2592 case UO_Plus:
2593 // The result is always just the subexpr.
2594 return true;
2595 case UO_Minus:
2596 if (Result.isComplexFloat()) {
2597 Result.getComplexFloatReal().changeSign();
2598 Result.getComplexFloatImag().changeSign();
2599 }
2600 else {
2601 Result.getComplexIntReal() = -Result.getComplexIntReal();
2602 Result.getComplexIntImag() = -Result.getComplexIntImag();
2603 }
2604 return true;
2605 case UO_Not:
2606 if (Result.isComplexFloat())
2607 Result.getComplexFloatImag().changeSign();
2608 else
2609 Result.getComplexIntImag() = -Result.getComplexIntImag();
2610 return true;
2611 }
2612}
2613
John McCall56ca35d2011-02-17 10:25:35 +00002614bool ComplexExprEvaluator::
2615VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
2616 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2617 if (opaque.hasError()) return false;
2618
2619 bool cond;
2620 if (!HandleConversionToBool(e->getCond(), cond, Info))
2621 return false;
2622
2623 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2624}
2625
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002626bool ComplexExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
2627 bool Cond;
2628 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2629 return false;
2630
2631 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2632}
2633
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002634//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002635// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002636//===----------------------------------------------------------------------===//
2637
John McCall56ca35d2011-02-17 10:25:35 +00002638static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002639 if (E->getType()->isVectorType()) {
2640 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002641 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002642 } else if (E->getType()->isIntegerType()) {
2643 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002644 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002645 if (Info.EvalResult.Val.isLValue() &&
2646 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002647 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002648 } else if (E->getType()->hasPointerRepresentation()) {
2649 LValue LV;
2650 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002651 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002652 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002653 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002654 LV.moveInto(Info.EvalResult.Val);
2655 } else if (E->getType()->isRealFloatingType()) {
2656 llvm::APFloat F(0.0);
2657 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002658 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002659
John McCallefdb83e2010-05-07 21:00:08 +00002660 Info.EvalResult.Val = APValue(F);
2661 } else if (E->getType()->isAnyComplexType()) {
2662 ComplexValue C;
2663 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002664 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002665 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002666 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002667 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002668
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002669 return true;
2670}
2671
John McCall56ca35d2011-02-17 10:25:35 +00002672/// Evaluate - Return true if this is a constant which we can fold using
2673/// any crazy technique (that has nothing to do with language standards) that
2674/// we want to. If this function returns true, it returns the folded constant
2675/// in Result.
2676bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2677 EvalInfo Info(Ctx, Result);
2678 return ::Evaluate(Info, this);
2679}
2680
Jay Foad4ba2a172011-01-12 09:06:06 +00002681bool Expr::EvaluateAsBooleanCondition(bool &Result,
2682 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002683 EvalResult Scratch;
2684 EvalInfo Info(Ctx, Scratch);
2685
2686 return HandleConversionToBool(this, Result, Info);
2687}
2688
Jay Foad4ba2a172011-01-12 09:06:06 +00002689bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002690 EvalInfo Info(Ctx, Result);
2691
John McCallefdb83e2010-05-07 21:00:08 +00002692 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002693 if (EvaluateLValue(this, LV, Info) &&
2694 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002695 IsGlobalLValue(LV.Base)) {
2696 LV.moveInto(Result.Val);
2697 return true;
2698 }
2699 return false;
2700}
2701
Jay Foad4ba2a172011-01-12 09:06:06 +00002702bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2703 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002704 EvalInfo Info(Ctx, Result);
2705
2706 LValue LV;
2707 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002708 LV.moveInto(Result.Val);
2709 return true;
2710 }
2711 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002712}
2713
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002714/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002715/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002716bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002717 EvalResult Result;
2718 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002719}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002720
Jay Foad4ba2a172011-01-12 09:06:06 +00002721bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002722 Expr::EvalResult Result;
2723 EvalInfo Info(Ctx, Result);
2724 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2725}
2726
Jay Foad4ba2a172011-01-12 09:06:06 +00002727APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002728 EvalResult EvalResult;
2729 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002730 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002731 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002732 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002733
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002734 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002735}
John McCalld905f5a2010-05-07 05:32:02 +00002736
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002737 bool Expr::EvalResult::isGlobalLValue() const {
2738 assert(Val.isLValue());
2739 return IsGlobalLValue(Val.getLValueBase());
2740 }
2741
2742
John McCalld905f5a2010-05-07 05:32:02 +00002743/// isIntegerConstantExpr - this recursive routine will test if an expression is
2744/// an integer constant expression.
2745
2746/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2747/// comma, etc
2748///
2749/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2750/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2751/// cast+dereference.
2752
2753// CheckICE - This function does the fundamental ICE checking: the returned
2754// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2755// Note that to reduce code duplication, this helper does no evaluation
2756// itself; the caller checks whether the expression is evaluatable, and
2757// in the rare cases where CheckICE actually cares about the evaluated
2758// value, it calls into Evalute.
2759//
2760// Meanings of Val:
2761// 0: This expression is an ICE if it can be evaluated by Evaluate.
2762// 1: This expression is not an ICE, but if it isn't evaluated, it's
2763// a legal subexpression for an ICE. This return value is used to handle
2764// the comma operator in C99 mode.
2765// 2: This expression is not an ICE, and is not a legal subexpression for one.
2766
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002767namespace {
2768
John McCalld905f5a2010-05-07 05:32:02 +00002769struct ICEDiag {
2770 unsigned Val;
2771 SourceLocation Loc;
2772
2773 public:
2774 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2775 ICEDiag() : Val(0) {}
2776};
2777
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002778}
2779
2780static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002781
2782static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2783 Expr::EvalResult EVResult;
2784 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2785 !EVResult.Val.isInt()) {
2786 return ICEDiag(2, E->getLocStart());
2787 }
2788 return NoDiag();
2789}
2790
2791static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2792 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002793 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002794 return ICEDiag(2, E->getLocStart());
2795 }
2796
2797 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002798#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002799#define STMT(Node, Base) case Expr::Node##Class:
2800#define EXPR(Node, Base)
2801#include "clang/AST/StmtNodes.inc"
2802 case Expr::PredefinedExprClass:
2803 case Expr::FloatingLiteralClass:
2804 case Expr::ImaginaryLiteralClass:
2805 case Expr::StringLiteralClass:
2806 case Expr::ArraySubscriptExprClass:
2807 case Expr::MemberExprClass:
2808 case Expr::CompoundAssignOperatorClass:
2809 case Expr::CompoundLiteralExprClass:
2810 case Expr::ExtVectorElementExprClass:
2811 case Expr::InitListExprClass:
2812 case Expr::DesignatedInitExprClass:
2813 case Expr::ImplicitValueInitExprClass:
2814 case Expr::ParenListExprClass:
2815 case Expr::VAArgExprClass:
2816 case Expr::AddrLabelExprClass:
2817 case Expr::StmtExprClass:
2818 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002819 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002820 case Expr::CXXDynamicCastExprClass:
2821 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002822 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002823 case Expr::CXXNullPtrLiteralExprClass:
2824 case Expr::CXXThisExprClass:
2825 case Expr::CXXThrowExprClass:
2826 case Expr::CXXNewExprClass:
2827 case Expr::CXXDeleteExprClass:
2828 case Expr::CXXPseudoDestructorExprClass:
2829 case Expr::UnresolvedLookupExprClass:
2830 case Expr::DependentScopeDeclRefExprClass:
2831 case Expr::CXXConstructExprClass:
2832 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002833 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002834 case Expr::CXXTemporaryObjectExprClass:
2835 case Expr::CXXUnresolvedConstructExprClass:
2836 case Expr::CXXDependentScopeMemberExprClass:
2837 case Expr::UnresolvedMemberExprClass:
2838 case Expr::ObjCStringLiteralClass:
2839 case Expr::ObjCEncodeExprClass:
2840 case Expr::ObjCMessageExprClass:
2841 case Expr::ObjCSelectorExprClass:
2842 case Expr::ObjCProtocolExprClass:
2843 case Expr::ObjCIvarRefExprClass:
2844 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002845 case Expr::ObjCIsaExprClass:
2846 case Expr::ShuffleVectorExprClass:
2847 case Expr::BlockExprClass:
2848 case Expr::BlockDeclRefExprClass:
2849 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002850 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002851 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002852 case Expr::SubstNonTypeTemplateParmPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002853 return ICEDiag(2, E->getLocStart());
2854
Douglas Gregoree8aff02011-01-04 17:33:58 +00002855 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002856 case Expr::GNUNullExprClass:
2857 // GCC considers the GNU __null value to be an integral constant expression.
2858 return NoDiag();
2859
2860 case Expr::ParenExprClass:
2861 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002862 case Expr::GenericSelectionExprClass:
2863 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002864 case Expr::IntegerLiteralClass:
2865 case Expr::CharacterLiteralClass:
2866 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002867 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002868 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002869 case Expr::BinaryTypeTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002870 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002871 return NoDiag();
2872 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002873 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002874 const CallExpr *CE = cast<CallExpr>(E);
2875 if (CE->isBuiltinCall(Ctx))
2876 return CheckEvalInICE(E, Ctx);
2877 return ICEDiag(2, E->getLocStart());
2878 }
2879 case Expr::DeclRefExprClass:
2880 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2881 return NoDiag();
2882 if (Ctx.getLangOptions().CPlusPlus &&
2883 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2884 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2885
2886 // Parameter variables are never constants. Without this check,
2887 // getAnyInitializer() can find a default argument, which leads
2888 // to chaos.
2889 if (isa<ParmVarDecl>(D))
2890 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2891
2892 // C++ 7.1.5.1p2
2893 // A variable of non-volatile const-qualified integral or enumeration
2894 // type initialized by an ICE can be used in ICEs.
2895 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2896 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2897 if (Quals.hasVolatile() || !Quals.hasConst())
2898 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2899
2900 // Look for a declaration of this variable that has an initializer.
2901 const VarDecl *ID = 0;
2902 const Expr *Init = Dcl->getAnyInitializer(ID);
2903 if (Init) {
2904 if (ID->isInitKnownICE()) {
2905 // We have already checked whether this subexpression is an
2906 // integral constant expression.
2907 if (ID->isInitICE())
2908 return NoDiag();
2909 else
2910 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2911 }
2912
2913 // It's an ICE whether or not the definition we found is
2914 // out-of-line. See DR 721 and the discussion in Clang PR
2915 // 6206 for details.
2916
2917 if (Dcl->isCheckingICE()) {
2918 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2919 }
2920
2921 Dcl->setCheckingICE();
2922 ICEDiag Result = CheckICE(Init, Ctx);
2923 // Cache the result of the ICE test.
2924 Dcl->setInitKnownICE(Result.Val == 0);
2925 return Result;
2926 }
2927 }
2928 }
2929 return ICEDiag(2, E->getLocStart());
2930 case Expr::UnaryOperatorClass: {
2931 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2932 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002933 case UO_PostInc:
2934 case UO_PostDec:
2935 case UO_PreInc:
2936 case UO_PreDec:
2937 case UO_AddrOf:
2938 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002939 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002940 case UO_Extension:
2941 case UO_LNot:
2942 case UO_Plus:
2943 case UO_Minus:
2944 case UO_Not:
2945 case UO_Real:
2946 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002947 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002948 }
2949
2950 // OffsetOf falls through here.
2951 }
2952 case Expr::OffsetOfExprClass: {
2953 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2954 // Evaluate matches the proposed gcc behavior for cases like
2955 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2956 // compliance: we should warn earlier for offsetof expressions with
2957 // array subscripts that aren't ICEs, and if the array subscripts
2958 // are ICEs, the value of the offsetof must be an integer constant.
2959 return CheckEvalInICE(E, Ctx);
2960 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002961 case Expr::UnaryExprOrTypeTraitExprClass: {
2962 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2963 if ((Exp->getKind() == UETT_SizeOf) &&
2964 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002965 return ICEDiag(2, E->getLocStart());
2966 return NoDiag();
2967 }
2968 case Expr::BinaryOperatorClass: {
2969 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2970 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002971 case BO_PtrMemD:
2972 case BO_PtrMemI:
2973 case BO_Assign:
2974 case BO_MulAssign:
2975 case BO_DivAssign:
2976 case BO_RemAssign:
2977 case BO_AddAssign:
2978 case BO_SubAssign:
2979 case BO_ShlAssign:
2980 case BO_ShrAssign:
2981 case BO_AndAssign:
2982 case BO_XorAssign:
2983 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002984 return ICEDiag(2, E->getLocStart());
2985
John McCall2de56d12010-08-25 11:45:40 +00002986 case BO_Mul:
2987 case BO_Div:
2988 case BO_Rem:
2989 case BO_Add:
2990 case BO_Sub:
2991 case BO_Shl:
2992 case BO_Shr:
2993 case BO_LT:
2994 case BO_GT:
2995 case BO_LE:
2996 case BO_GE:
2997 case BO_EQ:
2998 case BO_NE:
2999 case BO_And:
3000 case BO_Xor:
3001 case BO_Or:
3002 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00003003 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3004 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00003005 if (Exp->getOpcode() == BO_Div ||
3006 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00003007 // Evaluate gives an error for undefined Div/Rem, so make sure
3008 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00003009 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00003010 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
3011 if (REval == 0)
3012 return ICEDiag(1, E->getLocStart());
3013 if (REval.isSigned() && REval.isAllOnesValue()) {
3014 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
3015 if (LEval.isMinSignedValue())
3016 return ICEDiag(1, E->getLocStart());
3017 }
3018 }
3019 }
John McCall2de56d12010-08-25 11:45:40 +00003020 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00003021 if (Ctx.getLangOptions().C99) {
3022 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3023 // if it isn't evaluated.
3024 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3025 return ICEDiag(1, E->getLocStart());
3026 } else {
3027 // In both C89 and C++, commas in ICEs are illegal.
3028 return ICEDiag(2, E->getLocStart());
3029 }
3030 }
3031 if (LHSResult.Val >= RHSResult.Val)
3032 return LHSResult;
3033 return RHSResult;
3034 }
John McCall2de56d12010-08-25 11:45:40 +00003035 case BO_LAnd:
3036 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00003037 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3038 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3039 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3040 // Rare case where the RHS has a comma "side-effect"; we need
3041 // to actually check the condition to see whether the side
3042 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003043 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00003044 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3045 return RHSResult;
3046 return NoDiag();
3047 }
3048
3049 if (LHSResult.Val >= RHSResult.Val)
3050 return LHSResult;
3051 return RHSResult;
3052 }
3053 }
3054 }
3055 case Expr::ImplicitCastExprClass:
3056 case Expr::CStyleCastExprClass:
3057 case Expr::CXXFunctionalCastExprClass:
3058 case Expr::CXXStaticCastExprClass:
3059 case Expr::CXXReinterpretCastExprClass:
3060 case Expr::CXXConstCastExprClass: {
3061 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003062 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003063 return CheckICE(SubExpr, Ctx);
3064 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3065 return NoDiag();
3066 return ICEDiag(2, E->getLocStart());
3067 }
John McCall56ca35d2011-02-17 10:25:35 +00003068 case Expr::BinaryConditionalOperatorClass: {
3069 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3070 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3071 if (CommonResult.Val == 2) return CommonResult;
3072 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3073 if (FalseResult.Val == 2) return FalseResult;
3074 if (CommonResult.Val == 1) return CommonResult;
3075 if (FalseResult.Val == 1 &&
3076 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3077 return FalseResult;
3078 }
John McCalld905f5a2010-05-07 05:32:02 +00003079 case Expr::ConditionalOperatorClass: {
3080 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3081 // If the condition (ignoring parens) is a __builtin_constant_p call,
3082 // then only the true side is actually considered in an integer constant
3083 // expression, and it is fully evaluated. This is an important GNU
3084 // extension. See GCC PR38377 for discussion.
3085 if (const CallExpr *CallCE
3086 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3087 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3088 Expr::EvalResult EVResult;
3089 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3090 !EVResult.Val.isInt()) {
3091 return ICEDiag(2, E->getLocStart());
3092 }
3093 return NoDiag();
3094 }
3095 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
3096 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3097 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3098 if (CondResult.Val == 2)
3099 return CondResult;
3100 if (TrueResult.Val == 2)
3101 return TrueResult;
3102 if (FalseResult.Val == 2)
3103 return FalseResult;
3104 if (CondResult.Val == 1)
3105 return CondResult;
3106 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3107 return NoDiag();
3108 // Rare case where the diagnostics depend on which side is evaluated
3109 // Note that if we get here, CondResult is 0, and at least one of
3110 // TrueResult and FalseResult is non-zero.
3111 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3112 return FalseResult;
3113 }
3114 return TrueResult;
3115 }
3116 case Expr::CXXDefaultArgExprClass:
3117 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3118 case Expr::ChooseExprClass: {
3119 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3120 }
3121 }
3122
3123 // Silence a GCC warning
3124 return ICEDiag(2, E->getLocStart());
3125}
3126
3127bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3128 SourceLocation *Loc, bool isEvaluated) const {
3129 ICEDiag d = CheckICE(this, Ctx);
3130 if (d.Val != 0) {
3131 if (Loc) *Loc = d.Loc;
3132 return false;
3133 }
3134 EvalResult EvalResult;
3135 if (!Evaluate(EvalResult, Ctx))
3136 llvm_unreachable("ICE cannot be evaluated!");
3137 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3138 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3139 Result = EvalResult.Val.getInt();
3140 return true;
3141}