blob: 519bbaa115ecd70f3e277d523d1a4b1632c8150c [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;
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000322 if (Expr *filler = E->getArrayFiller())
323 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000324 return false;
325 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000326
327 bool VisitSizeOfPackExpr(SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000328};
329
John McCall56ca35d2011-02-17 10:25:35 +0000330class OpaqueValueEvaluation {
331 EvalInfo &info;
332 OpaqueValueExpr *opaqueValue;
333
334public:
335 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
336 Expr *value)
337 : info(info), opaqueValue(opaqueValue) {
338
339 // If evaluation fails, fail immediately.
340 if (!Evaluate(info, value)) {
341 this->opaqueValue = 0;
342 return;
343 }
344 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
345 }
346
347 bool hasError() const { return opaqueValue == 0; }
348
349 ~OpaqueValueEvaluation() {
350 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
351 }
352};
353
Mike Stumpc4c90452009-10-27 22:09:17 +0000354} // end anonymous namespace
355
Eli Friedman4efaa272008-11-12 09:44:48 +0000356//===----------------------------------------------------------------------===//
357// LValue Evaluation
358//===----------------------------------------------------------------------===//
359namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000360class LValueExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000361 : public StmtVisitor<LValueExprEvaluator, bool> {
Eli Friedman4efaa272008-11-12 09:44:48 +0000362 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000363 LValue &Result;
364
365 bool Success(Expr *E) {
366 Result.Base = E;
367 Result.Offset = CharUnits::Zero();
368 return true;
369 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000370public:
Mike Stump1eb44332009-09-09 15:08:12 +0000371
John McCallefdb83e2010-05-07 21:00:08 +0000372 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
373 Info(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000374
John McCallefdb83e2010-05-07 21:00:08 +0000375 bool VisitStmt(Stmt *S) {
376 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000377 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000378
John McCallefdb83e2010-05-07 21:00:08 +0000379 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000380 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
381 return Visit(E->getResultExpr());
382 }
John McCallefdb83e2010-05-07 21:00:08 +0000383 bool VisitDeclRefExpr(DeclRefExpr *E);
384 bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); }
385 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
386 bool VisitMemberExpr(MemberExpr *E);
387 bool VisitStringLiteral(StringLiteral *E) { return Success(E); }
388 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); }
389 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E);
390 bool VisitUnaryDeref(UnaryOperator *E);
391 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000392 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000393 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000394 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlsson26bc2202009-10-03 16:30:22 +0000395
John McCallefdb83e2010-05-07 21:00:08 +0000396 bool VisitCastExpr(CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000397 switch (E->getCastKind()) {
398 default:
John McCallefdb83e2010-05-07 21:00:08 +0000399 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000400
John McCall2de56d12010-08-25 11:45:40 +0000401 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000402 return Visit(E->getSubExpr());
403 }
404 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000405 // FIXME: Missing: __real__, __imag__
Eli Friedman4efaa272008-11-12 09:44:48 +0000406};
407} // end anonymous namespace
408
John McCallefdb83e2010-05-07 21:00:08 +0000409static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
410 return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Eli Friedman4efaa272008-11-12 09:44:48 +0000411}
412
John McCallefdb83e2010-05-07 21:00:08 +0000413bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000414 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000415 return Success(E);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000416 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
417 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000418 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000419 // Reference parameters can refer to anything even if they have an
420 // "initializer" in the form of a default argument.
421 if (isa<ParmVarDecl>(VD))
422 return false;
Eli Friedmand933a012009-08-29 19:09:59 +0000423 // FIXME: Check whether VD might be overridden!
Sebastian Redl31310a22010-02-01 20:16:42 +0000424 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000425 return Visit(const_cast<Expr *>(Init));
Eli Friedman50c39ea2009-05-27 06:04:58 +0000426 }
427
John McCallefdb83e2010-05-07 21:00:08 +0000428 return false;
Anders Carlsson35873c42008-11-24 04:41:22 +0000429}
430
John McCallefdb83e2010-05-07 21:00:08 +0000431bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000432 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000433}
434
John McCallefdb83e2010-05-07 21:00:08 +0000435bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000436 QualType Ty;
437 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000438 if (!EvaluatePointer(E->getBase(), Result, Info))
439 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000440 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000441 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000442 if (!Visit(E->getBase()))
443 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000444 Ty = E->getBase()->getType();
445 }
446
Ted Kremenek6217b802009-07-29 21:53:49 +0000447 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000448 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000449
450 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
451 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000452 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000453
454 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000455 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000456
Eli Friedman4efaa272008-11-12 09:44:48 +0000457 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000458 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000459 for (RecordDecl::field_iterator Field = RD->field_begin(),
460 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000461 Field != FieldEnd; (void)++Field, ++i) {
462 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000463 break;
464 }
465
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000466 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000467 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000468}
469
John McCallefdb83e2010-05-07 21:00:08 +0000470bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000471 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000472 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Anders Carlsson3068d112008-11-16 19:01:22 +0000474 APSInt Index;
475 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000476 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000477
Ken Dyck199c3d62010-01-11 17:06:35 +0000478 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000479 Result.Offset += Index.getSExtValue() * ElementSize;
480 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000481}
Eli Friedman4efaa272008-11-12 09:44:48 +0000482
John McCallefdb83e2010-05-07 21:00:08 +0000483bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
484 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000485}
486
Eli Friedman4efaa272008-11-12 09:44:48 +0000487//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000488// Pointer Evaluation
489//===----------------------------------------------------------------------===//
490
Anders Carlssonc754aa62008-07-08 05:13:58 +0000491namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000492class PointerExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000493 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000494 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000495 LValue &Result;
496
497 bool Success(Expr *E) {
498 Result.Base = E;
499 Result.Offset = CharUnits::Zero();
500 return true;
501 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000502public:
Mike Stump1eb44332009-09-09 15:08:12 +0000503
John McCallefdb83e2010-05-07 21:00:08 +0000504 PointerExprEvaluator(EvalInfo &info, LValue &Result)
505 : Info(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000506
John McCallefdb83e2010-05-07 21:00:08 +0000507 bool VisitStmt(Stmt *S) {
508 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000509 }
510
John McCallefdb83e2010-05-07 21:00:08 +0000511 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000512 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
513 return Visit(E->getResultExpr());
514 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000515
John McCallefdb83e2010-05-07 21:00:08 +0000516 bool VisitBinaryOperator(const BinaryOperator *E);
517 bool VisitCastExpr(CastExpr* E);
518 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman2217c872009-02-22 11:46:18 +0000519 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000520 bool VisitUnaryAddrOf(const UnaryOperator *E);
521 bool VisitObjCStringLiteral(ObjCStringLiteral *E)
522 { return Success(E); }
523 bool VisitAddrLabelExpr(AddrLabelExpr *E)
524 { return Success(E); }
525 bool VisitCallExpr(CallExpr *E);
526 bool VisitBlockExpr(BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000527 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000528 return Success(E);
529 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000530 }
John McCallefdb83e2010-05-07 21:00:08 +0000531 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
532 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000533 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
John McCallefdb83e2010-05-07 21:00:08 +0000534 bool VisitConditionalOperator(ConditionalOperator *E);
535 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000536 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallefdb83e2010-05-07 21:00:08 +0000537 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
538 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000539
540 bool VisitOpaqueValueExpr(OpaqueValueExpr *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000541 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000542};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000543} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000544
John McCallefdb83e2010-05-07 21:00:08 +0000545static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000546 assert(E->getType()->hasPointerRepresentation());
John McCallefdb83e2010-05-07 21:00:08 +0000547 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000548}
549
John McCallefdb83e2010-05-07 21:00:08 +0000550bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000551 if (E->getOpcode() != BO_Add &&
552 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000553 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000555 const Expr *PExp = E->getLHS();
556 const Expr *IExp = E->getRHS();
557 if (IExp->getType()->isPointerType())
558 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000559
John McCallefdb83e2010-05-07 21:00:08 +0000560 if (!EvaluatePointer(PExp, Result, Info))
561 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000562
John McCallefdb83e2010-05-07 21:00:08 +0000563 llvm::APSInt Offset;
564 if (!EvaluateInteger(IExp, Offset, Info))
565 return false;
566 int64_t AdditionalOffset
567 = Offset.isSigned() ? Offset.getSExtValue()
568 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000569
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000570 // Compute the new offset in the appropriate width.
571
572 QualType PointeeType =
573 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000574 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000576 // Explicitly handle GNU void* and function pointer arithmetic extensions.
577 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000578 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000579 else
John McCallefdb83e2010-05-07 21:00:08 +0000580 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000581
John McCall2de56d12010-08-25 11:45:40 +0000582 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000583 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000584 else
John McCallefdb83e2010-05-07 21:00:08 +0000585 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000586
John McCallefdb83e2010-05-07 21:00:08 +0000587 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000588}
Eli Friedman4efaa272008-11-12 09:44:48 +0000589
John McCallefdb83e2010-05-07 21:00:08 +0000590bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
591 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000592}
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000594
John McCallefdb83e2010-05-07 21:00:08 +0000595bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000596 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000597
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000598 switch (E->getCastKind()) {
599 default:
600 break;
601
John McCall2de56d12010-08-25 11:45:40 +0000602 case CK_NoOp:
603 case CK_BitCast:
John McCall2de56d12010-08-25 11:45:40 +0000604 case CK_AnyPointerToObjCPointerCast:
605 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000606 return Visit(SubExpr);
607
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000608 case CK_DerivedToBase:
609 case CK_UncheckedDerivedToBase: {
610 LValue BaseLV;
611 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
612 return false;
613
614 // Now figure out the necessary offset to add to the baseLV to get from
615 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000616 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000617
618 QualType Ty = E->getSubExpr()->getType();
619 const CXXRecordDecl *DerivedDecl =
620 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
621
622 for (CastExpr::path_const_iterator PathI = E->path_begin(),
623 PathE = E->path_end(); PathI != PathE; ++PathI) {
624 const CXXBaseSpecifier *Base = *PathI;
625
626 // FIXME: If the base is virtual, we'd need to determine the type of the
627 // most derived class and we don't support that right now.
628 if (Base->isVirtual())
629 return false;
630
631 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
632 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
633
Ken Dyck7c7f8202011-01-26 02:17:08 +0000634 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000635 DerivedDecl = BaseDecl;
636 }
637
638 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000639 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000640 return true;
641 }
642
John McCall404cd162010-11-13 01:35:44 +0000643 case CK_NullToPointer: {
644 Result.Base = 0;
645 Result.Offset = CharUnits::Zero();
646 return true;
647 }
648
John McCall2de56d12010-08-25 11:45:40 +0000649 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000650 APValue Value;
651 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000652 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000653
John McCallefdb83e2010-05-07 21:00:08 +0000654 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000655 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000656 Result.Base = 0;
657 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
658 return true;
659 } else {
660 // Cast is of an lvalue, no need to change value.
661 Result.Base = Value.getLValueBase();
662 Result.Offset = Value.getLValueOffset();
663 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000664 }
665 }
John McCall2de56d12010-08-25 11:45:40 +0000666 case CK_ArrayToPointerDecay:
667 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000668 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000669 }
670
John McCallefdb83e2010-05-07 21:00:08 +0000671 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000672}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000673
John McCallefdb83e2010-05-07 21:00:08 +0000674bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000675 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000676 Builtin::BI__builtin___CFStringMakeConstantString ||
677 E->isBuiltinCall(Info.Ctx) ==
678 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000679 return Success(E);
680 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000681}
682
John McCall56ca35d2011-02-17 10:25:35 +0000683bool PointerExprEvaluator::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
684 const APValue *value = Info.getOpaqueValue(e);
685 if (!value)
686 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
687 Result.setFrom(*value);
688 return true;
689}
690
691bool PointerExprEvaluator::
692VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
693 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
694 if (opaque.hasError()) return false;
695
696 bool cond;
697 if (!HandleConversionToBool(e->getCond(), cond, Info))
698 return false;
699
700 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
701}
702
John McCallefdb83e2010-05-07 21:00:08 +0000703bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000704 bool BoolResult;
705 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000706 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000707
708 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000709 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000710}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000711
712//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000713// Vector Evaluation
714//===----------------------------------------------------------------------===//
715
716namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000717 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000718 : public StmtVisitor<VectorExprEvaluator, APValue> {
719 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000720 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000721 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Nate Begeman59b5da62009-01-18 03:20:47 +0000723 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Nate Begeman59b5da62009-01-18 03:20:47 +0000725 APValue VisitStmt(Stmt *S) {
726 return APValue();
727 }
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Eli Friedman91110ee2009-02-23 04:23:56 +0000729 APValue VisitParenExpr(ParenExpr *E)
730 { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000731 APValue VisitGenericSelectionExpr(GenericSelectionExpr *E)
732 { return Visit(E->getResultExpr()); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000733 APValue VisitUnaryExtension(const UnaryOperator *E)
734 { return Visit(E->getSubExpr()); }
735 APValue VisitUnaryPlus(const UnaryOperator *E)
736 { return Visit(E->getSubExpr()); }
737 APValue VisitUnaryReal(const UnaryOperator *E)
738 { return Visit(E->getSubExpr()); }
739 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
740 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000741 APValue VisitCastExpr(const CastExpr* E);
742 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
743 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000744 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000745 APValue VisitChooseExpr(const ChooseExpr *E)
746 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000747 APValue VisitUnaryImag(const UnaryOperator *E);
748 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000749 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000750 // shufflevector, ExtVectorElementExpr
751 // (Note that these require implementing conversions
752 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000753 };
754} // end anonymous namespace
755
756static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
757 if (!E->getType()->isVectorType())
758 return false;
759 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
760 return !Result.isUninit();
761}
762
763APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000764 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000765 QualType EltTy = VTy->getElementType();
766 unsigned NElts = VTy->getNumElements();
767 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Nate Begeman59b5da62009-01-18 03:20:47 +0000769 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000770 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000771
Eli Friedman46a52322011-03-25 00:43:55 +0000772 switch (E->getCastKind()) {
773 case CK_VectorSplat: {
774 APValue Result = APValue();
775 if (SETy->isIntegerType()) {
776 APSInt IntResult;
777 if (!EvaluateInteger(SE, IntResult, Info))
778 return APValue();
779 Result = APValue(IntResult);
780 } else if (SETy->isRealFloatingType()) {
781 APFloat F(0.0);
782 if (!EvaluateFloat(SE, F, Info))
783 return APValue();
784 Result = APValue(F);
785 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000786 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000787 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000788
789 // Splat and create vector APValue.
790 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
791 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000792 }
Eli Friedman46a52322011-03-25 00:43:55 +0000793 case CK_BitCast: {
794 if (SETy->isVectorType())
795 return Visit(const_cast<Expr*>(SE));
Nate Begemanc0b8b192009-07-01 07:50:47 +0000796
Eli Friedman46a52322011-03-25 00:43:55 +0000797 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000798 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Eli Friedman46a52322011-03-25 00:43:55 +0000800 APSInt Init;
801 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000802 return APValue();
803
Eli Friedman46a52322011-03-25 00:43:55 +0000804 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
805 "Vectors must be composed of ints or floats");
806
807 llvm::SmallVector<APValue, 4> Elts;
808 for (unsigned i = 0; i != NElts; ++i) {
809 APSInt Tmp = Init.extOrTrunc(EltWidth);
810
811 if (EltTy->isIntegerType())
812 Elts.push_back(APValue(Tmp));
813 else
814 Elts.push_back(APValue(APFloat(Tmp)));
815
816 Init >>= EltWidth;
817 }
818 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000819 }
Eli Friedman46a52322011-03-25 00:43:55 +0000820 case CK_LValueToRValue:
821 case CK_NoOp:
822 return Visit(const_cast<Expr*>(SE));
823 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000824 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000825 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000826}
827
Mike Stump1eb44332009-09-09 15:08:12 +0000828APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000829VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
830 return this->Visit(const_cast<Expr*>(E->getInitializer()));
831}
832
Mike Stump1eb44332009-09-09 15:08:12 +0000833APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000834VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000835 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000836 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000837 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Nate Begeman59b5da62009-01-18 03:20:47 +0000839 QualType EltTy = VT->getElementType();
840 llvm::SmallVector<APValue, 4> Elements;
841
John McCalla7d6c222010-06-11 17:54:15 +0000842 // If a vector is initialized with a single element, that value
843 // becomes every element of the vector, not just the first.
844 // This is the behavior described in the IBM AltiVec documentation.
845 if (NumInits == 1) {
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000846
847 // Handle the case where the vector is initialized by a another
848 // vector (OpenCL 6.1.6).
849 if (E->getInit(0)->getType()->isVectorType())
850 return this->Visit(const_cast<Expr*>(E->getInit(0)));
851
John McCalla7d6c222010-06-11 17:54:15 +0000852 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000853 if (EltTy->isIntegerType()) {
854 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000855 if (!EvaluateInteger(E->getInit(0), sInt, Info))
856 return APValue();
857 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000858 } else {
859 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000860 if (!EvaluateFloat(E->getInit(0), f, Info))
861 return APValue();
862 InitValue = APValue(f);
863 }
864 for (unsigned i = 0; i < NumElements; i++) {
865 Elements.push_back(InitValue);
866 }
867 } else {
868 for (unsigned i = 0; i < NumElements; i++) {
869 if (EltTy->isIntegerType()) {
870 llvm::APSInt sInt(32);
871 if (i < NumInits) {
872 if (!EvaluateInteger(E->getInit(i), sInt, Info))
873 return APValue();
874 } else {
875 sInt = Info.Ctx.MakeIntValue(0, EltTy);
876 }
877 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000878 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000879 llvm::APFloat f(0.0);
880 if (i < NumInits) {
881 if (!EvaluateFloat(E->getInit(i), f, Info))
882 return APValue();
883 } else {
884 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
885 }
886 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000887 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000888 }
889 }
890 return APValue(&Elements[0], Elements.size());
891}
892
Mike Stump1eb44332009-09-09 15:08:12 +0000893APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000894VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000895 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000896 QualType EltTy = VT->getElementType();
897 APValue ZeroElement;
898 if (EltTy->isIntegerType())
899 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
900 else
901 ZeroElement =
902 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
903
904 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
905 return APValue(&Elements[0], Elements.size());
906}
907
908APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
909 bool BoolResult;
910 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
911 return APValue();
912
913 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
914
915 APValue Result;
916 if (EvaluateVector(EvalExpr, Result, Info))
917 return Result;
918 return APValue();
919}
920
Eli Friedman91110ee2009-02-23 04:23:56 +0000921APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
922 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
923 Info.EvalResult.HasSideEffects = true;
924 return GetZeroVector(E->getType());
925}
926
Nate Begeman59b5da62009-01-18 03:20:47 +0000927//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000928// Integer Evaluation
929//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000930
931namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000932class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000933 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000934 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000935 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000936public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000937 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000938 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000939
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000940 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000941 assert(E->getType()->isIntegralOrEnumerationType() &&
942 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000943 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000944 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000945 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000946 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000947 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000948 return true;
949 }
950
Daniel Dunbar131eb432009-02-19 09:06:44 +0000951 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000952 assert(E->getType()->isIntegralOrEnumerationType() &&
953 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000954 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000955 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000956 Result = APValue(APSInt(I));
957 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000958 return true;
959 }
960
961 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000962 assert(E->getType()->isIntegralOrEnumerationType() &&
963 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000964 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000965 return true;
966 }
967
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000968 bool Success(CharUnits Size, const Expr *E) {
969 return Success(Size.getQuantity(), E);
970 }
971
972
Anders Carlsson82206e22008-11-30 18:14:57 +0000973 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000974 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000975 if (Info.EvalResult.Diag == 0) {
976 Info.EvalResult.DiagLoc = L;
977 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000978 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000979 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000980 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000981 }
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Anders Carlssonc754aa62008-07-08 05:13:58 +0000983 //===--------------------------------------------------------------------===//
984 // Visitor Methods
985 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chris Lattner32fea9d2008-11-12 07:43:42 +0000987 bool VisitStmt(Stmt *) {
988 assert(0 && "This should be called on integers, stmts are not integers");
989 return false;
990 }
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner32fea9d2008-11-12 07:43:42 +0000992 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000993 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000994 }
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Chris Lattnerb542afe2008-07-11 19:10:17 +0000996 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000997 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
998 return Visit(E->getResultExpr());
999 }
Anders Carlssonc754aa62008-07-08 05:13:58 +00001000
Chris Lattner4c4867e2008-07-12 00:38:25 +00001001 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001002 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001003 }
1004 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001005 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001006 }
Eli Friedman04309752009-11-24 05:28:59 +00001007
John McCall56ca35d2011-02-17 10:25:35 +00001008 bool VisitOpaqueValueExpr(OpaqueValueExpr *e) {
1009 const APValue *value = Info.getOpaqueValue(e);
1010 if (!value) {
1011 if (e->getSourceExpr()) return Visit(e->getSourceExpr());
1012 return Error(e->getExprLoc(), diag::note_invalid_subexpr_in_ice, e);
1013 }
1014 return Success(value->getInt(), e);
1015 }
1016
Eli Friedman04309752009-11-24 05:28:59 +00001017 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1018 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1019 return CheckReferencedDecl(E, E->getDecl());
1020 }
1021 bool VisitMemberExpr(const MemberExpr *E) {
1022 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1023 // Conservatively assume a MemberExpr will have side-effects
1024 Info.EvalResult.HasSideEffects = true;
1025 return true;
1026 }
1027 return false;
1028 }
1029
Eli Friedmanc4a26382010-02-13 00:10:10 +00001030 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001031 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001032 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001033 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001034 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001035 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001036
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001037 bool VisitCastExpr(CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001038 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001039
Anders Carlsson3068d112008-11-16 19:01:22 +00001040 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001041 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001042 }
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Anders Carlsson3f704562008-12-21 22:39:40 +00001044 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001045 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001046 }
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Douglas Gregored8abf12010-07-08 06:14:04 +00001048 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001049 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001050 }
1051
Eli Friedman664a1042009-02-27 04:45:43 +00001052 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1053 return Success(0, E);
1054 }
1055
Sebastian Redl64b45f72009-01-05 20:52:13 +00001056 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001057 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001058 }
1059
Francois Pichet6ad6f282010-12-07 00:08:36 +00001060 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1061 return Success(E->getValue(), E);
1062 }
1063
John Wiegley55262202011-04-25 06:54:41 +00001064 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1065 return Success(E->getValue(), E);
1066 }
1067
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001068 bool VisitChooseExpr(const ChooseExpr *E) {
1069 return Visit(E->getChosenSubExpr(Info.Ctx));
1070 }
1071
Eli Friedman722c7172009-02-28 03:59:05 +00001072 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001073 bool VisitUnaryImag(const UnaryOperator *E);
1074
Sebastian Redl295995c2010-09-10 20:55:47 +00001075 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001076 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1077
Chris Lattnerfcee0012008-07-11 21:24:13 +00001078private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001079 CharUnits GetAlignOfExpr(const Expr *E);
1080 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001081 static QualType GetObjectType(const Expr *E);
1082 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001083 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001084};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001085} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001086
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001087static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001088 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001089 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1090}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001091
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001092static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001093 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001094
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001095 APValue Val;
1096 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1097 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001098 Result = Val.getInt();
1099 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001100}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001101
Eli Friedman04309752009-11-24 05:28:59 +00001102bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001103 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +00001104 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1105 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001106
1107 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001108 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001109 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1110 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001111
1112 if (isa<ParmVarDecl>(D))
1113 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1114
Eli Friedman04309752009-11-24 05:28:59 +00001115 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001116 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001117 if (APValue *V = VD->getEvaluatedValue()) {
1118 if (V->isInt())
1119 return Success(V->getInt(), E);
1120 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1121 }
1122
1123 if (VD->isEvaluatingValue())
1124 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1125
1126 VD->setEvaluatingValue();
1127
Eli Friedmana7dedf72010-09-06 00:10:32 +00001128 Expr::EvalResult EResult;
1129 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1130 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001131 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001132 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001133 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001134 return true;
1135 }
1136
Eli Friedmanc0131182009-12-03 20:31:57 +00001137 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001138 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001139 }
1140 }
1141
Chris Lattner4c4867e2008-07-12 00:38:25 +00001142 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001143 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001144}
1145
Chris Lattnera4d55d82008-10-06 06:40:35 +00001146/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1147/// as GCC.
1148static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1149 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001150 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001151 enum gcc_type_class {
1152 no_type_class = -1,
1153 void_type_class, integer_type_class, char_type_class,
1154 enumeral_type_class, boolean_type_class,
1155 pointer_type_class, reference_type_class, offset_type_class,
1156 real_type_class, complex_type_class,
1157 function_type_class, method_type_class,
1158 record_type_class, union_type_class,
1159 array_type_class, string_type_class,
1160 lang_type_class
1161 };
Mike Stump1eb44332009-09-09 15:08:12 +00001162
1163 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001164 // ideal, however it is what gcc does.
1165 if (E->getNumArgs() == 0)
1166 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Chris Lattnera4d55d82008-10-06 06:40:35 +00001168 QualType ArgTy = E->getArg(0)->getType();
1169 if (ArgTy->isVoidType())
1170 return void_type_class;
1171 else if (ArgTy->isEnumeralType())
1172 return enumeral_type_class;
1173 else if (ArgTy->isBooleanType())
1174 return boolean_type_class;
1175 else if (ArgTy->isCharType())
1176 return string_type_class; // gcc doesn't appear to use char_type_class
1177 else if (ArgTy->isIntegerType())
1178 return integer_type_class;
1179 else if (ArgTy->isPointerType())
1180 return pointer_type_class;
1181 else if (ArgTy->isReferenceType())
1182 return reference_type_class;
1183 else if (ArgTy->isRealType())
1184 return real_type_class;
1185 else if (ArgTy->isComplexType())
1186 return complex_type_class;
1187 else if (ArgTy->isFunctionType())
1188 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001189 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001190 return record_type_class;
1191 else if (ArgTy->isUnionType())
1192 return union_type_class;
1193 else if (ArgTy->isArrayType())
1194 return array_type_class;
1195 else if (ArgTy->isUnionType())
1196 return union_type_class;
1197 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1198 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1199 return -1;
1200}
1201
John McCall42c8f872010-05-10 23:27:23 +00001202/// Retrieves the "underlying object type" of the given expression,
1203/// as used by __builtin_object_size.
1204QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1205 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1206 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1207 return VD->getType();
1208 } else if (isa<CompoundLiteralExpr>(E)) {
1209 return E->getType();
1210 }
1211
1212 return QualType();
1213}
1214
1215bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1216 // TODO: Perhaps we should let LLVM lower this?
1217 LValue Base;
1218 if (!EvaluatePointer(E->getArg(0), Base, Info))
1219 return false;
1220
1221 // If we can prove the base is null, lower to zero now.
1222 const Expr *LVBase = Base.getLValueBase();
1223 if (!LVBase) return Success(0, E);
1224
1225 QualType T = GetObjectType(LVBase);
1226 if (T.isNull() ||
1227 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001228 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001229 T->isVariablyModifiedType() ||
1230 T->isDependentType())
1231 return false;
1232
1233 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1234 CharUnits Offset = Base.getLValueOffset();
1235
1236 if (!Offset.isNegative() && Offset <= Size)
1237 Size -= Offset;
1238 else
1239 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001240 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001241}
1242
Eli Friedmanc4a26382010-02-13 00:10:10 +00001243bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001244 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001245 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001246 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001247
1248 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001249 if (TryEvaluateBuiltinObjectSize(E))
1250 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001251
Eric Christopherb2aaf512010-01-19 22:58:35 +00001252 // If evaluating the argument has side-effects we can't determine
1253 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001254 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001255 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001256 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001257 return Success(0, E);
1258 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001259
Mike Stump64eda9e2009-10-26 18:35:08 +00001260 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1261 }
1262
Chris Lattner019f4e82008-10-06 05:28:25 +00001263 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001264 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001266 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001267 // __builtin_constant_p always has one operand: it returns true if that
1268 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001269 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001270
1271 case Builtin::BI__builtin_eh_return_data_regno: {
1272 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1273 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1274 return Success(Operand, E);
1275 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001276
1277 case Builtin::BI__builtin_expect:
1278 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001279
1280 case Builtin::BIstrlen:
1281 case Builtin::BI__builtin_strlen:
1282 // As an extension, we support strlen() and __builtin_strlen() as constant
1283 // expressions when the argument is a string literal.
1284 if (StringLiteral *S
1285 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1286 // The string literal may have embedded null characters. Find the first
1287 // one and truncate there.
1288 llvm::StringRef Str = S->getString();
1289 llvm::StringRef::size_type Pos = Str.find(0);
1290 if (Pos != llvm::StringRef::npos)
1291 Str = Str.substr(0, Pos);
1292
1293 return Success(Str.size(), E);
1294 }
1295
1296 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001297 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001298}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001299
Chris Lattnerb542afe2008-07-11 19:10:17 +00001300bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001301 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001302 if (!Visit(E->getRHS()))
1303 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001304
Eli Friedman33ef1452009-02-26 10:19:36 +00001305 // If we can't evaluate the LHS, it might have side effects;
1306 // conservatively mark it.
1307 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1308 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001309
Anders Carlsson027f62e2008-12-01 02:07:06 +00001310 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001311 }
1312
1313 if (E->isLogicalOp()) {
1314 // These need to be handled specially because the operands aren't
1315 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001316 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001318 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001319 // We were able to evaluate the LHS, see if we can get away with not
1320 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001321 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001322 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001323
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001324 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001325 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001326 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001327 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001328 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001329 }
1330 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001331 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001332 // We can't evaluate the LHS; however, sometimes the result
1333 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001334 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1335 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001336 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001337 // must have had side effects.
1338 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001339
1340 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001341 }
1342 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001343 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001344
Eli Friedmana6afa762008-11-13 06:09:17 +00001345 return false;
1346 }
1347
Anders Carlsson286f85e2008-11-16 07:17:21 +00001348 QualType LHSTy = E->getLHS()->getType();
1349 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001350
1351 if (LHSTy->isAnyComplexType()) {
1352 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001353 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001354
1355 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1356 return false;
1357
1358 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1359 return false;
1360
1361 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001362 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001363 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001364 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001365 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1366
John McCall2de56d12010-08-25 11:45:40 +00001367 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001368 return Success((CR_r == APFloat::cmpEqual &&
1369 CR_i == APFloat::cmpEqual), E);
1370 else {
John McCall2de56d12010-08-25 11:45:40 +00001371 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001372 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001373 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001374 CR_r == APFloat::cmpLessThan ||
1375 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001376 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001377 CR_i == APFloat::cmpLessThan ||
1378 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001379 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001380 } else {
John McCall2de56d12010-08-25 11:45:40 +00001381 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001382 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1383 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1384 else {
John McCall2de56d12010-08-25 11:45:40 +00001385 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001386 "Invalid compex comparison.");
1387 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1388 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1389 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001390 }
1391 }
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Anders Carlsson286f85e2008-11-16 07:17:21 +00001393 if (LHSTy->isRealFloatingType() &&
1394 RHSTy->isRealFloatingType()) {
1395 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Anders Carlsson286f85e2008-11-16 07:17:21 +00001397 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1398 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Anders Carlsson286f85e2008-11-16 07:17:21 +00001400 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1401 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Anders Carlsson286f85e2008-11-16 07:17:21 +00001403 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001404
Anders Carlsson286f85e2008-11-16 07:17:21 +00001405 switch (E->getOpcode()) {
1406 default:
1407 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001408 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001409 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001410 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001411 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001412 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001413 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001414 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001415 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001416 E);
John McCall2de56d12010-08-25 11:45:40 +00001417 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001418 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001419 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001420 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001421 || CR == APFloat::cmpLessThan
1422 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001423 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001426 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001427 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001428 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001429 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1430 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001431
John McCallefdb83e2010-05-07 21:00:08 +00001432 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001433 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1434 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001435
Eli Friedman5bc86102009-06-14 02:17:33 +00001436 // Reject any bases from the normal codepath; we special-case comparisons
1437 // to null.
1438 if (LHSValue.getLValueBase()) {
1439 if (!E->isEqualityOp())
1440 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001441 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001442 return false;
1443 bool bres;
1444 if (!EvalPointerValueAsBool(LHSValue, bres))
1445 return false;
John McCall2de56d12010-08-25 11:45:40 +00001446 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001447 } else if (RHSValue.getLValueBase()) {
1448 if (!E->isEqualityOp())
1449 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001450 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001451 return false;
1452 bool bres;
1453 if (!EvalPointerValueAsBool(RHSValue, bres))
1454 return false;
John McCall2de56d12010-08-25 11:45:40 +00001455 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001456 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001457
John McCall2de56d12010-08-25 11:45:40 +00001458 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001459 QualType Type = E->getLHS()->getType();
1460 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001461
Ken Dycka7305832010-01-15 12:37:54 +00001462 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001463 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001464 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001465
Ken Dycka7305832010-01-15 12:37:54 +00001466 CharUnits Diff = LHSValue.getLValueOffset() -
1467 RHSValue.getLValueOffset();
1468 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001469 }
1470 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001471 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001472 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001473 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001474 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1475 }
1476 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001477 }
1478 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001479 if (!LHSTy->isIntegralOrEnumerationType() ||
1480 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001481 // We can't continue from here for non-integral types, and they
1482 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001483 return false;
1484 }
1485
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001486 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001487 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001488 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001489
Eli Friedman42edd0d2009-03-24 01:14:50 +00001490 APValue RHSVal;
1491 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001492 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001493
1494 // Handle cases like (unsigned long)&a + 4.
1495 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001496 CharUnits Offset = Result.getLValueOffset();
1497 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1498 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001499 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001500 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001501 else
Ken Dycka7305832010-01-15 12:37:54 +00001502 Offset -= AdditionalOffset;
1503 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001504 return true;
1505 }
1506
1507 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001508 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001509 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001510 CharUnits Offset = RHSVal.getLValueOffset();
1511 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1512 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001513 return true;
1514 }
1515
1516 // All the following cases expect both operands to be an integer
1517 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001518 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001519
Eli Friedman42edd0d2009-03-24 01:14:50 +00001520 APSInt& RHS = RHSVal.getInt();
1521
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001522 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001523 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001524 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001525 case BO_Mul: return Success(Result.getInt() * RHS, E);
1526 case BO_Add: return Success(Result.getInt() + RHS, E);
1527 case BO_Sub: return Success(Result.getInt() - RHS, E);
1528 case BO_And: return Success(Result.getInt() & RHS, E);
1529 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1530 case BO_Or: return Success(Result.getInt() | RHS, E);
1531 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001532 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001533 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001534 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001535 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001536 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001537 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001538 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001539 case BO_Shl: {
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_right;
1544 }
1545
1546 shift_left:
1547 unsigned SA
1548 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001549 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001550 }
John McCall2de56d12010-08-25 11:45:40 +00001551 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001552 // During constant-folding, a negative shift is an opposite shift.
1553 if (RHS.isSigned() && RHS.isNegative()) {
1554 RHS = -RHS;
1555 goto shift_left;
1556 }
1557
1558 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001559 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001560 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1561 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
John McCall2de56d12010-08-25 11:45:40 +00001564 case BO_LT: return Success(Result.getInt() < RHS, E);
1565 case BO_GT: return Success(Result.getInt() > RHS, E);
1566 case BO_LE: return Success(Result.getInt() <= RHS, E);
1567 case BO_GE: return Success(Result.getInt() >= RHS, E);
1568 case BO_EQ: return Success(Result.getInt() == RHS, E);
1569 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001570 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001571}
1572
John McCall56ca35d2011-02-17 10:25:35 +00001573bool IntExprEvaluator::
1574VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
1575 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
1576 if (opaque.hasError()) return false;
1577
1578 bool cond;
1579 if (!HandleConversionToBool(e->getCond(), cond, Info))
1580 return false;
1581
1582 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
1583}
1584
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001585bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001586 bool Cond;
1587 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001588 return false;
1589
Nuno Lopesa25bd552008-11-16 22:06:39 +00001590 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001591}
1592
Ken Dyck8b752f12010-01-27 17:10:57 +00001593CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001594 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1595 // the result is the size of the referenced type."
1596 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1597 // result shall be the alignment of the referenced type."
1598 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1599 T = Ref->getPointeeType();
1600
Eli Friedman2be58612009-05-30 21:09:44 +00001601 // __alignof is defined to return the preferred alignment.
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001602 return Info.Ctx.toCharUnitsFromBits(
1603 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001604}
1605
Ken Dyck8b752f12010-01-27 17:10:57 +00001606CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001607 E = E->IgnoreParens();
1608
1609 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001610 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001611 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001612 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1613 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001614
Chris Lattneraf707ab2009-01-24 21:53:27 +00001615 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001616 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1617 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001618
Chris Lattnere9feb472009-01-24 21:09:06 +00001619 return GetAlignOfType(E->getType());
1620}
1621
1622
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001623/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1624/// a result as the expression's type.
1625bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1626 const UnaryExprOrTypeTraitExpr *E) {
1627 switch(E->getKind()) {
1628 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001629 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001630 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001631 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001632 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001633 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001634
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001635 case UETT_VecStep: {
1636 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001637
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001638 if (Ty->isVectorType()) {
1639 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001640
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001641 // The vec_step built-in functions that take a 3-component
1642 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1643 if (n == 3)
1644 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001645
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001646 return Success(n, E);
1647 } else
1648 return Success(1, E);
1649 }
1650
1651 case UETT_SizeOf: {
1652 QualType SrcTy = E->getTypeOfArgument();
1653 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1654 // the result is the size of the referenced type."
1655 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1656 // result shall be the alignment of the referenced type."
1657 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1658 SrcTy = Ref->getPointeeType();
1659
1660 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1661 // extension.
1662 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1663 return Success(1, E);
1664
1665 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1666 if (!SrcTy->isConstantSizeType())
1667 return false;
1668
1669 // Get information about the size.
1670 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1671 }
1672 }
1673
1674 llvm_unreachable("unknown expr/type trait");
1675 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001676}
1677
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001678bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1679 CharUnits Result;
1680 unsigned n = E->getNumComponents();
1681 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1682 if (n == 0)
1683 return false;
1684 QualType CurrentType = E->getTypeSourceInfo()->getType();
1685 for (unsigned i = 0; i != n; ++i) {
1686 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1687 switch (ON.getKind()) {
1688 case OffsetOfExpr::OffsetOfNode::Array: {
1689 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1690 APSInt IdxResult;
1691 if (!EvaluateInteger(Idx, IdxResult, Info))
1692 return false;
1693 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1694 if (!AT)
1695 return false;
1696 CurrentType = AT->getElementType();
1697 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1698 Result += IdxResult.getSExtValue() * ElementSize;
1699 break;
1700 }
1701
1702 case OffsetOfExpr::OffsetOfNode::Field: {
1703 FieldDecl *MemberDecl = ON.getField();
1704 const RecordType *RT = CurrentType->getAs<RecordType>();
1705 if (!RT)
1706 return false;
1707 RecordDecl *RD = RT->getDecl();
1708 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001709 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001710 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001711 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001712 CurrentType = MemberDecl->getType().getNonReferenceType();
1713 break;
1714 }
1715
1716 case OffsetOfExpr::OffsetOfNode::Identifier:
1717 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001718 return false;
1719
1720 case OffsetOfExpr::OffsetOfNode::Base: {
1721 CXXBaseSpecifier *BaseSpec = ON.getBase();
1722 if (BaseSpec->isVirtual())
1723 return false;
1724
1725 // Find the layout of the class whose base we are looking into.
1726 const RecordType *RT = CurrentType->getAs<RecordType>();
1727 if (!RT)
1728 return false;
1729 RecordDecl *RD = RT->getDecl();
1730 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1731
1732 // Find the base class itself.
1733 CurrentType = BaseSpec->getType();
1734 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1735 if (!BaseRT)
1736 return false;
1737
1738 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001739 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001740 break;
1741 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001742 }
1743 }
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001744 return Success(Result, E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001745}
1746
Chris Lattnerb542afe2008-07-11 19:10:17 +00001747bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001748 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001749 // LNot's operand isn't necessarily an integer, so we handle it specially.
1750 bool bres;
1751 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1752 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001753 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001754 }
1755
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001756 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001757 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001758 return false;
1759
Chris Lattner87eae5e2008-07-11 22:52:41 +00001760 // Get the operand value into 'Result'.
1761 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001762 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001763
Chris Lattner75a48812008-07-11 22:15:16 +00001764 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001765 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001766 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1767 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001768 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001769 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001770 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1771 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001772 return true;
John McCall2de56d12010-08-25 11:45:40 +00001773 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001774 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001775 return true;
John McCall2de56d12010-08-25 11:45:40 +00001776 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001777 if (!Result.isInt()) return false;
1778 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001779 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001780 if (!Result.isInt()) return false;
1781 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001782 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001783}
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Chris Lattner732b2232008-07-12 01:15:53 +00001785/// HandleCast - This is used to evaluate implicit or explicit casts where the
1786/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001787bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001788 Expr *SubExpr = E->getSubExpr();
1789 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001790 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001791
Eli Friedman46a52322011-03-25 00:43:55 +00001792 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001793 case CK_BaseToDerived:
1794 case CK_DerivedToBase:
1795 case CK_UncheckedDerivedToBase:
1796 case CK_Dynamic:
1797 case CK_ToUnion:
1798 case CK_ArrayToPointerDecay:
1799 case CK_FunctionToPointerDecay:
1800 case CK_NullToPointer:
1801 case CK_NullToMemberPointer:
1802 case CK_BaseToDerivedMemberPointer:
1803 case CK_DerivedToBaseMemberPointer:
1804 case CK_ConstructorConversion:
1805 case CK_IntegralToPointer:
1806 case CK_ToVoid:
1807 case CK_VectorSplat:
1808 case CK_IntegralToFloating:
1809 case CK_FloatingCast:
1810 case CK_AnyPointerToObjCPointerCast:
1811 case CK_AnyPointerToBlockPointerCast:
1812 case CK_ObjCObjectLValueCast:
1813 case CK_FloatingRealToComplex:
1814 case CK_FloatingComplexToReal:
1815 case CK_FloatingComplexCast:
1816 case CK_FloatingComplexToIntegralComplex:
1817 case CK_IntegralRealToComplex:
1818 case CK_IntegralComplexCast:
1819 case CK_IntegralComplexToFloatingComplex:
1820 llvm_unreachable("invalid cast kind for integral value");
1821
Eli Friedmane50c2972011-03-25 19:07:11 +00001822 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001823 case CK_Dependent:
1824 case CK_GetObjCProperty:
1825 case CK_LValueBitCast:
1826 case CK_UserDefinedConversion:
1827 return false;
1828
1829 case CK_LValueToRValue:
1830 case CK_NoOp:
1831 return Visit(E->getSubExpr());
1832
1833 case CK_MemberPointerToBoolean:
1834 case CK_PointerToBoolean:
1835 case CK_IntegralToBoolean:
1836 case CK_FloatingToBoolean:
1837 case CK_FloatingComplexToBoolean:
1838 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001839 bool BoolResult;
1840 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1841 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001842 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001843 }
1844
Eli Friedman46a52322011-03-25 00:43:55 +00001845 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001846 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001847 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001848
Eli Friedmanbe265702009-02-20 01:15:07 +00001849 if (!Result.isInt()) {
1850 // Only allow casts of lvalues if they are lossless.
1851 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1852 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001853
Daniel Dunbardd211642009-02-19 22:24:01 +00001854 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001855 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001856 }
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Eli Friedman46a52322011-03-25 00:43:55 +00001858 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001859 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001860 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001861 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001862
Daniel Dunbardd211642009-02-19 22:24:01 +00001863 if (LV.getLValueBase()) {
1864 // Only allow based lvalue casts if they are lossless.
1865 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1866 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001867
John McCallefdb83e2010-05-07 21:00:08 +00001868 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001869 return true;
1870 }
1871
Ken Dycka7305832010-01-15 12:37:54 +00001872 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1873 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001874 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001875 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001876
Eli Friedman46a52322011-03-25 00:43:55 +00001877 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001878 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001879 if (!EvaluateComplex(SubExpr, C, Info))
1880 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001881 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001882 }
Eli Friedman2217c872009-02-22 11:46:18 +00001883
Eli Friedman46a52322011-03-25 00:43:55 +00001884 case CK_FloatingToIntegral: {
1885 APFloat F(0.0);
1886 if (!EvaluateFloat(SubExpr, F, Info))
1887 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001888
Eli Friedman46a52322011-03-25 00:43:55 +00001889 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1890 }
1891 }
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Eli Friedman46a52322011-03-25 00:43:55 +00001893 llvm_unreachable("unknown cast resulting in integral value");
1894 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001895}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001896
Eli Friedman722c7172009-02-28 03:59:05 +00001897bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1898 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001899 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001900 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1901 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1902 return Success(LV.getComplexIntReal(), E);
1903 }
1904
1905 return Visit(E->getSubExpr());
1906}
1907
Eli Friedman664a1042009-02-27 04:45:43 +00001908bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001909 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001910 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001911 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1912 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1913 return Success(LV.getComplexIntImag(), E);
1914 }
1915
Eli Friedman664a1042009-02-27 04:45:43 +00001916 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1917 Info.EvalResult.HasSideEffects = true;
1918 return Success(0, E);
1919}
1920
Douglas Gregoree8aff02011-01-04 17:33:58 +00001921bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1922 return Success(E->getPackLength(), E);
1923}
1924
Sebastian Redl295995c2010-09-10 20:55:47 +00001925bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1926 return Success(E->getValue(), E);
1927}
1928
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001929//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001930// Float Evaluation
1931//===----------------------------------------------------------------------===//
1932
1933namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001934class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001935 : public StmtVisitor<FloatExprEvaluator, bool> {
1936 EvalInfo &Info;
1937 APFloat &Result;
1938public:
1939 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1940 : Info(info), Result(result) {}
1941
1942 bool VisitStmt(Stmt *S) {
1943 return false;
1944 }
1945
1946 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +00001947 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
1948 return Visit(E->getResultExpr());
1949 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001950 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001951
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001952 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001953 bool VisitBinaryOperator(const BinaryOperator *E);
1954 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001955 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001956 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001957 bool VisitConditionalOperator(ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001958 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001959
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001960 bool VisitChooseExpr(const ChooseExpr *E)
1961 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1962 bool VisitUnaryExtension(const UnaryOperator *E)
1963 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001964 bool VisitUnaryReal(const UnaryOperator *E);
1965 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001966
John McCall189d6ef2010-10-09 01:34:31 +00001967 bool VisitDeclRefExpr(const DeclRefExpr *E);
1968
John McCall56ca35d2011-02-17 10:25:35 +00001969 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
1970 const APValue *value = Info.getOpaqueValue(e);
1971 if (!value)
1972 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
1973 Result = value->getFloat();
1974 return true;
1975 }
1976
John McCallabd3a852010-05-07 22:08:54 +00001977 // FIXME: Missing: array subscript of vector, member of vector,
1978 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001979};
1980} // end anonymous namespace
1981
1982static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001983 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001984 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1985}
1986
Jay Foad4ba2a172011-01-12 09:06:06 +00001987static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001988 QualType ResultTy,
1989 const Expr *Arg,
1990 bool SNaN,
1991 llvm::APFloat &Result) {
1992 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1993 if (!S) return false;
1994
1995 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1996
1997 llvm::APInt fill;
1998
1999 // Treat empty strings as if they were zero.
2000 if (S->getString().empty())
2001 fill = llvm::APInt(32, 0);
2002 else if (S->getString().getAsInteger(0, fill))
2003 return false;
2004
2005 if (SNaN)
2006 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2007 else
2008 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2009 return true;
2010}
2011
Chris Lattner019f4e82008-10-06 05:28:25 +00002012bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00002013 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00002014 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00002015 case Builtin::BI__builtin_huge_val:
2016 case Builtin::BI__builtin_huge_valf:
2017 case Builtin::BI__builtin_huge_vall:
2018 case Builtin::BI__builtin_inf:
2019 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002020 case Builtin::BI__builtin_infl: {
2021 const llvm::fltSemantics &Sem =
2022 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002023 Result = llvm::APFloat::getInf(Sem);
2024 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002025 }
Mike Stump1eb44332009-09-09 15:08:12 +00002026
John McCalldb7b72a2010-02-28 13:00:19 +00002027 case Builtin::BI__builtin_nans:
2028 case Builtin::BI__builtin_nansf:
2029 case Builtin::BI__builtin_nansl:
2030 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2031 true, Result);
2032
Chris Lattner9e621712008-10-06 06:31:58 +00002033 case Builtin::BI__builtin_nan:
2034 case Builtin::BI__builtin_nanf:
2035 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002036 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002037 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002038 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2039 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002040
2041 case Builtin::BI__builtin_fabs:
2042 case Builtin::BI__builtin_fabsf:
2043 case Builtin::BI__builtin_fabsl:
2044 if (!EvaluateFloat(E->getArg(0), Result, Info))
2045 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002047 if (Result.isNegative())
2048 Result.changeSign();
2049 return true;
2050
Mike Stump1eb44332009-09-09 15:08:12 +00002051 case Builtin::BI__builtin_copysign:
2052 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002053 case Builtin::BI__builtin_copysignl: {
2054 APFloat RHS(0.);
2055 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2056 !EvaluateFloat(E->getArg(1), RHS, Info))
2057 return false;
2058 Result.copySign(RHS);
2059 return true;
2060 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002061 }
2062}
2063
John McCall189d6ef2010-10-09 01:34:31 +00002064bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2065 const Decl *D = E->getDecl();
2066 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2067 const VarDecl *VD = cast<VarDecl>(D);
2068
2069 // Require the qualifiers to be const and not volatile.
2070 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2071 if (!T.isConstQualified() || T.isVolatileQualified())
2072 return false;
2073
2074 const Expr *Init = VD->getAnyInitializer();
2075 if (!Init) return false;
2076
2077 if (APValue *V = VD->getEvaluatedValue()) {
2078 if (V->isFloat()) {
2079 Result = V->getFloat();
2080 return true;
2081 }
2082 return false;
2083 }
2084
2085 if (VD->isEvaluatingValue())
2086 return false;
2087
2088 VD->setEvaluatingValue();
2089
2090 Expr::EvalResult InitResult;
2091 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2092 InitResult.Val.isFloat()) {
2093 // Cache the evaluated value in the variable declaration.
2094 Result = InitResult.Val.getFloat();
2095 VD->setEvaluatedValue(InitResult.Val);
2096 return true;
2097 }
2098
2099 VD->setEvaluatedValue(APValue());
2100 return false;
2101}
2102
John McCallabd3a852010-05-07 22:08:54 +00002103bool FloatExprEvaluator::VisitUnaryReal(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.FloatReal;
2109 return true;
2110 }
2111
2112 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002113}
2114
2115bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002116 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2117 ComplexValue CV;
2118 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2119 return false;
2120 Result = CV.FloatImag;
2121 return true;
2122 }
2123
2124 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2125 Info.EvalResult.HasSideEffects = true;
2126 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2127 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002128 return true;
2129}
2130
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002131bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002132 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002133 return false;
2134
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002135 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2136 return false;
2137
2138 switch (E->getOpcode()) {
2139 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002140 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002141 return true;
John McCall2de56d12010-08-25 11:45:40 +00002142 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002143 Result.changeSign();
2144 return true;
2145 }
2146}
Chris Lattner019f4e82008-10-06 05:28:25 +00002147
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002148bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002149 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002150 if (!EvaluateFloat(E->getRHS(), Result, Info))
2151 return false;
2152
2153 // If we can't evaluate the LHS, it might have side effects;
2154 // conservatively mark it.
2155 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2156 Info.EvalResult.HasSideEffects = true;
2157
2158 return true;
2159 }
2160
Anders Carlsson96e93662010-10-31 01:21:47 +00002161 // We can't evaluate pointer-to-member operations.
2162 if (E->isPtrMemOp())
2163 return false;
2164
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002165 // FIXME: Diagnostics? I really don't understand how the warnings
2166 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002167 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002168 if (!EvaluateFloat(E->getLHS(), Result, Info))
2169 return false;
2170 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2171 return false;
2172
2173 switch (E->getOpcode()) {
2174 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002175 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002176 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2177 return true;
John McCall2de56d12010-08-25 11:45:40 +00002178 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002179 Result.add(RHS, APFloat::rmNearestTiesToEven);
2180 return true;
John McCall2de56d12010-08-25 11:45:40 +00002181 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002182 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2183 return true;
John McCall2de56d12010-08-25 11:45:40 +00002184 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002185 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2186 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002187 }
2188}
2189
2190bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2191 Result = E->getValue();
2192 return true;
2193}
2194
Eli Friedman4efaa272008-11-12 09:44:48 +00002195bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2196 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Eli Friedman2a523ee2011-03-25 00:54:52 +00002198 switch (E->getCastKind()) {
2199 default:
2200 return false;
2201
2202 case CK_LValueToRValue:
2203 case CK_NoOp:
2204 return Visit(SubExpr);
2205
2206 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002207 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002208 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002209 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002210 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002211 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002212 return true;
2213 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002214
2215 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002216 if (!Visit(SubExpr))
2217 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002218 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2219 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002220 return true;
2221 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002222
Eli Friedman2a523ee2011-03-25 00:54:52 +00002223 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002224 ComplexValue V;
2225 if (!EvaluateComplex(SubExpr, V, Info))
2226 return false;
2227 Result = V.getComplexFloatReal();
2228 return true;
2229 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002230 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002231
2232 return false;
2233}
2234
Douglas Gregored8abf12010-07-08 06:14:04 +00002235bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002236 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2237 return true;
2238}
2239
John McCall56ca35d2011-02-17 10:25:35 +00002240bool FloatExprEvaluator::
2241VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
2242 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2243 if (opaque.hasError()) return false;
2244
2245 bool cond;
2246 if (!HandleConversionToBool(e->getCond(), cond, Info))
2247 return false;
2248
2249 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2250}
2251
Eli Friedman67f85fc2009-12-04 02:12:53 +00002252bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2253 bool Cond;
2254 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2255 return false;
2256
2257 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2258}
2259
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002260//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002261// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002262//===----------------------------------------------------------------------===//
2263
2264namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002265class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00002266 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002267 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00002268 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002270public:
John McCallf4cf1a12010-05-07 17:22:02 +00002271 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2272 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002274 //===--------------------------------------------------------------------===//
2275 // Visitor Methods
2276 //===--------------------------------------------------------------------===//
2277
John McCallf4cf1a12010-05-07 17:22:02 +00002278 bool VisitStmt(Stmt *S) {
2279 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002280 }
Mike Stump1eb44332009-09-09 15:08:12 +00002281
John McCallf4cf1a12010-05-07 17:22:02 +00002282 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +00002283 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
2284 return Visit(E->getResultExpr());
2285 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002286
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002287 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002288
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002289 bool VisitCastExpr(CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002290
John McCallf4cf1a12010-05-07 17:22:02 +00002291 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002292 bool VisitUnaryOperator(const UnaryOperator *E);
2293 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00002294 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
John McCallf4cf1a12010-05-07 17:22:02 +00002295 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002296 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002297 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002298 { return Visit(E->getSubExpr()); }
John McCall56ca35d2011-02-17 10:25:35 +00002299 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
2300 const APValue *value = Info.getOpaqueValue(e);
2301 if (!value)
2302 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
2303 Result.setFrom(*value);
2304 return true;
2305 }
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002306 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002307};
2308} // end anonymous namespace
2309
John McCallf4cf1a12010-05-07 17:22:02 +00002310static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2311 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002312 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002313 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002314}
2315
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002316bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2317 Expr* SubExpr = E->getSubExpr();
2318
2319 if (SubExpr->getType()->isRealFloatingType()) {
2320 Result.makeComplexFloat();
2321 APFloat &Imag = Result.FloatImag;
2322 if (!EvaluateFloat(SubExpr, Imag, Info))
2323 return false;
2324
2325 Result.FloatReal = APFloat(Imag.getSemantics());
2326 return true;
2327 } else {
2328 assert(SubExpr->getType()->isIntegerType() &&
2329 "Unexpected imaginary literal.");
2330
2331 Result.makeComplexInt();
2332 APSInt &Imag = Result.IntImag;
2333 if (!EvaluateInteger(SubExpr, Imag, Info))
2334 return false;
2335
2336 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2337 return true;
2338 }
2339}
2340
2341bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002342
John McCall8786da72010-12-14 17:51:41 +00002343 switch (E->getCastKind()) {
2344 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002345 case CK_BaseToDerived:
2346 case CK_DerivedToBase:
2347 case CK_UncheckedDerivedToBase:
2348 case CK_Dynamic:
2349 case CK_ToUnion:
2350 case CK_ArrayToPointerDecay:
2351 case CK_FunctionToPointerDecay:
2352 case CK_NullToPointer:
2353 case CK_NullToMemberPointer:
2354 case CK_BaseToDerivedMemberPointer:
2355 case CK_DerivedToBaseMemberPointer:
2356 case CK_MemberPointerToBoolean:
2357 case CK_ConstructorConversion:
2358 case CK_IntegralToPointer:
2359 case CK_PointerToIntegral:
2360 case CK_PointerToBoolean:
2361 case CK_ToVoid:
2362 case CK_VectorSplat:
2363 case CK_IntegralCast:
2364 case CK_IntegralToBoolean:
2365 case CK_IntegralToFloating:
2366 case CK_FloatingToIntegral:
2367 case CK_FloatingToBoolean:
2368 case CK_FloatingCast:
2369 case CK_AnyPointerToObjCPointerCast:
2370 case CK_AnyPointerToBlockPointerCast:
2371 case CK_ObjCObjectLValueCast:
2372 case CK_FloatingComplexToReal:
2373 case CK_FloatingComplexToBoolean:
2374 case CK_IntegralComplexToReal:
2375 case CK_IntegralComplexToBoolean:
2376 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002377
John McCall8786da72010-12-14 17:51:41 +00002378 case CK_LValueToRValue:
2379 case CK_NoOp:
2380 return Visit(E->getSubExpr());
2381
2382 case CK_Dependent:
2383 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002384 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002385 case CK_UserDefinedConversion:
2386 return false;
2387
2388 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002389 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002390 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002391 return false;
2392
John McCall8786da72010-12-14 17:51:41 +00002393 Result.makeComplexFloat();
2394 Result.FloatImag = APFloat(Real.getSemantics());
2395 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002396 }
2397
John McCall8786da72010-12-14 17:51:41 +00002398 case CK_FloatingComplexCast: {
2399 if (!Visit(E->getSubExpr()))
2400 return false;
2401
2402 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2403 QualType From
2404 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2405
2406 Result.FloatReal
2407 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2408 Result.FloatImag
2409 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2410 return true;
2411 }
2412
2413 case CK_FloatingComplexToIntegralComplex: {
2414 if (!Visit(E->getSubExpr()))
2415 return false;
2416
2417 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2418 QualType From
2419 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2420 Result.makeComplexInt();
2421 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2422 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2423 return true;
2424 }
2425
2426 case CK_IntegralRealToComplex: {
2427 APSInt &Real = Result.IntReal;
2428 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2429 return false;
2430
2431 Result.makeComplexInt();
2432 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2433 return true;
2434 }
2435
2436 case CK_IntegralComplexCast: {
2437 if (!Visit(E->getSubExpr()))
2438 return false;
2439
2440 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2441 QualType From
2442 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2443
2444 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2445 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2446 return true;
2447 }
2448
2449 case CK_IntegralComplexToFloatingComplex: {
2450 if (!Visit(E->getSubExpr()))
2451 return false;
2452
2453 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2454 QualType From
2455 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2456 Result.makeComplexFloat();
2457 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2458 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2459 return true;
2460 }
2461 }
2462
2463 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002464 return false;
2465}
2466
John McCallf4cf1a12010-05-07 17:22:02 +00002467bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002468 if (E->getOpcode() == BO_Comma) {
2469 if (!Visit(E->getRHS()))
2470 return false;
2471
2472 // If we can't evaluate the LHS, it might have side effects;
2473 // conservatively mark it.
2474 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2475 Info.EvalResult.HasSideEffects = true;
2476
2477 return true;
2478 }
John McCallf4cf1a12010-05-07 17:22:02 +00002479 if (!Visit(E->getLHS()))
2480 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002481
John McCallf4cf1a12010-05-07 17:22:02 +00002482 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002483 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002484 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002485
Daniel Dunbar3f279872009-01-29 01:32:56 +00002486 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2487 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002488 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002489 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002490 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002491 if (Result.isComplexFloat()) {
2492 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2493 APFloat::rmNearestTiesToEven);
2494 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2495 APFloat::rmNearestTiesToEven);
2496 } else {
2497 Result.getComplexIntReal() += RHS.getComplexIntReal();
2498 Result.getComplexIntImag() += RHS.getComplexIntImag();
2499 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002500 break;
John McCall2de56d12010-08-25 11:45:40 +00002501 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002502 if (Result.isComplexFloat()) {
2503 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2504 APFloat::rmNearestTiesToEven);
2505 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2506 APFloat::rmNearestTiesToEven);
2507 } else {
2508 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2509 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2510 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002511 break;
John McCall2de56d12010-08-25 11:45:40 +00002512 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002513 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002514 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002515 APFloat &LHS_r = LHS.getComplexFloatReal();
2516 APFloat &LHS_i = LHS.getComplexFloatImag();
2517 APFloat &RHS_r = RHS.getComplexFloatReal();
2518 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002519
Daniel Dunbar3f279872009-01-29 01:32:56 +00002520 APFloat Tmp = LHS_r;
2521 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2522 Result.getComplexFloatReal() = Tmp;
2523 Tmp = LHS_i;
2524 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2525 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2526
2527 Tmp = LHS_r;
2528 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2529 Result.getComplexFloatImag() = Tmp;
2530 Tmp = LHS_i;
2531 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2532 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2533 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002534 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002535 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002536 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2537 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002538 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002539 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2540 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2541 }
2542 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002543 case BO_Div:
2544 if (Result.isComplexFloat()) {
2545 ComplexValue LHS = Result;
2546 APFloat &LHS_r = LHS.getComplexFloatReal();
2547 APFloat &LHS_i = LHS.getComplexFloatImag();
2548 APFloat &RHS_r = RHS.getComplexFloatReal();
2549 APFloat &RHS_i = RHS.getComplexFloatImag();
2550 APFloat &Res_r = Result.getComplexFloatReal();
2551 APFloat &Res_i = Result.getComplexFloatImag();
2552
2553 APFloat Den = RHS_r;
2554 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2555 APFloat Tmp = RHS_i;
2556 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2557 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2558
2559 Res_r = LHS_r;
2560 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2561 Tmp = LHS_i;
2562 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2563 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2564 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2565
2566 Res_i = LHS_i;
2567 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2568 Tmp = LHS_r;
2569 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2570 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2571 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2572 } else {
2573 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2574 // FIXME: what about diagnostics?
2575 return false;
2576 }
2577 ComplexValue LHS = Result;
2578 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2579 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2580 Result.getComplexIntReal() =
2581 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2582 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2583 Result.getComplexIntImag() =
2584 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2585 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2586 }
2587 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002588 }
2589
John McCallf4cf1a12010-05-07 17:22:02 +00002590 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002591}
2592
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002593bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2594 // Get the operand value into 'Result'.
2595 if (!Visit(E->getSubExpr()))
2596 return false;
2597
2598 switch (E->getOpcode()) {
2599 default:
2600 // FIXME: what about diagnostics?
2601 return false;
2602 case UO_Extension:
2603 return true;
2604 case UO_Plus:
2605 // The result is always just the subexpr.
2606 return true;
2607 case UO_Minus:
2608 if (Result.isComplexFloat()) {
2609 Result.getComplexFloatReal().changeSign();
2610 Result.getComplexFloatImag().changeSign();
2611 }
2612 else {
2613 Result.getComplexIntReal() = -Result.getComplexIntReal();
2614 Result.getComplexIntImag() = -Result.getComplexIntImag();
2615 }
2616 return true;
2617 case UO_Not:
2618 if (Result.isComplexFloat())
2619 Result.getComplexFloatImag().changeSign();
2620 else
2621 Result.getComplexIntImag() = -Result.getComplexIntImag();
2622 return true;
2623 }
2624}
2625
John McCall56ca35d2011-02-17 10:25:35 +00002626bool ComplexExprEvaluator::
2627VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
2628 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2629 if (opaque.hasError()) return false;
2630
2631 bool cond;
2632 if (!HandleConversionToBool(e->getCond(), cond, Info))
2633 return false;
2634
2635 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2636}
2637
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002638bool ComplexExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
2639 bool Cond;
2640 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2641 return false;
2642
2643 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2644}
2645
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002646//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002647// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002648//===----------------------------------------------------------------------===//
2649
John McCall56ca35d2011-02-17 10:25:35 +00002650static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002651 if (E->getType()->isVectorType()) {
2652 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002653 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002654 } else if (E->getType()->isIntegerType()) {
2655 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002656 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002657 if (Info.EvalResult.Val.isLValue() &&
2658 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002659 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002660 } else if (E->getType()->hasPointerRepresentation()) {
2661 LValue LV;
2662 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002663 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002664 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002665 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002666 LV.moveInto(Info.EvalResult.Val);
2667 } else if (E->getType()->isRealFloatingType()) {
2668 llvm::APFloat F(0.0);
2669 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002670 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002671
John McCallefdb83e2010-05-07 21:00:08 +00002672 Info.EvalResult.Val = APValue(F);
2673 } else if (E->getType()->isAnyComplexType()) {
2674 ComplexValue C;
2675 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002676 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002677 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002678 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002679 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002680
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002681 return true;
2682}
2683
John McCall56ca35d2011-02-17 10:25:35 +00002684/// Evaluate - Return true if this is a constant which we can fold using
2685/// any crazy technique (that has nothing to do with language standards) that
2686/// we want to. If this function returns true, it returns the folded constant
2687/// in Result.
2688bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2689 EvalInfo Info(Ctx, Result);
2690 return ::Evaluate(Info, this);
2691}
2692
Jay Foad4ba2a172011-01-12 09:06:06 +00002693bool Expr::EvaluateAsBooleanCondition(bool &Result,
2694 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002695 EvalResult Scratch;
2696 EvalInfo Info(Ctx, Scratch);
2697
2698 return HandleConversionToBool(this, Result, Info);
2699}
2700
Jay Foad4ba2a172011-01-12 09:06:06 +00002701bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002702 EvalInfo Info(Ctx, Result);
2703
John McCallefdb83e2010-05-07 21:00:08 +00002704 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002705 if (EvaluateLValue(this, LV, Info) &&
2706 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002707 IsGlobalLValue(LV.Base)) {
2708 LV.moveInto(Result.Val);
2709 return true;
2710 }
2711 return false;
2712}
2713
Jay Foad4ba2a172011-01-12 09:06:06 +00002714bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2715 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002716 EvalInfo Info(Ctx, Result);
2717
2718 LValue LV;
2719 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002720 LV.moveInto(Result.Val);
2721 return true;
2722 }
2723 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002724}
2725
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002726/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002727/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002728bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002729 EvalResult Result;
2730 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002731}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002732
Jay Foad4ba2a172011-01-12 09:06:06 +00002733bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002734 Expr::EvalResult Result;
2735 EvalInfo Info(Ctx, Result);
2736 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2737}
2738
Jay Foad4ba2a172011-01-12 09:06:06 +00002739APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002740 EvalResult EvalResult;
2741 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002742 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002743 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002744 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002745
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002746 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002747}
John McCalld905f5a2010-05-07 05:32:02 +00002748
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002749 bool Expr::EvalResult::isGlobalLValue() const {
2750 assert(Val.isLValue());
2751 return IsGlobalLValue(Val.getLValueBase());
2752 }
2753
2754
John McCalld905f5a2010-05-07 05:32:02 +00002755/// isIntegerConstantExpr - this recursive routine will test if an expression is
2756/// an integer constant expression.
2757
2758/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2759/// comma, etc
2760///
2761/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2762/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2763/// cast+dereference.
2764
2765// CheckICE - This function does the fundamental ICE checking: the returned
2766// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2767// Note that to reduce code duplication, this helper does no evaluation
2768// itself; the caller checks whether the expression is evaluatable, and
2769// in the rare cases where CheckICE actually cares about the evaluated
2770// value, it calls into Evalute.
2771//
2772// Meanings of Val:
2773// 0: This expression is an ICE if it can be evaluated by Evaluate.
2774// 1: This expression is not an ICE, but if it isn't evaluated, it's
2775// a legal subexpression for an ICE. This return value is used to handle
2776// the comma operator in C99 mode.
2777// 2: This expression is not an ICE, and is not a legal subexpression for one.
2778
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002779namespace {
2780
John McCalld905f5a2010-05-07 05:32:02 +00002781struct ICEDiag {
2782 unsigned Val;
2783 SourceLocation Loc;
2784
2785 public:
2786 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2787 ICEDiag() : Val(0) {}
2788};
2789
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002790}
2791
2792static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002793
2794static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2795 Expr::EvalResult EVResult;
2796 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2797 !EVResult.Val.isInt()) {
2798 return ICEDiag(2, E->getLocStart());
2799 }
2800 return NoDiag();
2801}
2802
2803static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2804 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002805 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002806 return ICEDiag(2, E->getLocStart());
2807 }
2808
2809 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002810#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002811#define STMT(Node, Base) case Expr::Node##Class:
2812#define EXPR(Node, Base)
2813#include "clang/AST/StmtNodes.inc"
2814 case Expr::PredefinedExprClass:
2815 case Expr::FloatingLiteralClass:
2816 case Expr::ImaginaryLiteralClass:
2817 case Expr::StringLiteralClass:
2818 case Expr::ArraySubscriptExprClass:
2819 case Expr::MemberExprClass:
2820 case Expr::CompoundAssignOperatorClass:
2821 case Expr::CompoundLiteralExprClass:
2822 case Expr::ExtVectorElementExprClass:
2823 case Expr::InitListExprClass:
2824 case Expr::DesignatedInitExprClass:
2825 case Expr::ImplicitValueInitExprClass:
2826 case Expr::ParenListExprClass:
2827 case Expr::VAArgExprClass:
2828 case Expr::AddrLabelExprClass:
2829 case Expr::StmtExprClass:
2830 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002831 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002832 case Expr::CXXDynamicCastExprClass:
2833 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002834 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002835 case Expr::CXXNullPtrLiteralExprClass:
2836 case Expr::CXXThisExprClass:
2837 case Expr::CXXThrowExprClass:
2838 case Expr::CXXNewExprClass:
2839 case Expr::CXXDeleteExprClass:
2840 case Expr::CXXPseudoDestructorExprClass:
2841 case Expr::UnresolvedLookupExprClass:
2842 case Expr::DependentScopeDeclRefExprClass:
2843 case Expr::CXXConstructExprClass:
2844 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002845 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002846 case Expr::CXXTemporaryObjectExprClass:
2847 case Expr::CXXUnresolvedConstructExprClass:
2848 case Expr::CXXDependentScopeMemberExprClass:
2849 case Expr::UnresolvedMemberExprClass:
2850 case Expr::ObjCStringLiteralClass:
2851 case Expr::ObjCEncodeExprClass:
2852 case Expr::ObjCMessageExprClass:
2853 case Expr::ObjCSelectorExprClass:
2854 case Expr::ObjCProtocolExprClass:
2855 case Expr::ObjCIvarRefExprClass:
2856 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002857 case Expr::ObjCIsaExprClass:
2858 case Expr::ShuffleVectorExprClass:
2859 case Expr::BlockExprClass:
2860 case Expr::BlockDeclRefExprClass:
2861 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002862 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002863 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002864 case Expr::SubstNonTypeTemplateParmPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002865 return ICEDiag(2, E->getLocStart());
2866
Douglas Gregoree8aff02011-01-04 17:33:58 +00002867 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002868 case Expr::GNUNullExprClass:
2869 // GCC considers the GNU __null value to be an integral constant expression.
2870 return NoDiag();
2871
2872 case Expr::ParenExprClass:
2873 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002874 case Expr::GenericSelectionExprClass:
2875 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002876 case Expr::IntegerLiteralClass:
2877 case Expr::CharacterLiteralClass:
2878 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002879 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002880 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002881 case Expr::BinaryTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00002882 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002883 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002884 return NoDiag();
2885 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002886 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002887 const CallExpr *CE = cast<CallExpr>(E);
2888 if (CE->isBuiltinCall(Ctx))
2889 return CheckEvalInICE(E, Ctx);
2890 return ICEDiag(2, E->getLocStart());
2891 }
2892 case Expr::DeclRefExprClass:
2893 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2894 return NoDiag();
2895 if (Ctx.getLangOptions().CPlusPlus &&
2896 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2897 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2898
2899 // Parameter variables are never constants. Without this check,
2900 // getAnyInitializer() can find a default argument, which leads
2901 // to chaos.
2902 if (isa<ParmVarDecl>(D))
2903 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2904
2905 // C++ 7.1.5.1p2
2906 // A variable of non-volatile const-qualified integral or enumeration
2907 // type initialized by an ICE can be used in ICEs.
2908 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2909 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2910 if (Quals.hasVolatile() || !Quals.hasConst())
2911 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2912
2913 // Look for a declaration of this variable that has an initializer.
2914 const VarDecl *ID = 0;
2915 const Expr *Init = Dcl->getAnyInitializer(ID);
2916 if (Init) {
2917 if (ID->isInitKnownICE()) {
2918 // We have already checked whether this subexpression is an
2919 // integral constant expression.
2920 if (ID->isInitICE())
2921 return NoDiag();
2922 else
2923 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2924 }
2925
2926 // It's an ICE whether or not the definition we found is
2927 // out-of-line. See DR 721 and the discussion in Clang PR
2928 // 6206 for details.
2929
2930 if (Dcl->isCheckingICE()) {
2931 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2932 }
2933
2934 Dcl->setCheckingICE();
2935 ICEDiag Result = CheckICE(Init, Ctx);
2936 // Cache the result of the ICE test.
2937 Dcl->setInitKnownICE(Result.Val == 0);
2938 return Result;
2939 }
2940 }
2941 }
2942 return ICEDiag(2, E->getLocStart());
2943 case Expr::UnaryOperatorClass: {
2944 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2945 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002946 case UO_PostInc:
2947 case UO_PostDec:
2948 case UO_PreInc:
2949 case UO_PreDec:
2950 case UO_AddrOf:
2951 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002952 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002953 case UO_Extension:
2954 case UO_LNot:
2955 case UO_Plus:
2956 case UO_Minus:
2957 case UO_Not:
2958 case UO_Real:
2959 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002960 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002961 }
2962
2963 // OffsetOf falls through here.
2964 }
2965 case Expr::OffsetOfExprClass: {
2966 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2967 // Evaluate matches the proposed gcc behavior for cases like
2968 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2969 // compliance: we should warn earlier for offsetof expressions with
2970 // array subscripts that aren't ICEs, and if the array subscripts
2971 // are ICEs, the value of the offsetof must be an integer constant.
2972 return CheckEvalInICE(E, Ctx);
2973 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002974 case Expr::UnaryExprOrTypeTraitExprClass: {
2975 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2976 if ((Exp->getKind() == UETT_SizeOf) &&
2977 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002978 return ICEDiag(2, E->getLocStart());
2979 return NoDiag();
2980 }
2981 case Expr::BinaryOperatorClass: {
2982 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2983 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002984 case BO_PtrMemD:
2985 case BO_PtrMemI:
2986 case BO_Assign:
2987 case BO_MulAssign:
2988 case BO_DivAssign:
2989 case BO_RemAssign:
2990 case BO_AddAssign:
2991 case BO_SubAssign:
2992 case BO_ShlAssign:
2993 case BO_ShrAssign:
2994 case BO_AndAssign:
2995 case BO_XorAssign:
2996 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002997 return ICEDiag(2, E->getLocStart());
2998
John McCall2de56d12010-08-25 11:45:40 +00002999 case BO_Mul:
3000 case BO_Div:
3001 case BO_Rem:
3002 case BO_Add:
3003 case BO_Sub:
3004 case BO_Shl:
3005 case BO_Shr:
3006 case BO_LT:
3007 case BO_GT:
3008 case BO_LE:
3009 case BO_GE:
3010 case BO_EQ:
3011 case BO_NE:
3012 case BO_And:
3013 case BO_Xor:
3014 case BO_Or:
3015 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00003016 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3017 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00003018 if (Exp->getOpcode() == BO_Div ||
3019 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00003020 // Evaluate gives an error for undefined Div/Rem, so make sure
3021 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00003022 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00003023 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
3024 if (REval == 0)
3025 return ICEDiag(1, E->getLocStart());
3026 if (REval.isSigned() && REval.isAllOnesValue()) {
3027 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
3028 if (LEval.isMinSignedValue())
3029 return ICEDiag(1, E->getLocStart());
3030 }
3031 }
3032 }
John McCall2de56d12010-08-25 11:45:40 +00003033 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00003034 if (Ctx.getLangOptions().C99) {
3035 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3036 // if it isn't evaluated.
3037 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3038 return ICEDiag(1, E->getLocStart());
3039 } else {
3040 // In both C89 and C++, commas in ICEs are illegal.
3041 return ICEDiag(2, E->getLocStart());
3042 }
3043 }
3044 if (LHSResult.Val >= RHSResult.Val)
3045 return LHSResult;
3046 return RHSResult;
3047 }
John McCall2de56d12010-08-25 11:45:40 +00003048 case BO_LAnd:
3049 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00003050 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3051 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3052 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3053 // Rare case where the RHS has a comma "side-effect"; we need
3054 // to actually check the condition to see whether the side
3055 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003056 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00003057 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3058 return RHSResult;
3059 return NoDiag();
3060 }
3061
3062 if (LHSResult.Val >= RHSResult.Val)
3063 return LHSResult;
3064 return RHSResult;
3065 }
3066 }
3067 }
3068 case Expr::ImplicitCastExprClass:
3069 case Expr::CStyleCastExprClass:
3070 case Expr::CXXFunctionalCastExprClass:
3071 case Expr::CXXStaticCastExprClass:
3072 case Expr::CXXReinterpretCastExprClass:
3073 case Expr::CXXConstCastExprClass: {
3074 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003075 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003076 return CheckICE(SubExpr, Ctx);
3077 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3078 return NoDiag();
3079 return ICEDiag(2, E->getLocStart());
3080 }
John McCall56ca35d2011-02-17 10:25:35 +00003081 case Expr::BinaryConditionalOperatorClass: {
3082 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3083 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3084 if (CommonResult.Val == 2) return CommonResult;
3085 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3086 if (FalseResult.Val == 2) return FalseResult;
3087 if (CommonResult.Val == 1) return CommonResult;
3088 if (FalseResult.Val == 1 &&
3089 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3090 return FalseResult;
3091 }
John McCalld905f5a2010-05-07 05:32:02 +00003092 case Expr::ConditionalOperatorClass: {
3093 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3094 // If the condition (ignoring parens) is a __builtin_constant_p call,
3095 // then only the true side is actually considered in an integer constant
3096 // expression, and it is fully evaluated. This is an important GNU
3097 // extension. See GCC PR38377 for discussion.
3098 if (const CallExpr *CallCE
3099 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3100 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3101 Expr::EvalResult EVResult;
3102 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3103 !EVResult.Val.isInt()) {
3104 return ICEDiag(2, E->getLocStart());
3105 }
3106 return NoDiag();
3107 }
3108 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
3109 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3110 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3111 if (CondResult.Val == 2)
3112 return CondResult;
3113 if (TrueResult.Val == 2)
3114 return TrueResult;
3115 if (FalseResult.Val == 2)
3116 return FalseResult;
3117 if (CondResult.Val == 1)
3118 return CondResult;
3119 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3120 return NoDiag();
3121 // Rare case where the diagnostics depend on which side is evaluated
3122 // Note that if we get here, CondResult is 0, and at least one of
3123 // TrueResult and FalseResult is non-zero.
3124 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3125 return FalseResult;
3126 }
3127 return TrueResult;
3128 }
3129 case Expr::CXXDefaultArgExprClass:
3130 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3131 case Expr::ChooseExprClass: {
3132 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3133 }
3134 }
3135
3136 // Silence a GCC warning
3137 return ICEDiag(2, E->getLocStart());
3138}
3139
3140bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3141 SourceLocation *Loc, bool isEvaluated) const {
3142 ICEDiag d = CheckICE(this, Ctx);
3143 if (d.Val != 0) {
3144 if (Loc) *Loc = d.Loc;
3145 return false;
3146 }
3147 EvalResult EvalResult;
3148 if (!Evaluate(EvalResult, Ctx))
3149 llvm_unreachable("ICE cannot be evaluated!");
3150 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3151 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3152 Result = EvalResult.Val.getInt();
3153 return true;
3154}