blob: c2caf8d40b16718ef7e2d5c4abbf02f5cda9f50e [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Benjamin Kramer024e6192011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
49 /// EvalResult - Contains information about the evaluation.
50 Expr::EvalResult &EvalResult;
51
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
61 : Ctx(ctx), EvalResult(evalresult) {}
62 };
63
John McCall93d91dc2010-05-07 17:22:02 +000064 struct ComplexValue {
65 private:
66 bool IsInt;
67
68 public:
69 APSInt IntReal, IntImag;
70 APFloat FloatReal, FloatImag;
71
72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
73
74 void makeComplexFloat() { IsInt = false; }
75 bool isComplexFloat() const { return !IsInt; }
76 APFloat &getComplexFloatReal() { return FloatReal; }
77 APFloat &getComplexFloatImag() { return FloatImag; }
78
79 void makeComplexInt() { IsInt = true; }
80 bool isComplexInt() const { return IsInt; }
81 APSInt &getComplexIntReal() { return IntReal; }
82 APSInt &getComplexIntImag() { return IntImag; }
83
John McCallc07a0c72011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCallc07a0c72011-02-17 10:25:35 +000090 void setFrom(const APValue &v) {
91 assert(v.isComplexFloat() || v.isComplexInt());
92 if (v.isComplexFloat()) {
93 makeComplexFloat();
94 FloatReal = v.getComplexFloatReal();
95 FloatImag = v.getComplexFloatImag();
96 } else {
97 makeComplexInt();
98 IntReal = v.getComplexIntReal();
99 IntImag = v.getComplexIntImag();
100 }
101 }
John McCall93d91dc2010-05-07 17:22:02 +0000102 };
John McCall45d55e42010-05-07 21:00:08 +0000103
104 struct LValue {
105 Expr *Base;
106 CharUnits Offset;
107
108 Expr *getLValueBase() { return Base; }
109 CharUnits getLValueOffset() { return Offset; }
110
John McCallc07a0c72011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCall45d55e42010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCallc07a0c72011-02-17 10:25:35 +0000114 void setFrom(const APValue &v) {
115 assert(v.isLValue());
116 Base = v.getLValueBase();
117 Offset = v.getLValueOffset();
118 }
John McCall45d55e42010-05-07 21:00:08 +0000119 };
John McCall93d91dc2010-05-07 17:22:02 +0000120}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000121
John McCallc07a0c72011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattner6c4d2552009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000136 if (!E) return true;
137
138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
139 if (isa<FunctionDecl>(DRE->getDecl()))
140 return true;
141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
142 return VD->hasGlobalStorage();
143 return false;
144 }
145
146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
147 return CLE->isFileScope();
148
149 return true;
150}
151
John McCall45d55e42010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000154
John McCalleb3e4f32010-05-07 21:34:32 +0000155 // A null base expression indicates a null pointer. These are always
156 // evaluatable, and they are false unless the offset is zero.
157 if (!Base) {
158 Result = !Value.Offset.isZero();
159 return true;
160 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000161
John McCall95007602010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000164
John McCalleb3e4f32010-05-07 21:34:32 +0000165 // We have a non-null base expression. These are generally known to
166 // be true, but if it'a decl-ref to a weak symbol it can be null at
167 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCalleb3e4f32010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman334046a2009-06-14 02:17:33 +0000181 return true;
182}
183
John McCall1be1c632010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000187 APSInt IntResult;
188 if (!EvaluateInteger(E, IntResult, Info))
189 return false;
190 Result = IntResult != 0;
191 return true;
192 } else if (E->getType()->isRealFloatingType()) {
193 APFloat FloatResult(0.0);
194 if (!EvaluateFloat(E, FloatResult, Info))
195 return false;
196 Result = !FloatResult.isZero();
197 return true;
Eli Friedman64004332009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman9a156e52008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman334046a2009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedman64004332009-03-23 04:38:34 +0000205 if (!EvaluateComplex(E, ComplexResult, Info))
206 return false;
207 if (ComplexResult.isComplexFloat()) {
208 Result = !ComplexResult.getComplexFloatReal().isZero() ||
209 !ComplexResult.getComplexFloatImag().isZero();
210 } else {
211 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
212 ComplexResult.getComplexIntImag().getBoolValue();
213 }
214 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump11289f42009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
224 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +0000225
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
227 uint64_t Space[4];
228 bool ignored;
229 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
230 llvm::APFloat::rmTowardZero, &ignored);
231 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
232}
233
Mike Stump11289f42009-09-09 15:08:12 +0000234static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000235 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000236 bool ignored;
237 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000238 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000239 APFloat::rmNearestTiesToEven, &ignored);
240 return Result;
241}
242
Mike Stump11289f42009-09-09 15:08:12 +0000243static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000244 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000245 unsigned DestWidth = Ctx.getIntWidth(DestType);
246 APSInt Result = Value;
247 // Figure out if this is a truncate, extend or noop cast.
248 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000249 Result = Result.extOrTrunc(DestWidth);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000250 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
251 return Result;
252}
253
Mike Stump11289f42009-09-09 15:08:12 +0000254static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000255 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000256
257 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
258 Result.convertFromAPInt(Value, Value.isSigned(),
259 APFloat::rmNearestTiesToEven);
260 return Result;
261}
262
Mike Stump876387b2009-10-27 22:09:17 +0000263namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000264class HasSideEffect
Mike Stump876387b2009-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 Collingbourne91147592011-04-15 00:35:48 +0000277 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
278 return Visit(E->getResultExpr());
279 }
Mike Stump876387b2009-10-27 22:09:17 +0000280 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000281 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000282 return true;
283 return false;
284 }
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 Collingbournee190dee2011-03-11 19:24:49 +0000296 bool VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E)
297 { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000298 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000299 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stump876387b2009-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 Stumpf3eb5ec2009-10-29 23:34:20 +0000304 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stumpfa502902009-10-29 20:48:09 +0000305 bool VisitBinaryOperator(BinaryOperator *E)
306 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stump876387b2009-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 Stump53f9ded2009-11-03 23:25:48 +0000312 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000313 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000314 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000315 }
316 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-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 Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000322 if (Expr *filler = E->getArrayFiller())
323 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000324 return false;
325 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000326
327 bool VisitSizeOfPackExpr(SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000328};
329
John McCallc07a0c72011-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 Stump876387b2009-10-27 22:09:17 +0000354} // end anonymous namespace
355
Eli Friedman9a156e52008-11-12 09:44:48 +0000356//===----------------------------------------------------------------------===//
357// LValue Evaluation
358//===----------------------------------------------------------------------===//
359namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000360class LValueExprEvaluator
John McCall45d55e42010-05-07 21:00:08 +0000361 : public StmtVisitor<LValueExprEvaluator, bool> {
Eli Friedman9a156e52008-11-12 09:44:48 +0000362 EvalInfo &Info;
John McCall45d55e42010-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 Friedman9a156e52008-11-12 09:44:48 +0000370public:
Mike Stump11289f42009-09-09 15:08:12 +0000371
John McCall45d55e42010-05-07 21:00:08 +0000372 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
373 Info(info), Result(Result) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000374
John McCall45d55e42010-05-07 21:00:08 +0000375 bool VisitStmt(Stmt *S) {
376 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000377 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000378
John McCall45d55e42010-05-07 21:00:08 +0000379 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbourne91147592011-04-15 00:35:48 +0000380 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
381 return Visit(E->getResultExpr());
382 }
John McCall45d55e42010-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 Friedman449fe542009-03-23 04:56:01 +0000392 { return Visit(E->getSubExpr()); }
John McCall45d55e42010-05-07 21:00:08 +0000393 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman449fe542009-03-23 04:56:01 +0000394 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlssonde55f642009-10-03 16:30:22 +0000395
John McCall45d55e42010-05-07 21:00:08 +0000396 bool VisitCastExpr(CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000397 switch (E->getCastKind()) {
398 default:
John McCall45d55e42010-05-07 21:00:08 +0000399 return false;
Anders Carlssonde55f642009-10-03 16:30:22 +0000400
John McCalle3027922010-08-25 11:45:40 +0000401 case CK_NoOp:
Anders Carlssonde55f642009-10-03 16:30:22 +0000402 return Visit(E->getSubExpr());
403 }
404 }
Eli Friedman449fe542009-03-23 04:56:01 +0000405 // FIXME: Missing: __real__, __imag__
Eli Friedman9a156e52008-11-12 09:44:48 +0000406};
407} // end anonymous namespace
408
John McCall45d55e42010-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 Friedman9a156e52008-11-12 09:44:48 +0000411}
412
John McCall45d55e42010-05-07 21:00:08 +0000413bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000414 if (isa<FunctionDecl>(E->getDecl())) {
John McCall45d55e42010-05-07 21:00:08 +0000415 return Success(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000416 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
417 if (!VD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000418 return Success(E);
Chandler Carruthe299ba62010-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 Friedman9ab03192009-08-29 19:09:59 +0000423 // FIXME: Check whether VD might be overridden!
Sebastian Redl5ca79842010-02-01 20:16:42 +0000424 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregor0840cc02009-11-01 20:32:48 +0000425 return Visit(const_cast<Expr *>(Init));
Eli Friedman751aa72b72009-05-27 06:04:58 +0000426 }
427
John McCall45d55e42010-05-07 21:00:08 +0000428 return false;
Anders Carlssona42ee442008-11-24 04:41:22 +0000429}
430
John McCall45d55e42010-05-07 21:00:08 +0000431bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000432 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000433}
434
John McCall45d55e42010-05-07 21:00:08 +0000435bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000436 QualType Ty;
437 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000438 if (!EvaluatePointer(E->getBase(), Result, Info))
439 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000440 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000441 } else {
John McCall45d55e42010-05-07 21:00:08 +0000442 if (!Visit(E->getBase()))
443 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000444 Ty = E->getBase()->getType();
445 }
446
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000447 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000448 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-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 McCall45d55e42010-05-07 21:00:08 +0000452 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000453
454 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000455 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000456
Eli Friedman9a156e52008-11-12 09:44:48 +0000457 // FIXME: This is linear time.
Douglas Gregor91f84212008-12-11 16:49:14 +0000458 unsigned i = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000459 for (RecordDecl::field_iterator Field = RD->field_begin(),
460 FieldEnd = RD->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +0000461 Field != FieldEnd; (void)++Field, ++i) {
462 if (*Field == FD)
Eli Friedman9a156e52008-11-12 09:44:48 +0000463 break;
464 }
465
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000466 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000467 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000468}
469
John McCall45d55e42010-05-07 21:00:08 +0000470bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000471 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000472 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000473
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000474 APSInt Index;
475 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000476 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000477
Ken Dyck40775002010-01-11 17:06:35 +0000478 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000479 Result.Offset += Index.getSExtValue() * ElementSize;
480 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000481}
Eli Friedman9a156e52008-11-12 09:44:48 +0000482
John McCall45d55e42010-05-07 21:00:08 +0000483bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
484 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000485}
486
Eli Friedman9a156e52008-11-12 09:44:48 +0000487//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000488// Pointer Evaluation
489//===----------------------------------------------------------------------===//
490
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000491namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000492class PointerExprEvaluator
John McCall45d55e42010-05-07 21:00:08 +0000493 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattnercdf34e72008-07-11 22:52:41 +0000494 EvalInfo &Info;
John McCall45d55e42010-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 Carlssonb5ad0212008-07-08 14:30:00 +0000502public:
Mike Stump11289f42009-09-09 15:08:12 +0000503
John McCall45d55e42010-05-07 21:00:08 +0000504 PointerExprEvaluator(EvalInfo &info, LValue &Result)
505 : Info(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000506
John McCall45d55e42010-05-07 21:00:08 +0000507 bool VisitStmt(Stmt *S) {
508 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000509 }
510
John McCall45d55e42010-05-07 21:00:08 +0000511 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbourne91147592011-04-15 00:35:48 +0000512 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
513 return Visit(E->getResultExpr());
514 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000515
John McCall45d55e42010-05-07 21:00:08 +0000516 bool VisitBinaryOperator(const BinaryOperator *E);
517 bool VisitCastExpr(CastExpr* E);
518 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanc2b50172009-02-22 11:46:18 +0000519 { return Visit(E->getSubExpr()); }
John McCall45d55e42010-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 McCallc63de662011-02-02 13:00:07 +0000527 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000528 return Success(E);
529 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000530 }
John McCall45d55e42010-05-07 21:00:08 +0000531 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
532 { return Success((Expr*)0); }
John McCallc07a0c72011-02-17 10:25:35 +0000533 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
John McCall45d55e42010-05-07 21:00:08 +0000534 bool VisitConditionalOperator(ConditionalOperator *E);
535 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl576fd422009-05-10 18:38:11 +0000536 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCall45d55e42010-05-07 21:00:08 +0000537 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
538 { return Success((Expr*)0); }
John McCallc07a0c72011-02-17 10:25:35 +0000539
540 bool VisitOpaqueValueExpr(OpaqueValueExpr *E);
Eli Friedman449fe542009-03-23 04:56:01 +0000541 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000542};
Chris Lattner05706e882008-07-11 18:11:29 +0000543} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000544
John McCall45d55e42010-05-07 21:00:08 +0000545static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000546 assert(E->getType()->hasPointerRepresentation());
John McCall45d55e42010-05-07 21:00:08 +0000547 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattner05706e882008-07-11 18:11:29 +0000548}
549
John McCall45d55e42010-05-07 21:00:08 +0000550bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000551 if (E->getOpcode() != BO_Add &&
552 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +0000553 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattner05706e882008-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 Stump11289f42009-09-09 15:08:12 +0000559
John McCall45d55e42010-05-07 21:00:08 +0000560 if (!EvaluatePointer(PExp, Result, Info))
561 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000562
John McCall45d55e42010-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 Lattner05706e882008-07-11 18:11:29 +0000569
Daniel Dunbar4c43e312010-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 McCall45d55e42010-05-07 21:00:08 +0000574 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +0000575
Anders Carlssonef56fba2009-02-19 04:55:58 +0000576 // Explicitly handle GNU void* and function pointer arithmetic extensions.
577 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +0000578 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +0000579 else
John McCall45d55e42010-05-07 21:00:08 +0000580 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +0000581
John McCalle3027922010-08-25 11:45:40 +0000582 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +0000583 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000584 else
John McCall45d55e42010-05-07 21:00:08 +0000585 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000586
John McCall45d55e42010-05-07 21:00:08 +0000587 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000588}
Eli Friedman9a156e52008-11-12 09:44:48 +0000589
John McCall45d55e42010-05-07 21:00:08 +0000590bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
591 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000592}
Mike Stump11289f42009-09-09 15:08:12 +0000593
Chris Lattner05706e882008-07-11 18:11:29 +0000594
John McCall45d55e42010-05-07 21:00:08 +0000595bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman847a2bc2009-12-27 05:43:15 +0000596 Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000597
Eli Friedman847a2bc2009-12-27 05:43:15 +0000598 switch (E->getCastKind()) {
599 default:
600 break;
601
John McCalle3027922010-08-25 11:45:40 +0000602 case CK_NoOp:
603 case CK_BitCast:
John McCalle3027922010-08-25 11:45:40 +0000604 case CK_AnyPointerToObjCPointerCast:
605 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +0000606 return Visit(SubExpr);
607
Anders Carlsson18275092010-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 Dyck02155cb2011-01-26 02:17:08 +0000616 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-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 Dyck02155cb2011-01-26 02:17:08 +0000634 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +0000635 DerivedDecl = BaseDecl;
636 }
637
638 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +0000639 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +0000640 return true;
641 }
642
John McCalle84af4e2010-11-13 01:35:44 +0000643 case CK_NullToPointer: {
644 Result.Base = 0;
645 Result.Offset = CharUnits::Zero();
646 return true;
647 }
648
John McCalle3027922010-08-25 11:45:40 +0000649 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +0000650 APValue Value;
651 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000652 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000653
John McCall45d55e42010-05-07 21:00:08 +0000654 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000655 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-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 Lattner05706e882008-07-11 18:11:29 +0000664 }
665 }
John McCalle3027922010-08-25 11:45:40 +0000666 case CK_ArrayToPointerDecay:
667 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +0000668 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000669 }
670
John McCall45d55e42010-05-07 21:00:08 +0000671 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000672}
Chris Lattner05706e882008-07-11 18:11:29 +0000673
John McCall45d55e42010-05-07 21:00:08 +0000674bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000675 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000676 Builtin::BI__builtin___CFStringMakeConstantString ||
677 E->isBuiltinCall(Info.Ctx) ==
678 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +0000679 return Success(E);
680 return false;
Eli Friedmanc69d4542009-01-25 01:54:01 +0000681}
682
John McCallc07a0c72011-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 McCall45d55e42010-05-07 21:00:08 +0000703bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000704 bool BoolResult;
705 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCall45d55e42010-05-07 21:00:08 +0000706 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000707
708 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCall45d55e42010-05-07 21:00:08 +0000709 return Visit(EvalExpr);
Eli Friedman9a156e52008-11-12 09:44:48 +0000710}
Chris Lattner05706e882008-07-11 18:11:29 +0000711
712//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000713// Vector Evaluation
714//===----------------------------------------------------------------------===//
715
716namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000717 class VectorExprEvaluator
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000718 : public StmtVisitor<VectorExprEvaluator, APValue> {
719 EvalInfo &Info;
Eli Friedman3ae59112009-02-23 04:23:56 +0000720 APValue GetZeroVector(QualType VecType);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000721 public:
Mike Stump11289f42009-09-09 15:08:12 +0000722
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000723 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump11289f42009-09-09 15:08:12 +0000724
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000725 APValue VisitStmt(Stmt *S) {
726 return APValue();
727 }
Mike Stump11289f42009-09-09 15:08:12 +0000728
Eli Friedman3ae59112009-02-23 04:23:56 +0000729 APValue VisitParenExpr(ParenExpr *E)
730 { return Visit(E->getSubExpr()); }
Peter Collingbourne91147592011-04-15 00:35:48 +0000731 APValue VisitGenericSelectionExpr(GenericSelectionExpr *E)
732 { return Visit(E->getResultExpr()); }
Eli Friedman3ae59112009-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 Begeman2f2bdeb2009-01-18 03:20:47 +0000741 APValue VisitCastExpr(const CastExpr* E);
742 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
743 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000744 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +0000745 APValue VisitChooseExpr(const ChooseExpr *E)
746 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman3ae59112009-02-23 04:23:56 +0000747 APValue VisitUnaryImag(const UnaryOperator *E);
748 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000749 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000750 // shufflevector, ExtVectorElementExpr
751 // (Note that these require implementing conversions
752 // between vector types.)
Nate Begeman2f2bdeb2009-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 McCall9dd450b2009-09-21 23:43:11 +0000764 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000765 QualType EltTy = VTy->getElementType();
766 unsigned NElts = VTy->getNumElements();
767 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000768
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000769 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000770 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000771
Eli Friedmanc757de22011-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 Carlsson6fc22042011-03-25 11:22:47 +0000786 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000787 }
Nate Begemanef1a7fa2009-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 Begeman2ffd3842009-06-26 18:22:18 +0000792 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000793 case CK_BitCast: {
794 if (SETy->isVectorType())
795 return Visit(const_cast<Expr*>(SE));
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000796
Eli Friedmanc757de22011-03-25 00:43:55 +0000797 if (!SETy->isIntegerType())
Anders Carlsson6fc22042011-03-25 11:22:47 +0000798 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000799
Eli Friedmanc757de22011-03-25 00:43:55 +0000800 APSInt Init;
801 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000802 return APValue();
803
Eli Friedmanc757de22011-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 Begemanef1a7fa2009-07-01 07:50:47 +0000819 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000820 case CK_LValueToRValue:
821 case CK_NoOp:
822 return Visit(const_cast<Expr*>(SE));
823 default:
Anders Carlsson6fc22042011-03-25 11:22:47 +0000824 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000825 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000826}
827
Mike Stump11289f42009-09-09 15:08:12 +0000828APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000829VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
830 return this->Visit(const_cast<Expr*>(E->getInitializer()));
831}
832
Mike Stump11289f42009-09-09 15:08:12 +0000833APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000834VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall9dd450b2009-09-21 23:43:11 +0000835 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000836 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000837 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000838
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000839 QualType EltTy = VT->getElementType();
840 llvm::SmallVector<APValue, 4> Elements;
841
John McCall875679e2010-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 Lattner5ac257d2011-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 McCall875679e2010-06-11 17:54:15 +0000852 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000853 if (EltTy->isIntegerType()) {
854 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +0000855 if (!EvaluateInteger(E->getInit(0), sInt, Info))
856 return APValue();
857 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000858 } else {
859 llvm::APFloat f(0.0);
John McCall875679e2010-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 Friedman3ae59112009-02-23 04:23:56 +0000878 } else {
John McCall875679e2010-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 Friedman3ae59112009-02-23 04:23:56 +0000887 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000888 }
889 }
890 return APValue(&Elements[0], Elements.size());
891}
892
Mike Stump11289f42009-09-09 15:08:12 +0000893APValue
Eli Friedman3ae59112009-02-23 04:23:56 +0000894VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +0000895 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman3ae59112009-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 Friedman3ae59112009-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 Begeman2f2bdeb2009-01-18 03:20:47 +0000927//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000928// Integer Evaluation
929//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000930
931namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000932class IntExprEvaluator
Chris Lattnere13042c2008-07-11 19:10:17 +0000933 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattnercdf34e72008-07-11 22:52:41 +0000934 EvalInfo &Info;
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000935 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000936public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000937 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattnercdf34e72008-07-11 22:52:41 +0000938 : Info(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000939
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000940 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000941 assert(E->getType()->isIntegralOrEnumerationType() &&
942 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000943 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000944 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000945 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000946 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000947 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000948 return true;
949 }
950
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000951 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000952 assert(E->getType()->isIntegralOrEnumerationType() &&
953 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000954 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000955 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000956 Result = APValue(APSInt(I));
957 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000958 return true;
959 }
960
961 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000962 assert(E->getType()->isIntegralOrEnumerationType() &&
963 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000964 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000965 return true;
966 }
967
Ken Dyckdbc01912011-03-11 02:13:43 +0000968 bool Success(CharUnits Size, const Expr *E) {
969 return Success(Size.getQuantity(), E);
970 }
971
972
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000973 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000974 // Take the first error.
Anders Carlssonbd1df8e2008-11-30 16:38:33 +0000975 if (Info.EvalResult.Diag == 0) {
976 Info.EvalResult.DiagLoc = L;
977 Info.EvalResult.Diag = D;
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000978 Info.EvalResult.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000979 }
Chris Lattner99415702008-07-12 00:14:42 +0000980 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +0000981 }
Mike Stump11289f42009-09-09 15:08:12 +0000982
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000983 //===--------------------------------------------------------------------===//
984 // Visitor Methods
985 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000986
Chris Lattnerfac05ae2008-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 Stump11289f42009-09-09 15:08:12 +0000991
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000992 bool VisitExpr(Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +0000993 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000994 }
Mike Stump11289f42009-09-09 15:08:12 +0000995
Chris Lattnere13042c2008-07-11 19:10:17 +0000996 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbourne91147592011-04-15 00:35:48 +0000997 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
998 return Visit(E->getResultExpr());
999 }
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001000
Chris Lattner7174bf32008-07-12 00:38:25 +00001001 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001002 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001003 }
1004 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001005 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001006 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001007
John McCallc07a0c72011-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 Friedmanfb8a93f2009-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 Friedmand5c93992010-02-13 00:10:10 +00001030 bool VisitCallExpr(CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001031 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001032 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001033 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopes42042612008-11-16 19:28:31 +00001034 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCallc07a0c72011-02-17 10:25:35 +00001035 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001036
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001037 bool VisitCastExpr(CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001038 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001039
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001040 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001041 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001042 }
Mike Stump11289f42009-09-09 15:08:12 +00001043
Anders Carlsson39def3a2008-12-21 22:39:40 +00001044 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001045 return Success(0, E);
Anders Carlsson39def3a2008-12-21 22:39:40 +00001046 }
Mike Stump11289f42009-09-09 15:08:12 +00001047
Douglas Gregor747eb782010-07-08 06:14:04 +00001048 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001049 return Success(0, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001050 }
1051
Eli Friedman4e7a2412009-02-27 04:45:43 +00001052 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1053 return Success(0, E);
1054 }
1055
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001056 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001057 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001058 }
1059
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001060 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1061 return Success(E->getValue(), E);
1062 }
1063
John Wiegley6242b6a2011-04-28 00:16:57 +00001064 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1065 return Success(E->getValue(), E);
1066 }
1067
John Wiegleyf9f65842011-04-25 06:54:41 +00001068 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1069 return Success(E->getValue(), E);
1070 }
1071
Eli Friedman449fe542009-03-23 04:56:01 +00001072 bool VisitChooseExpr(const ChooseExpr *E) {
1073 return Visit(E->getChosenSubExpr(Info.Ctx));
1074 }
1075
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001076 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001077 bool VisitUnaryImag(const UnaryOperator *E);
1078
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001079 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001080 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1081
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001082private:
Ken Dyck160146e2010-01-27 17:10:57 +00001083 CharUnits GetAlignOfExpr(const Expr *E);
1084 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001085 static QualType GetObjectType(const Expr *E);
1086 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001087 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001088};
Chris Lattner05706e882008-07-11 18:11:29 +00001089} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001090
Daniel Dunbarce399542009-02-20 18:22:23 +00001091static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001092 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbarce399542009-02-20 18:22:23 +00001093 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1094}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001095
Daniel Dunbarce399542009-02-20 18:22:23 +00001096static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001097 assert(E->getType()->isIntegralOrEnumerationType());
John McCallf0c4f352010-05-07 05:46:35 +00001098
Daniel Dunbarce399542009-02-20 18:22:23 +00001099 APValue Val;
1100 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1101 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001102 Result = Val.getInt();
1103 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001104}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001105
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001106bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001107 // Enums are integer constant exprs.
Eli Friedmanee275c82009-12-10 22:29:29 +00001108 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1109 return Success(ECD->getInitVal(), E);
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001110
1111 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +00001112 // In C, they can also be folded, although they are not ICEs.
Douglas Gregor0840cc02009-11-01 20:32:48 +00001113 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1114 == Qualifiers::Const) {
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001115
1116 if (isa<ParmVarDecl>(D))
1117 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1118
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001119 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001120 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedman1d6fb162009-12-03 20:31:57 +00001121 if (APValue *V = VD->getEvaluatedValue()) {
1122 if (V->isInt())
1123 return Success(V->getInt(), E);
1124 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1125 }
1126
1127 if (VD->isEvaluatingValue())
1128 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1129
1130 VD->setEvaluatingValue();
1131
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001132 Expr::EvalResult EResult;
1133 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1134 EResult.Val.isInt()) {
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001135 // Cache the evaluated value in the variable declaration.
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001136 Result = EResult.Val;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001137 VD->setEvaluatedValue(Result);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001138 return true;
1139 }
1140
Eli Friedman1d6fb162009-12-03 20:31:57 +00001141 VD->setEvaluatedValue(APValue());
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001142 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001143 }
1144 }
1145
Chris Lattner7174bf32008-07-12 00:38:25 +00001146 // Otherwise, random variable references are not constants.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001147 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001148}
1149
Chris Lattner86ee2862008-10-06 06:40:35 +00001150/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1151/// as GCC.
1152static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1153 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001154 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001155 enum gcc_type_class {
1156 no_type_class = -1,
1157 void_type_class, integer_type_class, char_type_class,
1158 enumeral_type_class, boolean_type_class,
1159 pointer_type_class, reference_type_class, offset_type_class,
1160 real_type_class, complex_type_class,
1161 function_type_class, method_type_class,
1162 record_type_class, union_type_class,
1163 array_type_class, string_type_class,
1164 lang_type_class
1165 };
Mike Stump11289f42009-09-09 15:08:12 +00001166
1167 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001168 // ideal, however it is what gcc does.
1169 if (E->getNumArgs() == 0)
1170 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001171
Chris Lattner86ee2862008-10-06 06:40:35 +00001172 QualType ArgTy = E->getArg(0)->getType();
1173 if (ArgTy->isVoidType())
1174 return void_type_class;
1175 else if (ArgTy->isEnumeralType())
1176 return enumeral_type_class;
1177 else if (ArgTy->isBooleanType())
1178 return boolean_type_class;
1179 else if (ArgTy->isCharType())
1180 return string_type_class; // gcc doesn't appear to use char_type_class
1181 else if (ArgTy->isIntegerType())
1182 return integer_type_class;
1183 else if (ArgTy->isPointerType())
1184 return pointer_type_class;
1185 else if (ArgTy->isReferenceType())
1186 return reference_type_class;
1187 else if (ArgTy->isRealType())
1188 return real_type_class;
1189 else if (ArgTy->isComplexType())
1190 return complex_type_class;
1191 else if (ArgTy->isFunctionType())
1192 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001193 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001194 return record_type_class;
1195 else if (ArgTy->isUnionType())
1196 return union_type_class;
1197 else if (ArgTy->isArrayType())
1198 return array_type_class;
1199 else if (ArgTy->isUnionType())
1200 return union_type_class;
1201 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1202 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1203 return -1;
1204}
1205
John McCall95007602010-05-10 23:27:23 +00001206/// Retrieves the "underlying object type" of the given expression,
1207/// as used by __builtin_object_size.
1208QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1209 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1210 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1211 return VD->getType();
1212 } else if (isa<CompoundLiteralExpr>(E)) {
1213 return E->getType();
1214 }
1215
1216 return QualType();
1217}
1218
1219bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1220 // TODO: Perhaps we should let LLVM lower this?
1221 LValue Base;
1222 if (!EvaluatePointer(E->getArg(0), Base, Info))
1223 return false;
1224
1225 // If we can prove the base is null, lower to zero now.
1226 const Expr *LVBase = Base.getLValueBase();
1227 if (!LVBase) return Success(0, E);
1228
1229 QualType T = GetObjectType(LVBase);
1230 if (T.isNull() ||
1231 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001232 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001233 T->isVariablyModifiedType() ||
1234 T->isDependentType())
1235 return false;
1236
1237 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1238 CharUnits Offset = Base.getLValueOffset();
1239
1240 if (!Offset.isNegative() && Offset <= Size)
1241 Size -= Offset;
1242 else
1243 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001244 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001245}
1246
Eli Friedmand5c93992010-02-13 00:10:10 +00001247bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001248 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001249 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001250 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001251
1252 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001253 if (TryEvaluateBuiltinObjectSize(E))
1254 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001255
Eric Christopher99469702010-01-19 22:58:35 +00001256 // If evaluating the argument has side-effects we can't determine
1257 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001258 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer0128f662010-01-03 18:18:37 +00001259 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001260 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001261 return Success(0, E);
1262 }
Mike Stump876387b2009-10-27 22:09:17 +00001263
Mike Stump722cedf2009-10-26 18:35:08 +00001264 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1265 }
1266
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001267 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001268 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001269
Anders Carlsson4c76e932008-11-24 04:21:33 +00001270 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001271 // __builtin_constant_p always has one operand: it returns true if that
1272 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001273 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001274
1275 case Builtin::BI__builtin_eh_return_data_regno: {
1276 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1277 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1278 return Success(Operand, E);
1279 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001280
1281 case Builtin::BI__builtin_expect:
1282 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001283
1284 case Builtin::BIstrlen:
1285 case Builtin::BI__builtin_strlen:
1286 // As an extension, we support strlen() and __builtin_strlen() as constant
1287 // expressions when the argument is a string literal.
1288 if (StringLiteral *S
1289 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1290 // The string literal may have embedded null characters. Find the first
1291 // one and truncate there.
1292 llvm::StringRef Str = S->getString();
1293 llvm::StringRef::size_type Pos = Str.find(0);
1294 if (Pos != llvm::StringRef::npos)
1295 Str = Str.substr(0, Pos);
1296
1297 return Success(Str.size(), E);
1298 }
1299
1300 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001301 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001302}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001303
Chris Lattnere13042c2008-07-11 19:10:17 +00001304bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001305 if (E->getOpcode() == BO_Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001306 if (!Visit(E->getRHS()))
1307 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001308
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001309 // If we can't evaluate the LHS, it might have side effects;
1310 // conservatively mark it.
1311 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1312 Info.EvalResult.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001313
Anders Carlsson564730a2008-12-01 02:07:06 +00001314 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001315 }
1316
1317 if (E->isLogicalOp()) {
1318 // These need to be handled specially because the operands aren't
1319 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001320 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001321
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001322 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001323 // We were able to evaluate the LHS, see if we can get away with not
1324 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001325 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001326 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001327
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001328 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001329 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001330 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001331 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001332 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001333 }
1334 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001335 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001336 // We can't evaluate the LHS; however, sometimes the result
1337 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001338 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1339 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001340 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001341 // must have had side effects.
1342 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001343
1344 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001345 }
1346 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001347 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001348
Eli Friedman5a332ea2008-11-13 06:09:17 +00001349 return false;
1350 }
1351
Anders Carlssonacc79812008-11-16 07:17:21 +00001352 QualType LHSTy = E->getLHS()->getType();
1353 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001354
1355 if (LHSTy->isAnyComplexType()) {
1356 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001357 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001358
1359 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1360 return false;
1361
1362 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1363 return false;
1364
1365 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001366 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001367 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001368 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001369 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1370
John McCalle3027922010-08-25 11:45:40 +00001371 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001372 return Success((CR_r == APFloat::cmpEqual &&
1373 CR_i == APFloat::cmpEqual), E);
1374 else {
John McCalle3027922010-08-25 11:45:40 +00001375 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001376 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001377 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001378 CR_r == APFloat::cmpLessThan ||
1379 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001380 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001381 CR_i == APFloat::cmpLessThan ||
1382 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001383 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001384 } else {
John McCalle3027922010-08-25 11:45:40 +00001385 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001386 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1387 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1388 else {
John McCalle3027922010-08-25 11:45:40 +00001389 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001390 "Invalid compex comparison.");
1391 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1392 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1393 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001394 }
1395 }
Mike Stump11289f42009-09-09 15:08:12 +00001396
Anders Carlssonacc79812008-11-16 07:17:21 +00001397 if (LHSTy->isRealFloatingType() &&
1398 RHSTy->isRealFloatingType()) {
1399 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001400
Anders Carlssonacc79812008-11-16 07:17:21 +00001401 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1402 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001403
Anders Carlssonacc79812008-11-16 07:17:21 +00001404 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1405 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001406
Anders Carlssonacc79812008-11-16 07:17:21 +00001407 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001408
Anders Carlssonacc79812008-11-16 07:17:21 +00001409 switch (E->getOpcode()) {
1410 default:
1411 assert(0 && "Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001412 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001413 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001414 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001415 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001416 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001417 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001418 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001419 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001420 E);
John McCalle3027922010-08-25 11:45:40 +00001421 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001422 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001423 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001424 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001425 || CR == APFloat::cmpLessThan
1426 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001427 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001428 }
Mike Stump11289f42009-09-09 15:08:12 +00001429
Eli Friedmana38da572009-04-28 19:17:36 +00001430 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001431 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001432 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001433 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1434 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001435
John McCall45d55e42010-05-07 21:00:08 +00001436 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001437 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1438 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001439
Eli Friedman334046a2009-06-14 02:17:33 +00001440 // Reject any bases from the normal codepath; we special-case comparisons
1441 // to null.
1442 if (LHSValue.getLValueBase()) {
1443 if (!E->isEqualityOp())
1444 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001445 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001446 return false;
1447 bool bres;
1448 if (!EvalPointerValueAsBool(LHSValue, bres))
1449 return false;
John McCalle3027922010-08-25 11:45:40 +00001450 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001451 } else if (RHSValue.getLValueBase()) {
1452 if (!E->isEqualityOp())
1453 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001454 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001455 return false;
1456 bool bres;
1457 if (!EvalPointerValueAsBool(RHSValue, bres))
1458 return false;
John McCalle3027922010-08-25 11:45:40 +00001459 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001460 }
Eli Friedman64004332009-03-23 04:38:34 +00001461
John McCalle3027922010-08-25 11:45:40 +00001462 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001463 QualType Type = E->getLHS()->getType();
1464 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001465
Ken Dyck02990832010-01-15 12:37:54 +00001466 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001467 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001468 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001469
Ken Dyck02990832010-01-15 12:37:54 +00001470 CharUnits Diff = LHSValue.getLValueOffset() -
1471 RHSValue.getLValueOffset();
1472 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001473 }
1474 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001475 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001476 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001477 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001478 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1479 }
1480 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001481 }
1482 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001483 if (!LHSTy->isIntegralOrEnumerationType() ||
1484 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001485 // We can't continue from here for non-integral types, and they
1486 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001487 return false;
1488 }
1489
Anders Carlsson9c181652008-07-08 14:35:21 +00001490 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001491 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001492 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001493
Eli Friedman94c25c62009-03-24 01:14:50 +00001494 APValue RHSVal;
1495 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001496 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001497
1498 // Handle cases like (unsigned long)&a + 4.
1499 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001500 CharUnits Offset = Result.getLValueOffset();
1501 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1502 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001503 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001504 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001505 else
Ken Dyck02990832010-01-15 12:37:54 +00001506 Offset -= AdditionalOffset;
1507 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001508 return true;
1509 }
1510
1511 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001512 if (E->getOpcode() == BO_Add &&
Eli Friedman94c25c62009-03-24 01:14:50 +00001513 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001514 CharUnits Offset = RHSVal.getLValueOffset();
1515 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1516 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001517 return true;
1518 }
1519
1520 // All the following cases expect both operands to be an integer
1521 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001522 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001523
Eli Friedman94c25c62009-03-24 01:14:50 +00001524 APSInt& RHS = RHSVal.getInt();
1525
Anders Carlsson9c181652008-07-08 14:35:21 +00001526 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001527 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001528 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001529 case BO_Mul: return Success(Result.getInt() * RHS, E);
1530 case BO_Add: return Success(Result.getInt() + RHS, E);
1531 case BO_Sub: return Success(Result.getInt() - RHS, E);
1532 case BO_And: return Success(Result.getInt() & RHS, E);
1533 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1534 case BO_Or: return Success(Result.getInt() | RHS, E);
1535 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001536 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001537 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001538 return Success(Result.getInt() / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001539 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001540 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001541 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001542 return Success(Result.getInt() % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001543 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001544 // During constant-folding, a negative shift is an opposite shift.
1545 if (RHS.isSigned() && RHS.isNegative()) {
1546 RHS = -RHS;
1547 goto shift_right;
1548 }
1549
1550 shift_left:
1551 unsigned SA
1552 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001553 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001554 }
John McCalle3027922010-08-25 11:45:40 +00001555 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001556 // During constant-folding, a negative shift is an opposite shift.
1557 if (RHS.isSigned() && RHS.isNegative()) {
1558 RHS = -RHS;
1559 goto shift_left;
1560 }
1561
1562 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001563 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001564 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1565 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001566 }
Mike Stump11289f42009-09-09 15:08:12 +00001567
John McCalle3027922010-08-25 11:45:40 +00001568 case BO_LT: return Success(Result.getInt() < RHS, E);
1569 case BO_GT: return Success(Result.getInt() > RHS, E);
1570 case BO_LE: return Success(Result.getInt() <= RHS, E);
1571 case BO_GE: return Success(Result.getInt() >= RHS, E);
1572 case BO_EQ: return Success(Result.getInt() == RHS, E);
1573 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001574 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001575}
1576
John McCallc07a0c72011-02-17 10:25:35 +00001577bool IntExprEvaluator::
1578VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
1579 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
1580 if (opaque.hasError()) return false;
1581
1582 bool cond;
1583 if (!HandleConversionToBool(e->getCond(), cond, Info))
1584 return false;
1585
1586 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
1587}
1588
Nuno Lopes42042612008-11-16 19:28:31 +00001589bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes527b5a62008-11-16 22:06:39 +00001590 bool Cond;
1591 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopes42042612008-11-16 19:28:31 +00001592 return false;
1593
Nuno Lopes527b5a62008-11-16 22:06:39 +00001594 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopes42042612008-11-16 19:28:31 +00001595}
1596
Ken Dyck160146e2010-01-27 17:10:57 +00001597CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001598 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1599 // the result is the size of the referenced type."
1600 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1601 // result shall be the alignment of the referenced type."
1602 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1603 T = Ref->getPointeeType();
1604
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001605 // __alignof is defined to return the preferred alignment.
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001606 return Info.Ctx.toCharUnitsFromBits(
1607 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001608}
1609
Ken Dyck160146e2010-01-27 17:10:57 +00001610CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001611 E = E->IgnoreParens();
1612
1613 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001614 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001615 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001616 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1617 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001618
Chris Lattner68061312009-01-24 21:53:27 +00001619 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001620 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1621 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001622
Chris Lattner24aeeab2009-01-24 21:09:06 +00001623 return GetAlignOfType(E->getType());
1624}
1625
1626
Peter Collingbournee190dee2011-03-11 19:24:49 +00001627/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1628/// a result as the expression's type.
1629bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1630 const UnaryExprOrTypeTraitExpr *E) {
1631 switch(E->getKind()) {
1632 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001633 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00001634 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001635 else
Ken Dyckdbc01912011-03-11 02:13:43 +00001636 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001637 }
Eli Friedman64004332009-03-23 04:38:34 +00001638
Peter Collingbournee190dee2011-03-11 19:24:49 +00001639 case UETT_VecStep: {
1640 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00001641
Peter Collingbournee190dee2011-03-11 19:24:49 +00001642 if (Ty->isVectorType()) {
1643 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00001644
Peter Collingbournee190dee2011-03-11 19:24:49 +00001645 // The vec_step built-in functions that take a 3-component
1646 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1647 if (n == 3)
1648 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001649
Peter Collingbournee190dee2011-03-11 19:24:49 +00001650 return Success(n, E);
1651 } else
1652 return Success(1, E);
1653 }
1654
1655 case UETT_SizeOf: {
1656 QualType SrcTy = E->getTypeOfArgument();
1657 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1658 // the result is the size of the referenced type."
1659 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1660 // result shall be the alignment of the referenced type."
1661 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1662 SrcTy = Ref->getPointeeType();
1663
1664 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1665 // extension.
1666 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1667 return Success(1, E);
1668
1669 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1670 if (!SrcTy->isConstantSizeType())
1671 return false;
1672
1673 // Get information about the size.
1674 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1675 }
1676 }
1677
1678 llvm_unreachable("unknown expr/type trait");
1679 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001680}
1681
Douglas Gregor882211c2010-04-28 22:16:22 +00001682bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1683 CharUnits Result;
1684 unsigned n = E->getNumComponents();
1685 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1686 if (n == 0)
1687 return false;
1688 QualType CurrentType = E->getTypeSourceInfo()->getType();
1689 for (unsigned i = 0; i != n; ++i) {
1690 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1691 switch (ON.getKind()) {
1692 case OffsetOfExpr::OffsetOfNode::Array: {
1693 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1694 APSInt IdxResult;
1695 if (!EvaluateInteger(Idx, IdxResult, Info))
1696 return false;
1697 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1698 if (!AT)
1699 return false;
1700 CurrentType = AT->getElementType();
1701 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1702 Result += IdxResult.getSExtValue() * ElementSize;
1703 break;
1704 }
1705
1706 case OffsetOfExpr::OffsetOfNode::Field: {
1707 FieldDecl *MemberDecl = ON.getField();
1708 const RecordType *RT = CurrentType->getAs<RecordType>();
1709 if (!RT)
1710 return false;
1711 RecordDecl *RD = RT->getDecl();
1712 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00001713 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00001714 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001715 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00001716 CurrentType = MemberDecl->getType().getNonReferenceType();
1717 break;
1718 }
1719
1720 case OffsetOfExpr::OffsetOfNode::Identifier:
1721 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001722 return false;
1723
1724 case OffsetOfExpr::OffsetOfNode::Base: {
1725 CXXBaseSpecifier *BaseSpec = ON.getBase();
1726 if (BaseSpec->isVirtual())
1727 return false;
1728
1729 // Find the layout of the class whose base we are looking into.
1730 const RecordType *RT = CurrentType->getAs<RecordType>();
1731 if (!RT)
1732 return false;
1733 RecordDecl *RD = RT->getDecl();
1734 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1735
1736 // Find the base class itself.
1737 CurrentType = BaseSpec->getType();
1738 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1739 if (!BaseRT)
1740 return false;
1741
1742 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00001743 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00001744 break;
1745 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001746 }
1747 }
Ken Dyckdbc01912011-03-11 02:13:43 +00001748 return Success(Result, E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001749}
1750
Chris Lattnere13042c2008-07-11 19:10:17 +00001751bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001752 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001753 // LNot's operand isn't necessarily an integer, so we handle it specially.
1754 bool bres;
1755 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1756 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001757 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001758 }
1759
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001760 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00001761 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001762 return false;
1763
Chris Lattnercdf34e72008-07-11 22:52:41 +00001764 // Get the operand value into 'Result'.
1765 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001766 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001767
Chris Lattnerf09ad162008-07-11 22:15:16 +00001768 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001769 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001770 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1771 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001772 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001773 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001774 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1775 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001776 return true;
John McCalle3027922010-08-25 11:45:40 +00001777 case UO_Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001778 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001779 return true;
John McCalle3027922010-08-25 11:45:40 +00001780 case UO_Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001781 if (!Result.isInt()) return false;
1782 return Success(-Result.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00001783 case UO_Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001784 if (!Result.isInt()) return false;
1785 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001786 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001787}
Mike Stump11289f42009-09-09 15:08:12 +00001788
Chris Lattner477c4be2008-07-12 01:15:53 +00001789/// HandleCast - This is used to evaluate implicit or explicit casts where the
1790/// result type is integer.
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001791bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001792 Expr *SubExpr = E->getSubExpr();
1793 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001794 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001795
Eli Friedmanc757de22011-03-25 00:43:55 +00001796 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00001797 case CK_BaseToDerived:
1798 case CK_DerivedToBase:
1799 case CK_UncheckedDerivedToBase:
1800 case CK_Dynamic:
1801 case CK_ToUnion:
1802 case CK_ArrayToPointerDecay:
1803 case CK_FunctionToPointerDecay:
1804 case CK_NullToPointer:
1805 case CK_NullToMemberPointer:
1806 case CK_BaseToDerivedMemberPointer:
1807 case CK_DerivedToBaseMemberPointer:
1808 case CK_ConstructorConversion:
1809 case CK_IntegralToPointer:
1810 case CK_ToVoid:
1811 case CK_VectorSplat:
1812 case CK_IntegralToFloating:
1813 case CK_FloatingCast:
1814 case CK_AnyPointerToObjCPointerCast:
1815 case CK_AnyPointerToBlockPointerCast:
1816 case CK_ObjCObjectLValueCast:
1817 case CK_FloatingRealToComplex:
1818 case CK_FloatingComplexToReal:
1819 case CK_FloatingComplexCast:
1820 case CK_FloatingComplexToIntegralComplex:
1821 case CK_IntegralRealToComplex:
1822 case CK_IntegralComplexCast:
1823 case CK_IntegralComplexToFloatingComplex:
1824 llvm_unreachable("invalid cast kind for integral value");
1825
Eli Friedman9faf2f92011-03-25 19:07:11 +00001826 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001827 case CK_Dependent:
1828 case CK_GetObjCProperty:
1829 case CK_LValueBitCast:
1830 case CK_UserDefinedConversion:
1831 return false;
1832
1833 case CK_LValueToRValue:
1834 case CK_NoOp:
1835 return Visit(E->getSubExpr());
1836
1837 case CK_MemberPointerToBoolean:
1838 case CK_PointerToBoolean:
1839 case CK_IntegralToBoolean:
1840 case CK_FloatingToBoolean:
1841 case CK_FloatingComplexToBoolean:
1842 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00001843 bool BoolResult;
1844 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1845 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001846 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001847 }
1848
Eli Friedmanc757de22011-03-25 00:43:55 +00001849 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00001850 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001851 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001852
Eli Friedman742421e2009-02-20 01:15:07 +00001853 if (!Result.isInt()) {
1854 // Only allow casts of lvalues if they are lossless.
1855 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1856 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001857
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001858 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001859 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001860 }
Mike Stump11289f42009-09-09 15:08:12 +00001861
Eli Friedmanc757de22011-03-25 00:43:55 +00001862 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00001863 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001864 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001865 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001866
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001867 if (LV.getLValueBase()) {
1868 // Only allow based lvalue casts if they are lossless.
1869 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1870 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001871
John McCall45d55e42010-05-07 21:00:08 +00001872 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001873 return true;
1874 }
1875
Ken Dyck02990832010-01-15 12:37:54 +00001876 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1877 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001878 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001879 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001880
Eli Friedmanc757de22011-03-25 00:43:55 +00001881 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00001882 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001883 if (!EvaluateComplex(SubExpr, C, Info))
1884 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00001885 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001886 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001887
Eli Friedmanc757de22011-03-25 00:43:55 +00001888 case CK_FloatingToIntegral: {
1889 APFloat F(0.0);
1890 if (!EvaluateFloat(SubExpr, F, Info))
1891 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00001892
Eli Friedmanc757de22011-03-25 00:43:55 +00001893 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1894 }
1895 }
Mike Stump11289f42009-09-09 15:08:12 +00001896
Eli Friedmanc757de22011-03-25 00:43:55 +00001897 llvm_unreachable("unknown cast resulting in integral value");
1898 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001899}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001900
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001901bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1902 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001903 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001904 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1905 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1906 return Success(LV.getComplexIntReal(), E);
1907 }
1908
1909 return Visit(E->getSubExpr());
1910}
1911
Eli Friedman4e7a2412009-02-27 04:45:43 +00001912bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001913 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001914 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001915 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1916 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1917 return Success(LV.getComplexIntImag(), E);
1918 }
1919
Eli Friedman4e7a2412009-02-27 04:45:43 +00001920 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1921 Info.EvalResult.HasSideEffects = true;
1922 return Success(0, E);
1923}
1924
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001925bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1926 return Success(E->getPackLength(), E);
1927}
1928
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001929bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1930 return Success(E->getValue(), E);
1931}
1932
Chris Lattner05706e882008-07-11 18:11:29 +00001933//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00001934// Float Evaluation
1935//===----------------------------------------------------------------------===//
1936
1937namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001938class FloatExprEvaluator
Eli Friedman24c01542008-08-22 00:06:13 +00001939 : public StmtVisitor<FloatExprEvaluator, bool> {
1940 EvalInfo &Info;
1941 APFloat &Result;
1942public:
1943 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1944 : Info(info), Result(result) {}
1945
1946 bool VisitStmt(Stmt *S) {
1947 return false;
1948 }
1949
1950 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbourne91147592011-04-15 00:35:48 +00001951 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
1952 return Visit(E->getResultExpr());
1953 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001954 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001955
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001956 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001957 bool VisitBinaryOperator(const BinaryOperator *E);
1958 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001959 bool VisitCastExpr(CastExpr *E);
Douglas Gregor747eb782010-07-08 06:14:04 +00001960 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedmanf3da3342009-12-04 02:12:53 +00001961 bool VisitConditionalOperator(ConditionalOperator *E);
John McCallc07a0c72011-02-17 10:25:35 +00001962 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00001963
Eli Friedman449fe542009-03-23 04:56:01 +00001964 bool VisitChooseExpr(const ChooseExpr *E)
1965 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1966 bool VisitUnaryExtension(const UnaryOperator *E)
1967 { return Visit(E->getSubExpr()); }
John McCallb1fb0d32010-05-07 22:08:54 +00001968 bool VisitUnaryReal(const UnaryOperator *E);
1969 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00001970
John McCalla2fabff2010-10-09 01:34:31 +00001971 bool VisitDeclRefExpr(const DeclRefExpr *E);
1972
John McCallc07a0c72011-02-17 10:25:35 +00001973 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
1974 const APValue *value = Info.getOpaqueValue(e);
1975 if (!value)
1976 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
1977 Result = value->getFloat();
1978 return true;
1979 }
1980
John McCallb1fb0d32010-05-07 22:08:54 +00001981 // FIXME: Missing: array subscript of vector, member of vector,
1982 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00001983};
1984} // end anonymous namespace
1985
1986static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00001987 assert(E->getType()->isRealFloatingType());
Eli Friedman24c01542008-08-22 00:06:13 +00001988 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1989}
1990
Jay Foad39c79802011-01-12 09:06:06 +00001991static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00001992 QualType ResultTy,
1993 const Expr *Arg,
1994 bool SNaN,
1995 llvm::APFloat &Result) {
1996 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1997 if (!S) return false;
1998
1999 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2000
2001 llvm::APInt fill;
2002
2003 // Treat empty strings as if they were zero.
2004 if (S->getString().empty())
2005 fill = llvm::APInt(32, 0);
2006 else if (S->getString().getAsInteger(0, fill))
2007 return false;
2008
2009 if (SNaN)
2010 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2011 else
2012 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2013 return true;
2014}
2015
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002016bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002017 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner37346e02008-10-06 05:53:16 +00002018 default: return false;
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002019 case Builtin::BI__builtin_huge_val:
2020 case Builtin::BI__builtin_huge_valf:
2021 case Builtin::BI__builtin_huge_vall:
2022 case Builtin::BI__builtin_inf:
2023 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002024 case Builtin::BI__builtin_infl: {
2025 const llvm::fltSemantics &Sem =
2026 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002027 Result = llvm::APFloat::getInf(Sem);
2028 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002029 }
Mike Stump11289f42009-09-09 15:08:12 +00002030
John McCall16291492010-02-28 13:00:19 +00002031 case Builtin::BI__builtin_nans:
2032 case Builtin::BI__builtin_nansf:
2033 case Builtin::BI__builtin_nansl:
2034 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2035 true, Result);
2036
Chris Lattner0b7282e2008-10-06 06:31:58 +00002037 case Builtin::BI__builtin_nan:
2038 case Builtin::BI__builtin_nanf:
2039 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002040 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002041 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002042 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2043 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002044
2045 case Builtin::BI__builtin_fabs:
2046 case Builtin::BI__builtin_fabsf:
2047 case Builtin::BI__builtin_fabsl:
2048 if (!EvaluateFloat(E->getArg(0), Result, Info))
2049 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002050
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002051 if (Result.isNegative())
2052 Result.changeSign();
2053 return true;
2054
Mike Stump11289f42009-09-09 15:08:12 +00002055 case Builtin::BI__builtin_copysign:
2056 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002057 case Builtin::BI__builtin_copysignl: {
2058 APFloat RHS(0.);
2059 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2060 !EvaluateFloat(E->getArg(1), RHS, Info))
2061 return false;
2062 Result.copySign(RHS);
2063 return true;
2064 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002065 }
2066}
2067
John McCalla2fabff2010-10-09 01:34:31 +00002068bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2069 const Decl *D = E->getDecl();
2070 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2071 const VarDecl *VD = cast<VarDecl>(D);
2072
2073 // Require the qualifiers to be const and not volatile.
2074 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2075 if (!T.isConstQualified() || T.isVolatileQualified())
2076 return false;
2077
2078 const Expr *Init = VD->getAnyInitializer();
2079 if (!Init) return false;
2080
2081 if (APValue *V = VD->getEvaluatedValue()) {
2082 if (V->isFloat()) {
2083 Result = V->getFloat();
2084 return true;
2085 }
2086 return false;
2087 }
2088
2089 if (VD->isEvaluatingValue())
2090 return false;
2091
2092 VD->setEvaluatingValue();
2093
2094 Expr::EvalResult InitResult;
2095 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2096 InitResult.Val.isFloat()) {
2097 // Cache the evaluated value in the variable declaration.
2098 Result = InitResult.Val.getFloat();
2099 VD->setEvaluatedValue(InitResult.Val);
2100 return true;
2101 }
2102
2103 VD->setEvaluatedValue(APValue());
2104 return false;
2105}
2106
John McCallb1fb0d32010-05-07 22:08:54 +00002107bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002108 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2109 ComplexValue CV;
2110 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2111 return false;
2112 Result = CV.FloatReal;
2113 return true;
2114 }
2115
2116 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002117}
2118
2119bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002120 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2121 ComplexValue CV;
2122 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2123 return false;
2124 Result = CV.FloatImag;
2125 return true;
2126 }
2127
2128 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2129 Info.EvalResult.HasSideEffects = true;
2130 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2131 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002132 return true;
2133}
2134
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002135bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002136 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002137 return false;
2138
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002139 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2140 return false;
2141
2142 switch (E->getOpcode()) {
2143 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002144 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002145 return true;
John McCalle3027922010-08-25 11:45:40 +00002146 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002147 Result.changeSign();
2148 return true;
2149 }
2150}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002151
Eli Friedman24c01542008-08-22 00:06:13 +00002152bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002153 if (E->getOpcode() == BO_Comma) {
Eli Friedman141fbf32009-11-16 04:25:37 +00002154 if (!EvaluateFloat(E->getRHS(), Result, Info))
2155 return false;
2156
2157 // If we can't evaluate the LHS, it might have side effects;
2158 // conservatively mark it.
2159 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2160 Info.EvalResult.HasSideEffects = true;
2161
2162 return true;
2163 }
2164
Anders Carlssona5df61a2010-10-31 01:21:47 +00002165 // We can't evaluate pointer-to-member operations.
2166 if (E->isPtrMemOp())
2167 return false;
2168
Eli Friedman24c01542008-08-22 00:06:13 +00002169 // FIXME: Diagnostics? I really don't understand how the warnings
2170 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002171 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002172 if (!EvaluateFloat(E->getLHS(), Result, Info))
2173 return false;
2174 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2175 return false;
2176
2177 switch (E->getOpcode()) {
2178 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002179 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002180 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2181 return true;
John McCalle3027922010-08-25 11:45:40 +00002182 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002183 Result.add(RHS, APFloat::rmNearestTiesToEven);
2184 return true;
John McCalle3027922010-08-25 11:45:40 +00002185 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002186 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2187 return true;
John McCalle3027922010-08-25 11:45:40 +00002188 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002189 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2190 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002191 }
2192}
2193
2194bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2195 Result = E->getValue();
2196 return true;
2197}
2198
Eli Friedman9a156e52008-11-12 09:44:48 +00002199bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2200 Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002201
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002202 switch (E->getCastKind()) {
2203 default:
2204 return false;
2205
2206 case CK_LValueToRValue:
2207 case CK_NoOp:
2208 return Visit(SubExpr);
2209
2210 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002211 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002212 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002213 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002214 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002215 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002216 return true;
2217 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002218
2219 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002220 if (!Visit(SubExpr))
2221 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002222 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2223 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002224 return true;
2225 }
John McCalld7646252010-11-14 08:17:51 +00002226
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002227 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002228 ComplexValue V;
2229 if (!EvaluateComplex(SubExpr, V, Info))
2230 return false;
2231 Result = V.getComplexFloatReal();
2232 return true;
2233 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002234 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002235
2236 return false;
2237}
2238
Douglas Gregor747eb782010-07-08 06:14:04 +00002239bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +00002240 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2241 return true;
2242}
2243
John McCallc07a0c72011-02-17 10:25:35 +00002244bool FloatExprEvaluator::
2245VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
2246 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2247 if (opaque.hasError()) return false;
2248
2249 bool cond;
2250 if (!HandleConversionToBool(e->getCond(), cond, Info))
2251 return false;
2252
2253 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2254}
2255
Eli Friedmanf3da3342009-12-04 02:12:53 +00002256bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2257 bool Cond;
2258 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2259 return false;
2260
2261 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2262}
2263
Eli Friedman24c01542008-08-22 00:06:13 +00002264//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002265// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002266//===----------------------------------------------------------------------===//
2267
2268namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002269class ComplexExprEvaluator
John McCall93d91dc2010-05-07 17:22:02 +00002270 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson537969c2008-11-16 20:27:53 +00002271 EvalInfo &Info;
John McCall93d91dc2010-05-07 17:22:02 +00002272 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002273
Anders Carlsson537969c2008-11-16 20:27:53 +00002274public:
John McCall93d91dc2010-05-07 17:22:02 +00002275 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2276 : Info(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002277
Anders Carlsson537969c2008-11-16 20:27:53 +00002278 //===--------------------------------------------------------------------===//
2279 // Visitor Methods
2280 //===--------------------------------------------------------------------===//
2281
John McCall93d91dc2010-05-07 17:22:02 +00002282 bool VisitStmt(Stmt *S) {
2283 return false;
Anders Carlsson537969c2008-11-16 20:27:53 +00002284 }
Mike Stump11289f42009-09-09 15:08:12 +00002285
John McCall93d91dc2010-05-07 17:22:02 +00002286 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbourne91147592011-04-15 00:35:48 +00002287 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
2288 return Visit(E->getResultExpr());
2289 }
Anders Carlsson537969c2008-11-16 20:27:53 +00002290
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002291 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002292
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002293 bool VisitCastExpr(CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002294
John McCall93d91dc2010-05-07 17:22:02 +00002295 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002296 bool VisitUnaryOperator(const UnaryOperator *E);
2297 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCallc07a0c72011-02-17 10:25:35 +00002298 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
John McCall93d91dc2010-05-07 17:22:02 +00002299 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman449fe542009-03-23 04:56:01 +00002300 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCall93d91dc2010-05-07 17:22:02 +00002301 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman449fe542009-03-23 04:56:01 +00002302 { return Visit(E->getSubExpr()); }
John McCallc07a0c72011-02-17 10:25:35 +00002303 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
2304 const APValue *value = Info.getOpaqueValue(e);
2305 if (!value)
2306 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
2307 Result.setFrom(*value);
2308 return true;
2309 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002310 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002311};
2312} // end anonymous namespace
2313
John McCall93d91dc2010-05-07 17:22:02 +00002314static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2315 EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002316 assert(E->getType()->isAnyComplexType());
John McCall93d91dc2010-05-07 17:22:02 +00002317 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson537969c2008-11-16 20:27:53 +00002318}
2319
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002320bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2321 Expr* SubExpr = E->getSubExpr();
2322
2323 if (SubExpr->getType()->isRealFloatingType()) {
2324 Result.makeComplexFloat();
2325 APFloat &Imag = Result.FloatImag;
2326 if (!EvaluateFloat(SubExpr, Imag, Info))
2327 return false;
2328
2329 Result.FloatReal = APFloat(Imag.getSemantics());
2330 return true;
2331 } else {
2332 assert(SubExpr->getType()->isIntegerType() &&
2333 "Unexpected imaginary literal.");
2334
2335 Result.makeComplexInt();
2336 APSInt &Imag = Result.IntImag;
2337 if (!EvaluateInteger(SubExpr, Imag, Info))
2338 return false;
2339
2340 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2341 return true;
2342 }
2343}
2344
2345bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002346
John McCallfcef3cf2010-12-14 17:51:41 +00002347 switch (E->getCastKind()) {
2348 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002349 case CK_BaseToDerived:
2350 case CK_DerivedToBase:
2351 case CK_UncheckedDerivedToBase:
2352 case CK_Dynamic:
2353 case CK_ToUnion:
2354 case CK_ArrayToPointerDecay:
2355 case CK_FunctionToPointerDecay:
2356 case CK_NullToPointer:
2357 case CK_NullToMemberPointer:
2358 case CK_BaseToDerivedMemberPointer:
2359 case CK_DerivedToBaseMemberPointer:
2360 case CK_MemberPointerToBoolean:
2361 case CK_ConstructorConversion:
2362 case CK_IntegralToPointer:
2363 case CK_PointerToIntegral:
2364 case CK_PointerToBoolean:
2365 case CK_ToVoid:
2366 case CK_VectorSplat:
2367 case CK_IntegralCast:
2368 case CK_IntegralToBoolean:
2369 case CK_IntegralToFloating:
2370 case CK_FloatingToIntegral:
2371 case CK_FloatingToBoolean:
2372 case CK_FloatingCast:
2373 case CK_AnyPointerToObjCPointerCast:
2374 case CK_AnyPointerToBlockPointerCast:
2375 case CK_ObjCObjectLValueCast:
2376 case CK_FloatingComplexToReal:
2377 case CK_FloatingComplexToBoolean:
2378 case CK_IntegralComplexToReal:
2379 case CK_IntegralComplexToBoolean:
2380 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002381
John McCallfcef3cf2010-12-14 17:51:41 +00002382 case CK_LValueToRValue:
2383 case CK_NoOp:
2384 return Visit(E->getSubExpr());
2385
2386 case CK_Dependent:
2387 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002388 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002389 case CK_UserDefinedConversion:
2390 return false;
2391
2392 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002393 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002394 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002395 return false;
2396
John McCallfcef3cf2010-12-14 17:51:41 +00002397 Result.makeComplexFloat();
2398 Result.FloatImag = APFloat(Real.getSemantics());
2399 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002400 }
2401
John McCallfcef3cf2010-12-14 17:51:41 +00002402 case CK_FloatingComplexCast: {
2403 if (!Visit(E->getSubExpr()))
2404 return false;
2405
2406 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2407 QualType From
2408 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2409
2410 Result.FloatReal
2411 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2412 Result.FloatImag
2413 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2414 return true;
2415 }
2416
2417 case CK_FloatingComplexToIntegralComplex: {
2418 if (!Visit(E->getSubExpr()))
2419 return false;
2420
2421 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2422 QualType From
2423 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2424 Result.makeComplexInt();
2425 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2426 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2427 return true;
2428 }
2429
2430 case CK_IntegralRealToComplex: {
2431 APSInt &Real = Result.IntReal;
2432 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2433 return false;
2434
2435 Result.makeComplexInt();
2436 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2437 return true;
2438 }
2439
2440 case CK_IntegralComplexCast: {
2441 if (!Visit(E->getSubExpr()))
2442 return false;
2443
2444 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2445 QualType From
2446 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2447
2448 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2449 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2450 return true;
2451 }
2452
2453 case CK_IntegralComplexToFloatingComplex: {
2454 if (!Visit(E->getSubExpr()))
2455 return false;
2456
2457 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2458 QualType From
2459 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2460 Result.makeComplexFloat();
2461 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2462 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2463 return true;
2464 }
2465 }
2466
2467 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002468 return false;
2469}
2470
John McCall93d91dc2010-05-07 17:22:02 +00002471bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002472 if (E->getOpcode() == BO_Comma) {
2473 if (!Visit(E->getRHS()))
2474 return false;
2475
2476 // If we can't evaluate the LHS, it might have side effects;
2477 // conservatively mark it.
2478 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2479 Info.EvalResult.HasSideEffects = true;
2480
2481 return true;
2482 }
John McCall93d91dc2010-05-07 17:22:02 +00002483 if (!Visit(E->getLHS()))
2484 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002485
John McCall93d91dc2010-05-07 17:22:02 +00002486 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002487 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002488 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002489
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002490 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2491 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002492 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002493 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002494 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002495 if (Result.isComplexFloat()) {
2496 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2497 APFloat::rmNearestTiesToEven);
2498 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2499 APFloat::rmNearestTiesToEven);
2500 } else {
2501 Result.getComplexIntReal() += RHS.getComplexIntReal();
2502 Result.getComplexIntImag() += RHS.getComplexIntImag();
2503 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002504 break;
John McCalle3027922010-08-25 11:45:40 +00002505 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002506 if (Result.isComplexFloat()) {
2507 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2508 APFloat::rmNearestTiesToEven);
2509 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2510 APFloat::rmNearestTiesToEven);
2511 } else {
2512 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2513 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2514 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002515 break;
John McCalle3027922010-08-25 11:45:40 +00002516 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002517 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002518 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002519 APFloat &LHS_r = LHS.getComplexFloatReal();
2520 APFloat &LHS_i = LHS.getComplexFloatImag();
2521 APFloat &RHS_r = RHS.getComplexFloatReal();
2522 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002523
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002524 APFloat Tmp = LHS_r;
2525 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2526 Result.getComplexFloatReal() = Tmp;
2527 Tmp = LHS_i;
2528 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2529 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2530
2531 Tmp = LHS_r;
2532 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2533 Result.getComplexFloatImag() = Tmp;
2534 Tmp = LHS_i;
2535 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2536 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2537 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002538 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002539 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002540 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2541 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002542 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002543 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2544 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2545 }
2546 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002547 case BO_Div:
2548 if (Result.isComplexFloat()) {
2549 ComplexValue LHS = Result;
2550 APFloat &LHS_r = LHS.getComplexFloatReal();
2551 APFloat &LHS_i = LHS.getComplexFloatImag();
2552 APFloat &RHS_r = RHS.getComplexFloatReal();
2553 APFloat &RHS_i = RHS.getComplexFloatImag();
2554 APFloat &Res_r = Result.getComplexFloatReal();
2555 APFloat &Res_i = Result.getComplexFloatImag();
2556
2557 APFloat Den = RHS_r;
2558 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2559 APFloat Tmp = RHS_i;
2560 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2561 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2562
2563 Res_r = LHS_r;
2564 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2565 Tmp = LHS_i;
2566 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2567 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2568 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2569
2570 Res_i = LHS_i;
2571 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2572 Tmp = LHS_r;
2573 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2574 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2575 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2576 } else {
2577 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2578 // FIXME: what about diagnostics?
2579 return false;
2580 }
2581 ComplexValue LHS = Result;
2582 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2583 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2584 Result.getComplexIntReal() =
2585 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2586 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2587 Result.getComplexIntImag() =
2588 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2589 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2590 }
2591 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002592 }
2593
John McCall93d91dc2010-05-07 17:22:02 +00002594 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002595}
2596
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002597bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2598 // Get the operand value into 'Result'.
2599 if (!Visit(E->getSubExpr()))
2600 return false;
2601
2602 switch (E->getOpcode()) {
2603 default:
2604 // FIXME: what about diagnostics?
2605 return false;
2606 case UO_Extension:
2607 return true;
2608 case UO_Plus:
2609 // The result is always just the subexpr.
2610 return true;
2611 case UO_Minus:
2612 if (Result.isComplexFloat()) {
2613 Result.getComplexFloatReal().changeSign();
2614 Result.getComplexFloatImag().changeSign();
2615 }
2616 else {
2617 Result.getComplexIntReal() = -Result.getComplexIntReal();
2618 Result.getComplexIntImag() = -Result.getComplexIntImag();
2619 }
2620 return true;
2621 case UO_Not:
2622 if (Result.isComplexFloat())
2623 Result.getComplexFloatImag().changeSign();
2624 else
2625 Result.getComplexIntImag() = -Result.getComplexIntImag();
2626 return true;
2627 }
2628}
2629
John McCallc07a0c72011-02-17 10:25:35 +00002630bool ComplexExprEvaluator::
2631VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
2632 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2633 if (opaque.hasError()) return false;
2634
2635 bool cond;
2636 if (!HandleConversionToBool(e->getCond(), cond, Info))
2637 return false;
2638
2639 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2640}
2641
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002642bool ComplexExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
2643 bool Cond;
2644 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2645 return false;
2646
2647 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2648}
2649
Anders Carlsson537969c2008-11-16 20:27:53 +00002650//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002651// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002652//===----------------------------------------------------------------------===//
2653
John McCallc07a0c72011-02-17 10:25:35 +00002654static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00002655 if (E->getType()->isVectorType()) {
2656 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002657 return false;
John McCall45d55e42010-05-07 21:00:08 +00002658 } else if (E->getType()->isIntegerType()) {
2659 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002660 return false;
John McCallc07a0c72011-02-17 10:25:35 +00002661 if (Info.EvalResult.Val.isLValue() &&
2662 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall11086fc2010-07-07 05:08:32 +00002663 return false;
John McCall45d55e42010-05-07 21:00:08 +00002664 } else if (E->getType()->hasPointerRepresentation()) {
2665 LValue LV;
2666 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002667 return false;
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002668 if (!IsGlobalLValue(LV.Base))
John McCall95007602010-05-10 23:27:23 +00002669 return false;
John McCall45d55e42010-05-07 21:00:08 +00002670 LV.moveInto(Info.EvalResult.Val);
2671 } else if (E->getType()->isRealFloatingType()) {
2672 llvm::APFloat F(0.0);
2673 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002674 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002675
John McCall45d55e42010-05-07 21:00:08 +00002676 Info.EvalResult.Val = APValue(F);
2677 } else if (E->getType()->isAnyComplexType()) {
2678 ComplexValue C;
2679 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002680 return false;
John McCall45d55e42010-05-07 21:00:08 +00002681 C.moveInto(Info.EvalResult.Val);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002682 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002683 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002684
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002685 return true;
2686}
2687
John McCallc07a0c72011-02-17 10:25:35 +00002688/// Evaluate - Return true if this is a constant which we can fold using
2689/// any crazy technique (that has nothing to do with language standards) that
2690/// we want to. If this function returns true, it returns the folded constant
2691/// in Result.
2692bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2693 EvalInfo Info(Ctx, Result);
2694 return ::Evaluate(Info, this);
2695}
2696
Jay Foad39c79802011-01-12 09:06:06 +00002697bool Expr::EvaluateAsBooleanCondition(bool &Result,
2698 const ASTContext &Ctx) const {
John McCall1be1c632010-01-05 23:42:56 +00002699 EvalResult Scratch;
2700 EvalInfo Info(Ctx, Scratch);
2701
2702 return HandleConversionToBool(this, Result, Info);
2703}
2704
Jay Foad39c79802011-01-12 09:06:06 +00002705bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002706 EvalInfo Info(Ctx, Result);
2707
John McCall45d55e42010-05-07 21:00:08 +00002708 LValue LV;
John McCall95007602010-05-10 23:27:23 +00002709 if (EvaluateLValue(this, LV, Info) &&
2710 !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002711 IsGlobalLValue(LV.Base)) {
2712 LV.moveInto(Result.Val);
2713 return true;
2714 }
2715 return false;
2716}
2717
Jay Foad39c79802011-01-12 09:06:06 +00002718bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2719 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002720 EvalInfo Info(Ctx, Result);
2721
2722 LValue LV;
2723 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00002724 LV.moveInto(Result.Val);
2725 return true;
2726 }
2727 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00002728}
2729
Chris Lattner67d7b922008-11-16 21:24:15 +00002730/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002731/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00002732bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002733 EvalResult Result;
2734 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002735}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002736
Jay Foad39c79802011-01-12 09:06:06 +00002737bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002738 Expr::EvalResult Result;
2739 EvalInfo Info(Ctx, Result);
2740 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2741}
2742
Jay Foad39c79802011-01-12 09:06:06 +00002743APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002744 EvalResult EvalResult;
2745 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002746 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002747 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002748 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002749
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002750 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002751}
John McCall864e3962010-05-07 05:32:02 +00002752
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002753 bool Expr::EvalResult::isGlobalLValue() const {
2754 assert(Val.isLValue());
2755 return IsGlobalLValue(Val.getLValueBase());
2756 }
2757
2758
John McCall864e3962010-05-07 05:32:02 +00002759/// isIntegerConstantExpr - this recursive routine will test if an expression is
2760/// an integer constant expression.
2761
2762/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2763/// comma, etc
2764///
2765/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2766/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2767/// cast+dereference.
2768
2769// CheckICE - This function does the fundamental ICE checking: the returned
2770// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2771// Note that to reduce code duplication, this helper does no evaluation
2772// itself; the caller checks whether the expression is evaluatable, and
2773// in the rare cases where CheckICE actually cares about the evaluated
2774// value, it calls into Evalute.
2775//
2776// Meanings of Val:
2777// 0: This expression is an ICE if it can be evaluated by Evaluate.
2778// 1: This expression is not an ICE, but if it isn't evaluated, it's
2779// a legal subexpression for an ICE. This return value is used to handle
2780// the comma operator in C99 mode.
2781// 2: This expression is not an ICE, and is not a legal subexpression for one.
2782
Dan Gohman28ade552010-07-26 21:25:24 +00002783namespace {
2784
John McCall864e3962010-05-07 05:32:02 +00002785struct ICEDiag {
2786 unsigned Val;
2787 SourceLocation Loc;
2788
2789 public:
2790 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2791 ICEDiag() : Val(0) {}
2792};
2793
Dan Gohman28ade552010-07-26 21:25:24 +00002794}
2795
2796static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00002797
2798static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2799 Expr::EvalResult EVResult;
2800 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2801 !EVResult.Val.isInt()) {
2802 return ICEDiag(2, E->getLocStart());
2803 }
2804 return NoDiag();
2805}
2806
2807static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2808 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00002809 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00002810 return ICEDiag(2, E->getLocStart());
2811 }
2812
2813 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00002814#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00002815#define STMT(Node, Base) case Expr::Node##Class:
2816#define EXPR(Node, Base)
2817#include "clang/AST/StmtNodes.inc"
2818 case Expr::PredefinedExprClass:
2819 case Expr::FloatingLiteralClass:
2820 case Expr::ImaginaryLiteralClass:
2821 case Expr::StringLiteralClass:
2822 case Expr::ArraySubscriptExprClass:
2823 case Expr::MemberExprClass:
2824 case Expr::CompoundAssignOperatorClass:
2825 case Expr::CompoundLiteralExprClass:
2826 case Expr::ExtVectorElementExprClass:
2827 case Expr::InitListExprClass:
2828 case Expr::DesignatedInitExprClass:
2829 case Expr::ImplicitValueInitExprClass:
2830 case Expr::ParenListExprClass:
2831 case Expr::VAArgExprClass:
2832 case Expr::AddrLabelExprClass:
2833 case Expr::StmtExprClass:
2834 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00002835 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00002836 case Expr::CXXDynamicCastExprClass:
2837 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00002838 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00002839 case Expr::CXXNullPtrLiteralExprClass:
2840 case Expr::CXXThisExprClass:
2841 case Expr::CXXThrowExprClass:
2842 case Expr::CXXNewExprClass:
2843 case Expr::CXXDeleteExprClass:
2844 case Expr::CXXPseudoDestructorExprClass:
2845 case Expr::UnresolvedLookupExprClass:
2846 case Expr::DependentScopeDeclRefExprClass:
2847 case Expr::CXXConstructExprClass:
2848 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00002849 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00002850 case Expr::CXXTemporaryObjectExprClass:
2851 case Expr::CXXUnresolvedConstructExprClass:
2852 case Expr::CXXDependentScopeMemberExprClass:
2853 case Expr::UnresolvedMemberExprClass:
2854 case Expr::ObjCStringLiteralClass:
2855 case Expr::ObjCEncodeExprClass:
2856 case Expr::ObjCMessageExprClass:
2857 case Expr::ObjCSelectorExprClass:
2858 case Expr::ObjCProtocolExprClass:
2859 case Expr::ObjCIvarRefExprClass:
2860 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00002861 case Expr::ObjCIsaExprClass:
2862 case Expr::ShuffleVectorExprClass:
2863 case Expr::BlockExprClass:
2864 case Expr::BlockDeclRefExprClass:
2865 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00002866 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00002867 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00002868 case Expr::SubstNonTypeTemplateParmPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00002869 return ICEDiag(2, E->getLocStart());
2870
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002871 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00002872 case Expr::GNUNullExprClass:
2873 // GCC considers the GNU __null value to be an integral constant expression.
2874 return NoDiag();
2875
2876 case Expr::ParenExprClass:
2877 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002878 case Expr::GenericSelectionExprClass:
2879 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002880 case Expr::IntegerLiteralClass:
2881 case Expr::CharacterLiteralClass:
2882 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00002883 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00002884 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002885 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00002886 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00002887 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00002888 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00002889 return NoDiag();
2890 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00002891 case Expr::CXXOperatorCallExprClass: {
John McCall864e3962010-05-07 05:32:02 +00002892 const CallExpr *CE = cast<CallExpr>(E);
2893 if (CE->isBuiltinCall(Ctx))
2894 return CheckEvalInICE(E, Ctx);
2895 return ICEDiag(2, E->getLocStart());
2896 }
2897 case Expr::DeclRefExprClass:
2898 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2899 return NoDiag();
2900 if (Ctx.getLangOptions().CPlusPlus &&
2901 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2902 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2903
2904 // Parameter variables are never constants. Without this check,
2905 // getAnyInitializer() can find a default argument, which leads
2906 // to chaos.
2907 if (isa<ParmVarDecl>(D))
2908 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2909
2910 // C++ 7.1.5.1p2
2911 // A variable of non-volatile const-qualified integral or enumeration
2912 // type initialized by an ICE can be used in ICEs.
2913 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2914 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2915 if (Quals.hasVolatile() || !Quals.hasConst())
2916 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2917
2918 // Look for a declaration of this variable that has an initializer.
2919 const VarDecl *ID = 0;
2920 const Expr *Init = Dcl->getAnyInitializer(ID);
2921 if (Init) {
2922 if (ID->isInitKnownICE()) {
2923 // We have already checked whether this subexpression is an
2924 // integral constant expression.
2925 if (ID->isInitICE())
2926 return NoDiag();
2927 else
2928 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2929 }
2930
2931 // It's an ICE whether or not the definition we found is
2932 // out-of-line. See DR 721 and the discussion in Clang PR
2933 // 6206 for details.
2934
2935 if (Dcl->isCheckingICE()) {
2936 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2937 }
2938
2939 Dcl->setCheckingICE();
2940 ICEDiag Result = CheckICE(Init, Ctx);
2941 // Cache the result of the ICE test.
2942 Dcl->setInitKnownICE(Result.Val == 0);
2943 return Result;
2944 }
2945 }
2946 }
2947 return ICEDiag(2, E->getLocStart());
2948 case Expr::UnaryOperatorClass: {
2949 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2950 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002951 case UO_PostInc:
2952 case UO_PostDec:
2953 case UO_PreInc:
2954 case UO_PreDec:
2955 case UO_AddrOf:
2956 case UO_Deref:
John McCall864e3962010-05-07 05:32:02 +00002957 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00002958 case UO_Extension:
2959 case UO_LNot:
2960 case UO_Plus:
2961 case UO_Minus:
2962 case UO_Not:
2963 case UO_Real:
2964 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00002965 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002966 }
2967
2968 // OffsetOf falls through here.
2969 }
2970 case Expr::OffsetOfExprClass: {
2971 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2972 // Evaluate matches the proposed gcc behavior for cases like
2973 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2974 // compliance: we should warn earlier for offsetof expressions with
2975 // array subscripts that aren't ICEs, and if the array subscripts
2976 // are ICEs, the value of the offsetof must be an integer constant.
2977 return CheckEvalInICE(E, Ctx);
2978 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002979 case Expr::UnaryExprOrTypeTraitExprClass: {
2980 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2981 if ((Exp->getKind() == UETT_SizeOf) &&
2982 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00002983 return ICEDiag(2, E->getLocStart());
2984 return NoDiag();
2985 }
2986 case Expr::BinaryOperatorClass: {
2987 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2988 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002989 case BO_PtrMemD:
2990 case BO_PtrMemI:
2991 case BO_Assign:
2992 case BO_MulAssign:
2993 case BO_DivAssign:
2994 case BO_RemAssign:
2995 case BO_AddAssign:
2996 case BO_SubAssign:
2997 case BO_ShlAssign:
2998 case BO_ShrAssign:
2999 case BO_AndAssign:
3000 case BO_XorAssign:
3001 case BO_OrAssign:
John McCall864e3962010-05-07 05:32:02 +00003002 return ICEDiag(2, E->getLocStart());
3003
John McCalle3027922010-08-25 11:45:40 +00003004 case BO_Mul:
3005 case BO_Div:
3006 case BO_Rem:
3007 case BO_Add:
3008 case BO_Sub:
3009 case BO_Shl:
3010 case BO_Shr:
3011 case BO_LT:
3012 case BO_GT:
3013 case BO_LE:
3014 case BO_GE:
3015 case BO_EQ:
3016 case BO_NE:
3017 case BO_And:
3018 case BO_Xor:
3019 case BO_Or:
3020 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003021 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3022 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003023 if (Exp->getOpcode() == BO_Div ||
3024 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00003025 // Evaluate gives an error for undefined Div/Rem, so make sure
3026 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003027 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCall864e3962010-05-07 05:32:02 +00003028 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
3029 if (REval == 0)
3030 return ICEDiag(1, E->getLocStart());
3031 if (REval.isSigned() && REval.isAllOnesValue()) {
3032 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
3033 if (LEval.isMinSignedValue())
3034 return ICEDiag(1, E->getLocStart());
3035 }
3036 }
3037 }
John McCalle3027922010-08-25 11:45:40 +00003038 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003039 if (Ctx.getLangOptions().C99) {
3040 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3041 // if it isn't evaluated.
3042 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3043 return ICEDiag(1, E->getLocStart());
3044 } else {
3045 // In both C89 and C++, commas in ICEs are illegal.
3046 return ICEDiag(2, E->getLocStart());
3047 }
3048 }
3049 if (LHSResult.Val >= RHSResult.Val)
3050 return LHSResult;
3051 return RHSResult;
3052 }
John McCalle3027922010-08-25 11:45:40 +00003053 case BO_LAnd:
3054 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003055 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3056 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3057 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3058 // Rare case where the RHS has a comma "side-effect"; we need
3059 // to actually check the condition to see whether the side
3060 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003061 if ((Exp->getOpcode() == BO_LAnd) !=
John McCall864e3962010-05-07 05:32:02 +00003062 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3063 return RHSResult;
3064 return NoDiag();
3065 }
3066
3067 if (LHSResult.Val >= RHSResult.Val)
3068 return LHSResult;
3069 return RHSResult;
3070 }
3071 }
3072 }
3073 case Expr::ImplicitCastExprClass:
3074 case Expr::CStyleCastExprClass:
3075 case Expr::CXXFunctionalCastExprClass:
3076 case Expr::CXXStaticCastExprClass:
3077 case Expr::CXXReinterpretCastExprClass:
3078 case Expr::CXXConstCastExprClass: {
3079 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregorb90df602010-06-16 00:17:44 +00003080 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCall864e3962010-05-07 05:32:02 +00003081 return CheckICE(SubExpr, Ctx);
3082 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3083 return NoDiag();
3084 return ICEDiag(2, E->getLocStart());
3085 }
John McCallc07a0c72011-02-17 10:25:35 +00003086 case Expr::BinaryConditionalOperatorClass: {
3087 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3088 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3089 if (CommonResult.Val == 2) return CommonResult;
3090 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3091 if (FalseResult.Val == 2) return FalseResult;
3092 if (CommonResult.Val == 1) return CommonResult;
3093 if (FalseResult.Val == 1 &&
3094 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3095 return FalseResult;
3096 }
John McCall864e3962010-05-07 05:32:02 +00003097 case Expr::ConditionalOperatorClass: {
3098 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3099 // If the condition (ignoring parens) is a __builtin_constant_p call,
3100 // then only the true side is actually considered in an integer constant
3101 // expression, and it is fully evaluated. This is an important GNU
3102 // extension. See GCC PR38377 for discussion.
3103 if (const CallExpr *CallCE
3104 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3105 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3106 Expr::EvalResult EVResult;
3107 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3108 !EVResult.Val.isInt()) {
3109 return ICEDiag(2, E->getLocStart());
3110 }
3111 return NoDiag();
3112 }
3113 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
3114 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3115 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3116 if (CondResult.Val == 2)
3117 return CondResult;
3118 if (TrueResult.Val == 2)
3119 return TrueResult;
3120 if (FalseResult.Val == 2)
3121 return FalseResult;
3122 if (CondResult.Val == 1)
3123 return CondResult;
3124 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3125 return NoDiag();
3126 // Rare case where the diagnostics depend on which side is evaluated
3127 // Note that if we get here, CondResult is 0, and at least one of
3128 // TrueResult and FalseResult is non-zero.
3129 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3130 return FalseResult;
3131 }
3132 return TrueResult;
3133 }
3134 case Expr::CXXDefaultArgExprClass:
3135 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3136 case Expr::ChooseExprClass: {
3137 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3138 }
3139 }
3140
3141 // Silence a GCC warning
3142 return ICEDiag(2, E->getLocStart());
3143}
3144
3145bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3146 SourceLocation *Loc, bool isEvaluated) const {
3147 ICEDiag d = CheckICE(this, Ctx);
3148 if (d.Val != 0) {
3149 if (Loc) *Loc = d.Loc;
3150 return false;
3151 }
3152 EvalResult EvalResult;
3153 if (!Evaluate(EvalResult, Ctx))
3154 llvm_unreachable("ICE cannot be evaluated!");
3155 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3156 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3157 Result = EvalResult.Val.getInt();
3158 return true;
3159}