blob: 14a1222cad577dc412c07cfabdcbe0692ce0a468 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Benjamin Kramerc54061a2011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
49 /// EvalResult - Contains information about the evaluation.
50 Expr::EvalResult &EvalResult;
51
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
61 : Ctx(ctx), EvalResult(evalresult) {}
62 };
63
John McCallf4cf1a12010-05-07 17:22:02 +000064 struct ComplexValue {
65 private:
66 bool IsInt;
67
68 public:
69 APSInt IntReal, IntImag;
70 APFloat FloatReal, FloatImag;
71
72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
73
74 void makeComplexFloat() { IsInt = false; }
75 bool isComplexFloat() const { return !IsInt; }
76 APFloat &getComplexFloatReal() { return FloatReal; }
77 APFloat &getComplexFloatImag() { return FloatImag; }
78
79 void makeComplexInt() { IsInt = true; }
80 bool isComplexInt() const { return IsInt; }
81 APSInt &getComplexIntReal() { return IntReal; }
82 APSInt &getComplexIntImag() { return IntImag; }
83
John McCall56ca35d2011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCall56ca35d2011-02-17 10:25:35 +000090 void setFrom(const APValue &v) {
91 assert(v.isComplexFloat() || v.isComplexInt());
92 if (v.isComplexFloat()) {
93 makeComplexFloat();
94 FloatReal = v.getComplexFloatReal();
95 FloatImag = v.getComplexFloatImag();
96 } else {
97 makeComplexInt();
98 IntReal = v.getComplexIntReal();
99 IntImag = v.getComplexIntImag();
100 }
101 }
John McCallf4cf1a12010-05-07 17:22:02 +0000102 };
John McCallefdb83e2010-05-07 21:00:08 +0000103
104 struct LValue {
105 Expr *Base;
106 CharUnits Offset;
107
108 Expr *getLValueBase() { return Base; }
109 CharUnits getLValueOffset() { return Offset; }
110
John McCall56ca35d2011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCallefdb83e2010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCall56ca35d2011-02-17 10:25:35 +0000114 void setFrom(const APValue &v) {
115 assert(v.isLValue());
116 Base = v.getLValueBase();
117 Offset = v.getLValueOffset();
118 }
John McCallefdb83e2010-05-07 21:00:08 +0000119 };
John McCallf4cf1a12010-05-07 17:22:02 +0000120}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000121
John McCall56ca35d2011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000136 if (!E) return true;
137
138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
139 if (isa<FunctionDecl>(DRE->getDecl()))
140 return true;
141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
142 return VD->hasGlobalStorage();
143 return false;
144 }
145
146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
147 return CLE->isFileScope();
148
149 return true;
150}
151
John McCallefdb83e2010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000154
John McCall35542832010-05-07 21:34:32 +0000155 // A null base expression indicates a null pointer. These are always
156 // evaluatable, and they are false unless the offset is zero.
157 if (!Base) {
158 Result = !Value.Offset.isZero();
159 return true;
160 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000161
John McCall42c8f872010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000164
John McCall35542832010-05-07 21:34:32 +0000165 // We have a non-null base expression. These are generally known to
166 // be true, but if it'a decl-ref to a weak symbol it can be null at
167 // runtime.
John McCall35542832010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCall35542832010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman5bc86102009-06-14 02:17:33 +0000181 return true;
182}
183
John McCallcd7a4452010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000187 APSInt IntResult;
188 if (!EvaluateInteger(E, IntResult, Info))
189 return false;
190 Result = IntResult != 0;
191 return true;
192 } else if (E->getType()->isRealFloatingType()) {
193 APFloat FloatResult(0.0);
194 if (!EvaluateFloat(E, FloatResult, Info))
195 return false;
196 Result = !FloatResult.isZero();
197 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000205 if (!EvaluateComplex(E, ComplexResult, Info))
206 return false;
207 if (ComplexResult.isComplexFloat()) {
208 Result = !ComplexResult.getComplexFloatReal().isZero() ||
209 !ComplexResult.getComplexFloatImag().isZero();
210 } else {
211 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
212 ComplexResult.getComplexIntImag().getBoolValue();
213 }
214 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump1eb44332009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
224 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
227 uint64_t Space[4];
228 bool ignored;
229 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
230 llvm::APFloat::rmTowardZero, &ignored);
231 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
232}
233
Mike Stump1eb44332009-09-09 15:08:12 +0000234static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000235 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000236 bool ignored;
237 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000238 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000239 APFloat::rmNearestTiesToEven, &ignored);
240 return Result;
241}
242
Mike Stump1eb44332009-09-09 15:08:12 +0000243static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000244 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000245 unsigned DestWidth = Ctx.getIntWidth(DestType);
246 APSInt Result = Value;
247 // Figure out if this is a truncate, extend or noop cast.
248 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000249 Result = Result.extOrTrunc(DestWidth);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000250 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
251 return Result;
252}
253
Mike Stump1eb44332009-09-09 15:08:12 +0000254static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000255 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000256
257 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
258 Result.convertFromAPInt(Value, Value.isSigned(),
259 APFloat::rmNearestTiesToEven);
260 return Result;
261}
262
Mike Stumpc4c90452009-10-27 22:09:17 +0000263namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000264class HasSideEffect
Mike Stumpc4c90452009-10-27 22:09:17 +0000265 : public StmtVisitor<HasSideEffect, bool> {
266 EvalInfo &Info;
267public:
268
269 HasSideEffect(EvalInfo &info) : Info(info) {}
270
271 // Unhandled nodes conservatively default to having side effects.
272 bool VisitStmt(Stmt *S) {
273 return true;
274 }
275
276 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000277 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
278 return Visit(E->getResultExpr());
279 }
Mike Stumpc4c90452009-10-27 22:09:17 +0000280 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000281 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000282 return true;
283 return false;
284 }
285 // We don't want to evaluate BlockExprs multiple times, as they generate
286 // a ton of code.
287 bool VisitBlockExpr(BlockExpr *E) { return true; }
288 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
289 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
290 { return Visit(E->getInitializer()); }
291 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
292 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
293 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
294 bool VisitStringLiteral(StringLiteral *E) { return false; }
295 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000296 bool VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E)
297 { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000298 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000299 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000300 bool VisitChooseExpr(ChooseExpr *E)
301 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
302 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
303 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stump3f0147e2009-10-29 23:34:20 +0000304 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stump980ca222009-10-29 20:48:09 +0000305 bool VisitBinaryOperator(BinaryOperator *E)
306 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000307 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
308 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
309 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
310 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
311 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000312 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000313 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000314 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000315 }
316 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000317
318 // Has side effects if any element does.
319 bool VisitInitListExpr(InitListExpr *E) {
320 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
321 if (Visit(E->getInit(i))) return true;
322 return false;
323 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000324
325 bool VisitSizeOfPackExpr(SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000326};
327
John McCall56ca35d2011-02-17 10:25:35 +0000328class OpaqueValueEvaluation {
329 EvalInfo &info;
330 OpaqueValueExpr *opaqueValue;
331
332public:
333 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
334 Expr *value)
335 : info(info), opaqueValue(opaqueValue) {
336
337 // If evaluation fails, fail immediately.
338 if (!Evaluate(info, value)) {
339 this->opaqueValue = 0;
340 return;
341 }
342 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
343 }
344
345 bool hasError() const { return opaqueValue == 0; }
346
347 ~OpaqueValueEvaluation() {
348 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
349 }
350};
351
Mike Stumpc4c90452009-10-27 22:09:17 +0000352} // end anonymous namespace
353
Eli Friedman4efaa272008-11-12 09:44:48 +0000354//===----------------------------------------------------------------------===//
355// LValue Evaluation
356//===----------------------------------------------------------------------===//
357namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000358class LValueExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000359 : public StmtVisitor<LValueExprEvaluator, bool> {
Eli Friedman4efaa272008-11-12 09:44:48 +0000360 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000361 LValue &Result;
362
363 bool Success(Expr *E) {
364 Result.Base = E;
365 Result.Offset = CharUnits::Zero();
366 return true;
367 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000368public:
Mike Stump1eb44332009-09-09 15:08:12 +0000369
John McCallefdb83e2010-05-07 21:00:08 +0000370 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
371 Info(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000372
John McCallefdb83e2010-05-07 21:00:08 +0000373 bool VisitStmt(Stmt *S) {
374 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000375 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000376
John McCallefdb83e2010-05-07 21:00:08 +0000377 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000378 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
379 return Visit(E->getResultExpr());
380 }
John McCallefdb83e2010-05-07 21:00:08 +0000381 bool VisitDeclRefExpr(DeclRefExpr *E);
382 bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); }
383 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
384 bool VisitMemberExpr(MemberExpr *E);
385 bool VisitStringLiteral(StringLiteral *E) { return Success(E); }
386 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); }
387 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E);
388 bool VisitUnaryDeref(UnaryOperator *E);
389 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000390 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000391 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000392 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlsson26bc2202009-10-03 16:30:22 +0000393
John McCallefdb83e2010-05-07 21:00:08 +0000394 bool VisitCastExpr(CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000395 switch (E->getCastKind()) {
396 default:
John McCallefdb83e2010-05-07 21:00:08 +0000397 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000398
John McCall2de56d12010-08-25 11:45:40 +0000399 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000400 return Visit(E->getSubExpr());
401 }
402 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000403 // FIXME: Missing: __real__, __imag__
Eli Friedman4efaa272008-11-12 09:44:48 +0000404};
405} // end anonymous namespace
406
John McCallefdb83e2010-05-07 21:00:08 +0000407static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
408 return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Eli Friedman4efaa272008-11-12 09:44:48 +0000409}
410
John McCallefdb83e2010-05-07 21:00:08 +0000411bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000412 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000413 return Success(E);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000414 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
415 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000416 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000417 // Reference parameters can refer to anything even if they have an
418 // "initializer" in the form of a default argument.
419 if (isa<ParmVarDecl>(VD))
420 return false;
Eli Friedmand933a012009-08-29 19:09:59 +0000421 // FIXME: Check whether VD might be overridden!
Sebastian Redl31310a22010-02-01 20:16:42 +0000422 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000423 return Visit(const_cast<Expr *>(Init));
Eli Friedman50c39ea2009-05-27 06:04:58 +0000424 }
425
John McCallefdb83e2010-05-07 21:00:08 +0000426 return false;
Anders Carlsson35873c42008-11-24 04:41:22 +0000427}
428
John McCallefdb83e2010-05-07 21:00:08 +0000429bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000430 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000431}
432
John McCallefdb83e2010-05-07 21:00:08 +0000433bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000434 QualType Ty;
435 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000436 if (!EvaluatePointer(E->getBase(), Result, Info))
437 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000438 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000439 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000440 if (!Visit(E->getBase()))
441 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000442 Ty = E->getBase()->getType();
443 }
444
Ted Kremenek6217b802009-07-29 21:53:49 +0000445 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000446 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000447
448 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
449 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000450 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000451
452 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000453 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000454
Eli Friedman4efaa272008-11-12 09:44:48 +0000455 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000456 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000457 for (RecordDecl::field_iterator Field = RD->field_begin(),
458 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000459 Field != FieldEnd; (void)++Field, ++i) {
460 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000461 break;
462 }
463
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000464 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000465 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000466}
467
John McCallefdb83e2010-05-07 21:00:08 +0000468bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000469 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000470 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Anders Carlsson3068d112008-11-16 19:01:22 +0000472 APSInt Index;
473 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000474 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000475
Ken Dyck199c3d62010-01-11 17:06:35 +0000476 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000477 Result.Offset += Index.getSExtValue() * ElementSize;
478 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000479}
Eli Friedman4efaa272008-11-12 09:44:48 +0000480
John McCallefdb83e2010-05-07 21:00:08 +0000481bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
482 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000483}
484
Eli Friedman4efaa272008-11-12 09:44:48 +0000485//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000486// Pointer Evaluation
487//===----------------------------------------------------------------------===//
488
Anders Carlssonc754aa62008-07-08 05:13:58 +0000489namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000490class PointerExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000491 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000492 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000493 LValue &Result;
494
495 bool Success(Expr *E) {
496 Result.Base = E;
497 Result.Offset = CharUnits::Zero();
498 return true;
499 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000500public:
Mike Stump1eb44332009-09-09 15:08:12 +0000501
John McCallefdb83e2010-05-07 21:00:08 +0000502 PointerExprEvaluator(EvalInfo &info, LValue &Result)
503 : Info(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000504
John McCallefdb83e2010-05-07 21:00:08 +0000505 bool VisitStmt(Stmt *S) {
506 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000507 }
508
John McCallefdb83e2010-05-07 21:00:08 +0000509 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000510 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
511 return Visit(E->getResultExpr());
512 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000513
John McCallefdb83e2010-05-07 21:00:08 +0000514 bool VisitBinaryOperator(const BinaryOperator *E);
515 bool VisitCastExpr(CastExpr* E);
516 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman2217c872009-02-22 11:46:18 +0000517 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000518 bool VisitUnaryAddrOf(const UnaryOperator *E);
519 bool VisitObjCStringLiteral(ObjCStringLiteral *E)
520 { return Success(E); }
521 bool VisitAddrLabelExpr(AddrLabelExpr *E)
522 { return Success(E); }
523 bool VisitCallExpr(CallExpr *E);
524 bool VisitBlockExpr(BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000525 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000526 return Success(E);
527 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000528 }
John McCallefdb83e2010-05-07 21:00:08 +0000529 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
530 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000531 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
John McCallefdb83e2010-05-07 21:00:08 +0000532 bool VisitConditionalOperator(ConditionalOperator *E);
533 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000534 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallefdb83e2010-05-07 21:00:08 +0000535 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
536 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000537
538 bool VisitOpaqueValueExpr(OpaqueValueExpr *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000539 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000540};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000541} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000542
John McCallefdb83e2010-05-07 21:00:08 +0000543static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000544 assert(E->getType()->hasPointerRepresentation());
John McCallefdb83e2010-05-07 21:00:08 +0000545 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000546}
547
John McCallefdb83e2010-05-07 21:00:08 +0000548bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000549 if (E->getOpcode() != BO_Add &&
550 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000551 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000553 const Expr *PExp = E->getLHS();
554 const Expr *IExp = E->getRHS();
555 if (IExp->getType()->isPointerType())
556 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000557
John McCallefdb83e2010-05-07 21:00:08 +0000558 if (!EvaluatePointer(PExp, Result, Info))
559 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000560
John McCallefdb83e2010-05-07 21:00:08 +0000561 llvm::APSInt Offset;
562 if (!EvaluateInteger(IExp, Offset, Info))
563 return false;
564 int64_t AdditionalOffset
565 = Offset.isSigned() ? Offset.getSExtValue()
566 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000567
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000568 // Compute the new offset in the appropriate width.
569
570 QualType PointeeType =
571 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000572 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000574 // Explicitly handle GNU void* and function pointer arithmetic extensions.
575 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000576 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000577 else
John McCallefdb83e2010-05-07 21:00:08 +0000578 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000579
John McCall2de56d12010-08-25 11:45:40 +0000580 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000581 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000582 else
John McCallefdb83e2010-05-07 21:00:08 +0000583 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000584
John McCallefdb83e2010-05-07 21:00:08 +0000585 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000586}
Eli Friedman4efaa272008-11-12 09:44:48 +0000587
John McCallefdb83e2010-05-07 21:00:08 +0000588bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
589 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000590}
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000592
John McCallefdb83e2010-05-07 21:00:08 +0000593bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000594 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000595
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000596 switch (E->getCastKind()) {
597 default:
598 break;
599
John McCall2de56d12010-08-25 11:45:40 +0000600 case CK_NoOp:
601 case CK_BitCast:
John McCall2de56d12010-08-25 11:45:40 +0000602 case CK_AnyPointerToObjCPointerCast:
603 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000604 return Visit(SubExpr);
605
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000606 case CK_DerivedToBase:
607 case CK_UncheckedDerivedToBase: {
608 LValue BaseLV;
609 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
610 return false;
611
612 // Now figure out the necessary offset to add to the baseLV to get from
613 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000614 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000615
616 QualType Ty = E->getSubExpr()->getType();
617 const CXXRecordDecl *DerivedDecl =
618 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
619
620 for (CastExpr::path_const_iterator PathI = E->path_begin(),
621 PathE = E->path_end(); PathI != PathE; ++PathI) {
622 const CXXBaseSpecifier *Base = *PathI;
623
624 // FIXME: If the base is virtual, we'd need to determine the type of the
625 // most derived class and we don't support that right now.
626 if (Base->isVirtual())
627 return false;
628
629 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
630 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
631
Ken Dyck7c7f8202011-01-26 02:17:08 +0000632 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000633 DerivedDecl = BaseDecl;
634 }
635
636 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000637 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000638 return true;
639 }
640
John McCall404cd162010-11-13 01:35:44 +0000641 case CK_NullToPointer: {
642 Result.Base = 0;
643 Result.Offset = CharUnits::Zero();
644 return true;
645 }
646
John McCall2de56d12010-08-25 11:45:40 +0000647 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000648 APValue Value;
649 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000650 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000651
John McCallefdb83e2010-05-07 21:00:08 +0000652 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000653 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000654 Result.Base = 0;
655 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
656 return true;
657 } else {
658 // Cast is of an lvalue, no need to change value.
659 Result.Base = Value.getLValueBase();
660 Result.Offset = Value.getLValueOffset();
661 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000662 }
663 }
John McCall2de56d12010-08-25 11:45:40 +0000664 case CK_ArrayToPointerDecay:
665 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000666 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000667 }
668
John McCallefdb83e2010-05-07 21:00:08 +0000669 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000670}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000671
John McCallefdb83e2010-05-07 21:00:08 +0000672bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000673 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000674 Builtin::BI__builtin___CFStringMakeConstantString ||
675 E->isBuiltinCall(Info.Ctx) ==
676 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000677 return Success(E);
678 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000679}
680
John McCall56ca35d2011-02-17 10:25:35 +0000681bool PointerExprEvaluator::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
682 const APValue *value = Info.getOpaqueValue(e);
683 if (!value)
684 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
685 Result.setFrom(*value);
686 return true;
687}
688
689bool PointerExprEvaluator::
690VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
691 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
692 if (opaque.hasError()) return false;
693
694 bool cond;
695 if (!HandleConversionToBool(e->getCond(), cond, Info))
696 return false;
697
698 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
699}
700
John McCallefdb83e2010-05-07 21:00:08 +0000701bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000702 bool BoolResult;
703 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000704 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000705
706 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000707 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000708}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000709
710//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000711// Vector Evaluation
712//===----------------------------------------------------------------------===//
713
714namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000715 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000716 : public StmtVisitor<VectorExprEvaluator, APValue> {
717 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000718 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000719 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Nate Begeman59b5da62009-01-18 03:20:47 +0000721 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Nate Begeman59b5da62009-01-18 03:20:47 +0000723 APValue VisitStmt(Stmt *S) {
724 return APValue();
725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Eli Friedman91110ee2009-02-23 04:23:56 +0000727 APValue VisitParenExpr(ParenExpr *E)
728 { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000729 APValue VisitGenericSelectionExpr(GenericSelectionExpr *E)
730 { return Visit(E->getResultExpr()); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000731 APValue VisitUnaryExtension(const UnaryOperator *E)
732 { return Visit(E->getSubExpr()); }
733 APValue VisitUnaryPlus(const UnaryOperator *E)
734 { return Visit(E->getSubExpr()); }
735 APValue VisitUnaryReal(const UnaryOperator *E)
736 { return Visit(E->getSubExpr()); }
737 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
738 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000739 APValue VisitCastExpr(const CastExpr* E);
740 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
741 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000742 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000743 APValue VisitChooseExpr(const ChooseExpr *E)
744 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000745 APValue VisitUnaryImag(const UnaryOperator *E);
746 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000747 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000748 // shufflevector, ExtVectorElementExpr
749 // (Note that these require implementing conversions
750 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000751 };
752} // end anonymous namespace
753
754static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
755 if (!E->getType()->isVectorType())
756 return false;
757 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
758 return !Result.isUninit();
759}
760
761APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000762 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000763 QualType EltTy = VTy->getElementType();
764 unsigned NElts = VTy->getNumElements();
765 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Nate Begeman59b5da62009-01-18 03:20:47 +0000767 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000768 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000769
Eli Friedman46a52322011-03-25 00:43:55 +0000770 switch (E->getCastKind()) {
771 case CK_VectorSplat: {
772 APValue Result = APValue();
773 if (SETy->isIntegerType()) {
774 APSInt IntResult;
775 if (!EvaluateInteger(SE, IntResult, Info))
776 return APValue();
777 Result = APValue(IntResult);
778 } else if (SETy->isRealFloatingType()) {
779 APFloat F(0.0);
780 if (!EvaluateFloat(SE, F, Info))
781 return APValue();
782 Result = APValue(F);
783 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000784 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000785 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000786
787 // Splat and create vector APValue.
788 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
789 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000790 }
Eli Friedman46a52322011-03-25 00:43:55 +0000791 case CK_BitCast: {
792 if (SETy->isVectorType())
793 return Visit(const_cast<Expr*>(SE));
Nate Begemanc0b8b192009-07-01 07:50:47 +0000794
Eli Friedman46a52322011-03-25 00:43:55 +0000795 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000796 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Eli Friedman46a52322011-03-25 00:43:55 +0000798 APSInt Init;
799 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000800 return APValue();
801
Eli Friedman46a52322011-03-25 00:43:55 +0000802 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
803 "Vectors must be composed of ints or floats");
804
805 llvm::SmallVector<APValue, 4> Elts;
806 for (unsigned i = 0; i != NElts; ++i) {
807 APSInt Tmp = Init.extOrTrunc(EltWidth);
808
809 if (EltTy->isIntegerType())
810 Elts.push_back(APValue(Tmp));
811 else
812 Elts.push_back(APValue(APFloat(Tmp)));
813
814 Init >>= EltWidth;
815 }
816 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000817 }
Eli Friedman46a52322011-03-25 00:43:55 +0000818 case CK_LValueToRValue:
819 case CK_NoOp:
820 return Visit(const_cast<Expr*>(SE));
821 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000822 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000823 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000824}
825
Mike Stump1eb44332009-09-09 15:08:12 +0000826APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000827VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
828 return this->Visit(const_cast<Expr*>(E->getInitializer()));
829}
830
Mike Stump1eb44332009-09-09 15:08:12 +0000831APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000832VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000833 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000834 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000835 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Nate Begeman59b5da62009-01-18 03:20:47 +0000837 QualType EltTy = VT->getElementType();
838 llvm::SmallVector<APValue, 4> Elements;
839
John McCalla7d6c222010-06-11 17:54:15 +0000840 // If a vector is initialized with a single element, that value
841 // becomes every element of the vector, not just the first.
842 // This is the behavior described in the IBM AltiVec documentation.
843 if (NumInits == 1) {
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000844
845 // Handle the case where the vector is initialized by a another
846 // vector (OpenCL 6.1.6).
847 if (E->getInit(0)->getType()->isVectorType())
848 return this->Visit(const_cast<Expr*>(E->getInit(0)));
849
John McCalla7d6c222010-06-11 17:54:15 +0000850 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000851 if (EltTy->isIntegerType()) {
852 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000853 if (!EvaluateInteger(E->getInit(0), sInt, Info))
854 return APValue();
855 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000856 } else {
857 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000858 if (!EvaluateFloat(E->getInit(0), f, Info))
859 return APValue();
860 InitValue = APValue(f);
861 }
862 for (unsigned i = 0; i < NumElements; i++) {
863 Elements.push_back(InitValue);
864 }
865 } else {
866 for (unsigned i = 0; i < NumElements; i++) {
867 if (EltTy->isIntegerType()) {
868 llvm::APSInt sInt(32);
869 if (i < NumInits) {
870 if (!EvaluateInteger(E->getInit(i), sInt, Info))
871 return APValue();
872 } else {
873 sInt = Info.Ctx.MakeIntValue(0, EltTy);
874 }
875 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000876 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000877 llvm::APFloat f(0.0);
878 if (i < NumInits) {
879 if (!EvaluateFloat(E->getInit(i), f, Info))
880 return APValue();
881 } else {
882 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
883 }
884 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000885 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000886 }
887 }
888 return APValue(&Elements[0], Elements.size());
889}
890
Mike Stump1eb44332009-09-09 15:08:12 +0000891APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000892VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000893 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000894 QualType EltTy = VT->getElementType();
895 APValue ZeroElement;
896 if (EltTy->isIntegerType())
897 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
898 else
899 ZeroElement =
900 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
901
902 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
903 return APValue(&Elements[0], Elements.size());
904}
905
906APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
907 bool BoolResult;
908 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
909 return APValue();
910
911 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
912
913 APValue Result;
914 if (EvaluateVector(EvalExpr, Result, Info))
915 return Result;
916 return APValue();
917}
918
Eli Friedman91110ee2009-02-23 04:23:56 +0000919APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
920 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
921 Info.EvalResult.HasSideEffects = true;
922 return GetZeroVector(E->getType());
923}
924
Nate Begeman59b5da62009-01-18 03:20:47 +0000925//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000926// Integer Evaluation
927//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000928
929namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000930class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000931 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000932 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000933 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000934public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000935 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000936 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000937
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000938 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000939 assert(E->getType()->isIntegralOrEnumerationType() &&
940 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000941 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000942 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000943 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000944 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000945 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000946 return true;
947 }
948
Daniel Dunbar131eb432009-02-19 09:06:44 +0000949 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000950 assert(E->getType()->isIntegralOrEnumerationType() &&
951 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000952 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000953 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000954 Result = APValue(APSInt(I));
955 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000956 return true;
957 }
958
959 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000960 assert(E->getType()->isIntegralOrEnumerationType() &&
961 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000962 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000963 return true;
964 }
965
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000966 bool Success(CharUnits Size, const Expr *E) {
967 return Success(Size.getQuantity(), E);
968 }
969
970
Anders Carlsson82206e22008-11-30 18:14:57 +0000971 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000972 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000973 if (Info.EvalResult.Diag == 0) {
974 Info.EvalResult.DiagLoc = L;
975 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000976 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000977 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000978 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000979 }
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Anders Carlssonc754aa62008-07-08 05:13:58 +0000981 //===--------------------------------------------------------------------===//
982 // Visitor Methods
983 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Chris Lattner32fea9d2008-11-12 07:43:42 +0000985 bool VisitStmt(Stmt *) {
986 assert(0 && "This should be called on integers, stmts are not integers");
987 return false;
988 }
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Chris Lattner32fea9d2008-11-12 07:43:42 +0000990 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000991 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000992 }
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattnerb542afe2008-07-11 19:10:17 +0000994 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000995 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
996 return Visit(E->getResultExpr());
997 }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000998
Chris Lattner4c4867e2008-07-12 00:38:25 +0000999 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001000 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001001 }
1002 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001003 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001004 }
Eli Friedman04309752009-11-24 05:28:59 +00001005
John McCall56ca35d2011-02-17 10:25:35 +00001006 bool VisitOpaqueValueExpr(OpaqueValueExpr *e) {
1007 const APValue *value = Info.getOpaqueValue(e);
1008 if (!value) {
1009 if (e->getSourceExpr()) return Visit(e->getSourceExpr());
1010 return Error(e->getExprLoc(), diag::note_invalid_subexpr_in_ice, e);
1011 }
1012 return Success(value->getInt(), e);
1013 }
1014
Eli Friedman04309752009-11-24 05:28:59 +00001015 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1016 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1017 return CheckReferencedDecl(E, E->getDecl());
1018 }
1019 bool VisitMemberExpr(const MemberExpr *E) {
1020 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1021 // Conservatively assume a MemberExpr will have side-effects
1022 Info.EvalResult.HasSideEffects = true;
1023 return true;
1024 }
1025 return false;
1026 }
1027
Eli Friedmanc4a26382010-02-13 00:10:10 +00001028 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001029 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001030 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001031 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001032 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001033 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001034
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001035 bool VisitCastExpr(CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001036 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001037
Anders Carlsson3068d112008-11-16 19:01:22 +00001038 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001039 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001040 }
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Anders Carlsson3f704562008-12-21 22:39:40 +00001042 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001043 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001044 }
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Douglas Gregored8abf12010-07-08 06:14:04 +00001046 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001047 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001048 }
1049
Eli Friedman664a1042009-02-27 04:45:43 +00001050 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1051 return Success(0, E);
1052 }
1053
Sebastian Redl64b45f72009-01-05 20:52:13 +00001054 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001055 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001056 }
1057
Francois Pichet6ad6f282010-12-07 00:08:36 +00001058 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1059 return Success(E->getValue(), E);
1060 }
1061
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001062 bool VisitChooseExpr(const ChooseExpr *E) {
1063 return Visit(E->getChosenSubExpr(Info.Ctx));
1064 }
1065
Eli Friedman722c7172009-02-28 03:59:05 +00001066 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001067 bool VisitUnaryImag(const UnaryOperator *E);
1068
Sebastian Redl295995c2010-09-10 20:55:47 +00001069 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001070 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1071
Chris Lattnerfcee0012008-07-11 21:24:13 +00001072private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001073 CharUnits GetAlignOfExpr(const Expr *E);
1074 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001075 static QualType GetObjectType(const Expr *E);
1076 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001077 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001078};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001079} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001080
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001081static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001082 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001083 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1084}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001085
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001086static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001087 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001088
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001089 APValue Val;
1090 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1091 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001092 Result = Val.getInt();
1093 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001094}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001095
Eli Friedman04309752009-11-24 05:28:59 +00001096bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001097 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +00001098 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1099 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001100
1101 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001102 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001103 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1104 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001105
1106 if (isa<ParmVarDecl>(D))
1107 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1108
Eli Friedman04309752009-11-24 05:28:59 +00001109 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001110 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001111 if (APValue *V = VD->getEvaluatedValue()) {
1112 if (V->isInt())
1113 return Success(V->getInt(), E);
1114 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1115 }
1116
1117 if (VD->isEvaluatingValue())
1118 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1119
1120 VD->setEvaluatingValue();
1121
Eli Friedmana7dedf72010-09-06 00:10:32 +00001122 Expr::EvalResult EResult;
1123 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1124 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001125 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001126 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001127 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001128 return true;
1129 }
1130
Eli Friedmanc0131182009-12-03 20:31:57 +00001131 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001132 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001133 }
1134 }
1135
Chris Lattner4c4867e2008-07-12 00:38:25 +00001136 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001137 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001138}
1139
Chris Lattnera4d55d82008-10-06 06:40:35 +00001140/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1141/// as GCC.
1142static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1143 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001144 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001145 enum gcc_type_class {
1146 no_type_class = -1,
1147 void_type_class, integer_type_class, char_type_class,
1148 enumeral_type_class, boolean_type_class,
1149 pointer_type_class, reference_type_class, offset_type_class,
1150 real_type_class, complex_type_class,
1151 function_type_class, method_type_class,
1152 record_type_class, union_type_class,
1153 array_type_class, string_type_class,
1154 lang_type_class
1155 };
Mike Stump1eb44332009-09-09 15:08:12 +00001156
1157 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001158 // ideal, however it is what gcc does.
1159 if (E->getNumArgs() == 0)
1160 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Chris Lattnera4d55d82008-10-06 06:40:35 +00001162 QualType ArgTy = E->getArg(0)->getType();
1163 if (ArgTy->isVoidType())
1164 return void_type_class;
1165 else if (ArgTy->isEnumeralType())
1166 return enumeral_type_class;
1167 else if (ArgTy->isBooleanType())
1168 return boolean_type_class;
1169 else if (ArgTy->isCharType())
1170 return string_type_class; // gcc doesn't appear to use char_type_class
1171 else if (ArgTy->isIntegerType())
1172 return integer_type_class;
1173 else if (ArgTy->isPointerType())
1174 return pointer_type_class;
1175 else if (ArgTy->isReferenceType())
1176 return reference_type_class;
1177 else if (ArgTy->isRealType())
1178 return real_type_class;
1179 else if (ArgTy->isComplexType())
1180 return complex_type_class;
1181 else if (ArgTy->isFunctionType())
1182 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001183 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001184 return record_type_class;
1185 else if (ArgTy->isUnionType())
1186 return union_type_class;
1187 else if (ArgTy->isArrayType())
1188 return array_type_class;
1189 else if (ArgTy->isUnionType())
1190 return union_type_class;
1191 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1192 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1193 return -1;
1194}
1195
John McCall42c8f872010-05-10 23:27:23 +00001196/// Retrieves the "underlying object type" of the given expression,
1197/// as used by __builtin_object_size.
1198QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1199 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1200 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1201 return VD->getType();
1202 } else if (isa<CompoundLiteralExpr>(E)) {
1203 return E->getType();
1204 }
1205
1206 return QualType();
1207}
1208
1209bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1210 // TODO: Perhaps we should let LLVM lower this?
1211 LValue Base;
1212 if (!EvaluatePointer(E->getArg(0), Base, Info))
1213 return false;
1214
1215 // If we can prove the base is null, lower to zero now.
1216 const Expr *LVBase = Base.getLValueBase();
1217 if (!LVBase) return Success(0, E);
1218
1219 QualType T = GetObjectType(LVBase);
1220 if (T.isNull() ||
1221 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001222 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001223 T->isVariablyModifiedType() ||
1224 T->isDependentType())
1225 return false;
1226
1227 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1228 CharUnits Offset = Base.getLValueOffset();
1229
1230 if (!Offset.isNegative() && Offset <= Size)
1231 Size -= Offset;
1232 else
1233 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001234 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001235}
1236
Eli Friedmanc4a26382010-02-13 00:10:10 +00001237bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001238 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001239 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001240 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001241
1242 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001243 if (TryEvaluateBuiltinObjectSize(E))
1244 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001245
Eric Christopherb2aaf512010-01-19 22:58:35 +00001246 // If evaluating the argument has side-effects we can't determine
1247 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001248 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001249 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001250 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001251 return Success(0, E);
1252 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001253
Mike Stump64eda9e2009-10-26 18:35:08 +00001254 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1255 }
1256
Chris Lattner019f4e82008-10-06 05:28:25 +00001257 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001258 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001260 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001261 // __builtin_constant_p always has one operand: it returns true if that
1262 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001263 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001264
1265 case Builtin::BI__builtin_eh_return_data_regno: {
1266 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1267 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1268 return Success(Operand, E);
1269 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001270
1271 case Builtin::BI__builtin_expect:
1272 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001273
1274 case Builtin::BIstrlen:
1275 case Builtin::BI__builtin_strlen:
1276 // As an extension, we support strlen() and __builtin_strlen() as constant
1277 // expressions when the argument is a string literal.
1278 if (StringLiteral *S
1279 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1280 // The string literal may have embedded null characters. Find the first
1281 // one and truncate there.
1282 llvm::StringRef Str = S->getString();
1283 llvm::StringRef::size_type Pos = Str.find(0);
1284 if (Pos != llvm::StringRef::npos)
1285 Str = Str.substr(0, Pos);
1286
1287 return Success(Str.size(), E);
1288 }
1289
1290 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001291 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001292}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001293
Chris Lattnerb542afe2008-07-11 19:10:17 +00001294bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001295 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001296 if (!Visit(E->getRHS()))
1297 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001298
Eli Friedman33ef1452009-02-26 10:19:36 +00001299 // If we can't evaluate the LHS, it might have side effects;
1300 // conservatively mark it.
1301 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1302 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001303
Anders Carlsson027f62e2008-12-01 02:07:06 +00001304 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001305 }
1306
1307 if (E->isLogicalOp()) {
1308 // These need to be handled specially because the operands aren't
1309 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001310 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001312 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001313 // We were able to evaluate the LHS, see if we can get away with not
1314 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001315 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001316 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001317
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001318 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001319 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001320 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001321 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001322 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001323 }
1324 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001325 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001326 // We can't evaluate the LHS; however, sometimes the result
1327 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001328 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1329 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001330 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001331 // must have had side effects.
1332 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001333
1334 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001335 }
1336 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001337 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001338
Eli Friedmana6afa762008-11-13 06:09:17 +00001339 return false;
1340 }
1341
Anders Carlsson286f85e2008-11-16 07:17:21 +00001342 QualType LHSTy = E->getLHS()->getType();
1343 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001344
1345 if (LHSTy->isAnyComplexType()) {
1346 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001347 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001348
1349 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1350 return false;
1351
1352 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1353 return false;
1354
1355 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001356 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001357 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001358 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001359 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1360
John McCall2de56d12010-08-25 11:45:40 +00001361 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001362 return Success((CR_r == APFloat::cmpEqual &&
1363 CR_i == APFloat::cmpEqual), E);
1364 else {
John McCall2de56d12010-08-25 11:45:40 +00001365 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001366 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001367 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001368 CR_r == APFloat::cmpLessThan ||
1369 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001370 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001371 CR_i == APFloat::cmpLessThan ||
1372 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001373 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001374 } else {
John McCall2de56d12010-08-25 11:45:40 +00001375 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001376 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1377 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1378 else {
John McCall2de56d12010-08-25 11:45:40 +00001379 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001380 "Invalid compex comparison.");
1381 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1382 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1383 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001384 }
1385 }
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Anders Carlsson286f85e2008-11-16 07:17:21 +00001387 if (LHSTy->isRealFloatingType() &&
1388 RHSTy->isRealFloatingType()) {
1389 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Anders Carlsson286f85e2008-11-16 07:17:21 +00001391 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1392 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Anders Carlsson286f85e2008-11-16 07:17:21 +00001394 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1395 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Anders Carlsson286f85e2008-11-16 07:17:21 +00001397 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001398
Anders Carlsson286f85e2008-11-16 07:17:21 +00001399 switch (E->getOpcode()) {
1400 default:
1401 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001402 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001403 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001404 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001405 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001406 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001407 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001408 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001409 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001410 E);
John McCall2de56d12010-08-25 11:45:40 +00001411 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001412 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001413 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001414 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001415 || CR == APFloat::cmpLessThan
1416 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001417 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001418 }
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001420 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001421 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001422 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001423 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1424 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001425
John McCallefdb83e2010-05-07 21:00:08 +00001426 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001427 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1428 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001429
Eli Friedman5bc86102009-06-14 02:17:33 +00001430 // Reject any bases from the normal codepath; we special-case comparisons
1431 // to null.
1432 if (LHSValue.getLValueBase()) {
1433 if (!E->isEqualityOp())
1434 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001435 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001436 return false;
1437 bool bres;
1438 if (!EvalPointerValueAsBool(LHSValue, bres))
1439 return false;
John McCall2de56d12010-08-25 11:45:40 +00001440 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001441 } else if (RHSValue.getLValueBase()) {
1442 if (!E->isEqualityOp())
1443 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001444 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001445 return false;
1446 bool bres;
1447 if (!EvalPointerValueAsBool(RHSValue, bres))
1448 return false;
John McCall2de56d12010-08-25 11:45:40 +00001449 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001450 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001451
John McCall2de56d12010-08-25 11:45:40 +00001452 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001453 QualType Type = E->getLHS()->getType();
1454 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001455
Ken Dycka7305832010-01-15 12:37:54 +00001456 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001457 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001458 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001459
Ken Dycka7305832010-01-15 12:37:54 +00001460 CharUnits Diff = LHSValue.getLValueOffset() -
1461 RHSValue.getLValueOffset();
1462 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001463 }
1464 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001465 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001466 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001467 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001468 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1469 }
1470 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001471 }
1472 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001473 if (!LHSTy->isIntegralOrEnumerationType() ||
1474 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001475 // We can't continue from here for non-integral types, and they
1476 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001477 return false;
1478 }
1479
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001480 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001481 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001482 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001483
Eli Friedman42edd0d2009-03-24 01:14:50 +00001484 APValue RHSVal;
1485 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001486 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001487
1488 // Handle cases like (unsigned long)&a + 4.
1489 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001490 CharUnits Offset = Result.getLValueOffset();
1491 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1492 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001493 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001494 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001495 else
Ken Dycka7305832010-01-15 12:37:54 +00001496 Offset -= AdditionalOffset;
1497 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001498 return true;
1499 }
1500
1501 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001502 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001503 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001504 CharUnits Offset = RHSVal.getLValueOffset();
1505 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1506 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001507 return true;
1508 }
1509
1510 // All the following cases expect both operands to be an integer
1511 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001512 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001513
Eli Friedman42edd0d2009-03-24 01:14:50 +00001514 APSInt& RHS = RHSVal.getInt();
1515
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001516 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001517 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001518 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001519 case BO_Mul: return Success(Result.getInt() * RHS, E);
1520 case BO_Add: return Success(Result.getInt() + RHS, E);
1521 case BO_Sub: return Success(Result.getInt() - RHS, E);
1522 case BO_And: return Success(Result.getInt() & RHS, E);
1523 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1524 case BO_Or: return Success(Result.getInt() | RHS, E);
1525 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001526 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001527 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001528 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001529 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001530 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001531 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001532 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001533 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001534 // During constant-folding, a negative shift is an opposite shift.
1535 if (RHS.isSigned() && RHS.isNegative()) {
1536 RHS = -RHS;
1537 goto shift_right;
1538 }
1539
1540 shift_left:
1541 unsigned SA
1542 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001543 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001544 }
John McCall2de56d12010-08-25 11:45:40 +00001545 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001546 // During constant-folding, a negative shift is an opposite shift.
1547 if (RHS.isSigned() && RHS.isNegative()) {
1548 RHS = -RHS;
1549 goto shift_left;
1550 }
1551
1552 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001553 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001554 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1555 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001556 }
Mike Stump1eb44332009-09-09 15:08:12 +00001557
John McCall2de56d12010-08-25 11:45:40 +00001558 case BO_LT: return Success(Result.getInt() < RHS, E);
1559 case BO_GT: return Success(Result.getInt() > RHS, E);
1560 case BO_LE: return Success(Result.getInt() <= RHS, E);
1561 case BO_GE: return Success(Result.getInt() >= RHS, E);
1562 case BO_EQ: return Success(Result.getInt() == RHS, E);
1563 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001564 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001565}
1566
John McCall56ca35d2011-02-17 10:25:35 +00001567bool IntExprEvaluator::
1568VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
1569 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
1570 if (opaque.hasError()) return false;
1571
1572 bool cond;
1573 if (!HandleConversionToBool(e->getCond(), cond, Info))
1574 return false;
1575
1576 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
1577}
1578
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001579bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001580 bool Cond;
1581 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001582 return false;
1583
Nuno Lopesa25bd552008-11-16 22:06:39 +00001584 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001585}
1586
Ken Dyck8b752f12010-01-27 17:10:57 +00001587CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001588 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1589 // the result is the size of the referenced type."
1590 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1591 // result shall be the alignment of the referenced type."
1592 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1593 T = Ref->getPointeeType();
1594
Eli Friedman2be58612009-05-30 21:09:44 +00001595 // __alignof is defined to return the preferred alignment.
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001596 return Info.Ctx.toCharUnitsFromBits(
1597 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001598}
1599
Ken Dyck8b752f12010-01-27 17:10:57 +00001600CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001601 E = E->IgnoreParens();
1602
1603 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001604 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001605 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001606 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1607 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001608
Chris Lattneraf707ab2009-01-24 21:53:27 +00001609 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001610 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1611 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001612
Chris Lattnere9feb472009-01-24 21:09:06 +00001613 return GetAlignOfType(E->getType());
1614}
1615
1616
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001617/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1618/// a result as the expression's type.
1619bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1620 const UnaryExprOrTypeTraitExpr *E) {
1621 switch(E->getKind()) {
1622 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001623 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001624 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001625 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001626 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001627 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001628
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001629 case UETT_VecStep: {
1630 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001631
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001632 if (Ty->isVectorType()) {
1633 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001634
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001635 // The vec_step built-in functions that take a 3-component
1636 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1637 if (n == 3)
1638 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001639
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001640 return Success(n, E);
1641 } else
1642 return Success(1, E);
1643 }
1644
1645 case UETT_SizeOf: {
1646 QualType SrcTy = E->getTypeOfArgument();
1647 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1648 // the result is the size of the referenced type."
1649 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1650 // result shall be the alignment of the referenced type."
1651 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1652 SrcTy = Ref->getPointeeType();
1653
1654 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1655 // extension.
1656 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1657 return Success(1, E);
1658
1659 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1660 if (!SrcTy->isConstantSizeType())
1661 return false;
1662
1663 // Get information about the size.
1664 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1665 }
1666 }
1667
1668 llvm_unreachable("unknown expr/type trait");
1669 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001670}
1671
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001672bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1673 CharUnits Result;
1674 unsigned n = E->getNumComponents();
1675 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1676 if (n == 0)
1677 return false;
1678 QualType CurrentType = E->getTypeSourceInfo()->getType();
1679 for (unsigned i = 0; i != n; ++i) {
1680 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1681 switch (ON.getKind()) {
1682 case OffsetOfExpr::OffsetOfNode::Array: {
1683 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1684 APSInt IdxResult;
1685 if (!EvaluateInteger(Idx, IdxResult, Info))
1686 return false;
1687 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1688 if (!AT)
1689 return false;
1690 CurrentType = AT->getElementType();
1691 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1692 Result += IdxResult.getSExtValue() * ElementSize;
1693 break;
1694 }
1695
1696 case OffsetOfExpr::OffsetOfNode::Field: {
1697 FieldDecl *MemberDecl = ON.getField();
1698 const RecordType *RT = CurrentType->getAs<RecordType>();
1699 if (!RT)
1700 return false;
1701 RecordDecl *RD = RT->getDecl();
1702 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001703 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001704 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001705 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001706 CurrentType = MemberDecl->getType().getNonReferenceType();
1707 break;
1708 }
1709
1710 case OffsetOfExpr::OffsetOfNode::Identifier:
1711 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001712 return false;
1713
1714 case OffsetOfExpr::OffsetOfNode::Base: {
1715 CXXBaseSpecifier *BaseSpec = ON.getBase();
1716 if (BaseSpec->isVirtual())
1717 return false;
1718
1719 // Find the layout of the class whose base we are looking into.
1720 const RecordType *RT = CurrentType->getAs<RecordType>();
1721 if (!RT)
1722 return false;
1723 RecordDecl *RD = RT->getDecl();
1724 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1725
1726 // Find the base class itself.
1727 CurrentType = BaseSpec->getType();
1728 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1729 if (!BaseRT)
1730 return false;
1731
1732 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001733 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001734 break;
1735 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001736 }
1737 }
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001738 return Success(Result, E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001739}
1740
Chris Lattnerb542afe2008-07-11 19:10:17 +00001741bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001742 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001743 // LNot's operand isn't necessarily an integer, so we handle it specially.
1744 bool bres;
1745 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1746 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001747 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001748 }
1749
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001750 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001751 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001752 return false;
1753
Chris Lattner87eae5e2008-07-11 22:52:41 +00001754 // Get the operand value into 'Result'.
1755 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001756 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001757
Chris Lattner75a48812008-07-11 22:15:16 +00001758 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001759 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001760 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1761 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001762 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001763 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001764 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1765 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001766 return true;
John McCall2de56d12010-08-25 11:45:40 +00001767 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001768 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001769 return true;
John McCall2de56d12010-08-25 11:45:40 +00001770 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001771 if (!Result.isInt()) return false;
1772 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001773 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001774 if (!Result.isInt()) return false;
1775 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001776 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001777}
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Chris Lattner732b2232008-07-12 01:15:53 +00001779/// HandleCast - This is used to evaluate implicit or explicit casts where the
1780/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001781bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001782 Expr *SubExpr = E->getSubExpr();
1783 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001784 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001785
Eli Friedman46a52322011-03-25 00:43:55 +00001786 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001787 case CK_BaseToDerived:
1788 case CK_DerivedToBase:
1789 case CK_UncheckedDerivedToBase:
1790 case CK_Dynamic:
1791 case CK_ToUnion:
1792 case CK_ArrayToPointerDecay:
1793 case CK_FunctionToPointerDecay:
1794 case CK_NullToPointer:
1795 case CK_NullToMemberPointer:
1796 case CK_BaseToDerivedMemberPointer:
1797 case CK_DerivedToBaseMemberPointer:
1798 case CK_ConstructorConversion:
1799 case CK_IntegralToPointer:
1800 case CK_ToVoid:
1801 case CK_VectorSplat:
1802 case CK_IntegralToFloating:
1803 case CK_FloatingCast:
1804 case CK_AnyPointerToObjCPointerCast:
1805 case CK_AnyPointerToBlockPointerCast:
1806 case CK_ObjCObjectLValueCast:
1807 case CK_FloatingRealToComplex:
1808 case CK_FloatingComplexToReal:
1809 case CK_FloatingComplexCast:
1810 case CK_FloatingComplexToIntegralComplex:
1811 case CK_IntegralRealToComplex:
1812 case CK_IntegralComplexCast:
1813 case CK_IntegralComplexToFloatingComplex:
1814 llvm_unreachable("invalid cast kind for integral value");
1815
Eli Friedmane50c2972011-03-25 19:07:11 +00001816 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001817 case CK_Dependent:
1818 case CK_GetObjCProperty:
1819 case CK_LValueBitCast:
1820 case CK_UserDefinedConversion:
1821 return false;
1822
1823 case CK_LValueToRValue:
1824 case CK_NoOp:
1825 return Visit(E->getSubExpr());
1826
1827 case CK_MemberPointerToBoolean:
1828 case CK_PointerToBoolean:
1829 case CK_IntegralToBoolean:
1830 case CK_FloatingToBoolean:
1831 case CK_FloatingComplexToBoolean:
1832 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001833 bool BoolResult;
1834 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1835 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001836 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001837 }
1838
Eli Friedman46a52322011-03-25 00:43:55 +00001839 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001840 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001841 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001842
Eli Friedmanbe265702009-02-20 01:15:07 +00001843 if (!Result.isInt()) {
1844 // Only allow casts of lvalues if they are lossless.
1845 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1846 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001847
Daniel Dunbardd211642009-02-19 22:24:01 +00001848 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001849 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001850 }
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Eli Friedman46a52322011-03-25 00:43:55 +00001852 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001853 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001854 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001855 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001856
Daniel Dunbardd211642009-02-19 22:24:01 +00001857 if (LV.getLValueBase()) {
1858 // Only allow based lvalue casts if they are lossless.
1859 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1860 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001861
John McCallefdb83e2010-05-07 21:00:08 +00001862 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001863 return true;
1864 }
1865
Ken Dycka7305832010-01-15 12:37:54 +00001866 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1867 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001868 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001869 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001870
Eli Friedman46a52322011-03-25 00:43:55 +00001871 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001872 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001873 if (!EvaluateComplex(SubExpr, C, Info))
1874 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001875 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001876 }
Eli Friedman2217c872009-02-22 11:46:18 +00001877
Eli Friedman46a52322011-03-25 00:43:55 +00001878 case CK_FloatingToIntegral: {
1879 APFloat F(0.0);
1880 if (!EvaluateFloat(SubExpr, F, Info))
1881 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001882
Eli Friedman46a52322011-03-25 00:43:55 +00001883 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1884 }
1885 }
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Eli Friedman46a52322011-03-25 00:43:55 +00001887 llvm_unreachable("unknown cast resulting in integral value");
1888 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001889}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001890
Eli Friedman722c7172009-02-28 03:59:05 +00001891bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1892 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001893 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001894 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1895 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1896 return Success(LV.getComplexIntReal(), E);
1897 }
1898
1899 return Visit(E->getSubExpr());
1900}
1901
Eli Friedman664a1042009-02-27 04:45:43 +00001902bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001903 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001904 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001905 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1906 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1907 return Success(LV.getComplexIntImag(), E);
1908 }
1909
Eli Friedman664a1042009-02-27 04:45:43 +00001910 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1911 Info.EvalResult.HasSideEffects = true;
1912 return Success(0, E);
1913}
1914
Douglas Gregoree8aff02011-01-04 17:33:58 +00001915bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1916 return Success(E->getPackLength(), E);
1917}
1918
Sebastian Redl295995c2010-09-10 20:55:47 +00001919bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1920 return Success(E->getValue(), E);
1921}
1922
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001923//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001924// Float Evaluation
1925//===----------------------------------------------------------------------===//
1926
1927namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001928class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001929 : public StmtVisitor<FloatExprEvaluator, bool> {
1930 EvalInfo &Info;
1931 APFloat &Result;
1932public:
1933 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1934 : Info(info), Result(result) {}
1935
1936 bool VisitStmt(Stmt *S) {
1937 return false;
1938 }
1939
1940 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +00001941 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
1942 return Visit(E->getResultExpr());
1943 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001944 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001945
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001946 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001947 bool VisitBinaryOperator(const BinaryOperator *E);
1948 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001949 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001950 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001951 bool VisitConditionalOperator(ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001952 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001953
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001954 bool VisitChooseExpr(const ChooseExpr *E)
1955 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1956 bool VisitUnaryExtension(const UnaryOperator *E)
1957 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001958 bool VisitUnaryReal(const UnaryOperator *E);
1959 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001960
John McCall189d6ef2010-10-09 01:34:31 +00001961 bool VisitDeclRefExpr(const DeclRefExpr *E);
1962
John McCall56ca35d2011-02-17 10:25:35 +00001963 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
1964 const APValue *value = Info.getOpaqueValue(e);
1965 if (!value)
1966 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
1967 Result = value->getFloat();
1968 return true;
1969 }
1970
John McCallabd3a852010-05-07 22:08:54 +00001971 // FIXME: Missing: array subscript of vector, member of vector,
1972 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001973};
1974} // end anonymous namespace
1975
1976static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001977 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001978 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1979}
1980
Jay Foad4ba2a172011-01-12 09:06:06 +00001981static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001982 QualType ResultTy,
1983 const Expr *Arg,
1984 bool SNaN,
1985 llvm::APFloat &Result) {
1986 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1987 if (!S) return false;
1988
1989 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1990
1991 llvm::APInt fill;
1992
1993 // Treat empty strings as if they were zero.
1994 if (S->getString().empty())
1995 fill = llvm::APInt(32, 0);
1996 else if (S->getString().getAsInteger(0, fill))
1997 return false;
1998
1999 if (SNaN)
2000 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2001 else
2002 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2003 return true;
2004}
2005
Chris Lattner019f4e82008-10-06 05:28:25 +00002006bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00002007 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00002008 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00002009 case Builtin::BI__builtin_huge_val:
2010 case Builtin::BI__builtin_huge_valf:
2011 case Builtin::BI__builtin_huge_vall:
2012 case Builtin::BI__builtin_inf:
2013 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002014 case Builtin::BI__builtin_infl: {
2015 const llvm::fltSemantics &Sem =
2016 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002017 Result = llvm::APFloat::getInf(Sem);
2018 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002019 }
Mike Stump1eb44332009-09-09 15:08:12 +00002020
John McCalldb7b72a2010-02-28 13:00:19 +00002021 case Builtin::BI__builtin_nans:
2022 case Builtin::BI__builtin_nansf:
2023 case Builtin::BI__builtin_nansl:
2024 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2025 true, Result);
2026
Chris Lattner9e621712008-10-06 06:31:58 +00002027 case Builtin::BI__builtin_nan:
2028 case Builtin::BI__builtin_nanf:
2029 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002030 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002031 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002032 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2033 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002034
2035 case Builtin::BI__builtin_fabs:
2036 case Builtin::BI__builtin_fabsf:
2037 case Builtin::BI__builtin_fabsl:
2038 if (!EvaluateFloat(E->getArg(0), Result, Info))
2039 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002041 if (Result.isNegative())
2042 Result.changeSign();
2043 return true;
2044
Mike Stump1eb44332009-09-09 15:08:12 +00002045 case Builtin::BI__builtin_copysign:
2046 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002047 case Builtin::BI__builtin_copysignl: {
2048 APFloat RHS(0.);
2049 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2050 !EvaluateFloat(E->getArg(1), RHS, Info))
2051 return false;
2052 Result.copySign(RHS);
2053 return true;
2054 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002055 }
2056}
2057
John McCall189d6ef2010-10-09 01:34:31 +00002058bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2059 const Decl *D = E->getDecl();
2060 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2061 const VarDecl *VD = cast<VarDecl>(D);
2062
2063 // Require the qualifiers to be const and not volatile.
2064 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2065 if (!T.isConstQualified() || T.isVolatileQualified())
2066 return false;
2067
2068 const Expr *Init = VD->getAnyInitializer();
2069 if (!Init) return false;
2070
2071 if (APValue *V = VD->getEvaluatedValue()) {
2072 if (V->isFloat()) {
2073 Result = V->getFloat();
2074 return true;
2075 }
2076 return false;
2077 }
2078
2079 if (VD->isEvaluatingValue())
2080 return false;
2081
2082 VD->setEvaluatingValue();
2083
2084 Expr::EvalResult InitResult;
2085 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2086 InitResult.Val.isFloat()) {
2087 // Cache the evaluated value in the variable declaration.
2088 Result = InitResult.Val.getFloat();
2089 VD->setEvaluatedValue(InitResult.Val);
2090 return true;
2091 }
2092
2093 VD->setEvaluatedValue(APValue());
2094 return false;
2095}
2096
John McCallabd3a852010-05-07 22:08:54 +00002097bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002098 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2099 ComplexValue CV;
2100 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2101 return false;
2102 Result = CV.FloatReal;
2103 return true;
2104 }
2105
2106 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002107}
2108
2109bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002110 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2111 ComplexValue CV;
2112 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2113 return false;
2114 Result = CV.FloatImag;
2115 return true;
2116 }
2117
2118 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2119 Info.EvalResult.HasSideEffects = true;
2120 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2121 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002122 return true;
2123}
2124
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002125bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002126 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002127 return false;
2128
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002129 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2130 return false;
2131
2132 switch (E->getOpcode()) {
2133 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002134 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002135 return true;
John McCall2de56d12010-08-25 11:45:40 +00002136 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002137 Result.changeSign();
2138 return true;
2139 }
2140}
Chris Lattner019f4e82008-10-06 05:28:25 +00002141
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002142bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002143 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002144 if (!EvaluateFloat(E->getRHS(), Result, Info))
2145 return false;
2146
2147 // If we can't evaluate the LHS, it might have side effects;
2148 // conservatively mark it.
2149 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2150 Info.EvalResult.HasSideEffects = true;
2151
2152 return true;
2153 }
2154
Anders Carlsson96e93662010-10-31 01:21:47 +00002155 // We can't evaluate pointer-to-member operations.
2156 if (E->isPtrMemOp())
2157 return false;
2158
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002159 // FIXME: Diagnostics? I really don't understand how the warnings
2160 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002161 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002162 if (!EvaluateFloat(E->getLHS(), Result, Info))
2163 return false;
2164 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2165 return false;
2166
2167 switch (E->getOpcode()) {
2168 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002169 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002170 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2171 return true;
John McCall2de56d12010-08-25 11:45:40 +00002172 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002173 Result.add(RHS, APFloat::rmNearestTiesToEven);
2174 return true;
John McCall2de56d12010-08-25 11:45:40 +00002175 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002176 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2177 return true;
John McCall2de56d12010-08-25 11:45:40 +00002178 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002179 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2180 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002181 }
2182}
2183
2184bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2185 Result = E->getValue();
2186 return true;
2187}
2188
Eli Friedman4efaa272008-11-12 09:44:48 +00002189bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2190 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Eli Friedman2a523ee2011-03-25 00:54:52 +00002192 switch (E->getCastKind()) {
2193 default:
2194 return false;
2195
2196 case CK_LValueToRValue:
2197 case CK_NoOp:
2198 return Visit(SubExpr);
2199
2200 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002201 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002202 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002203 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002204 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002205 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002206 return true;
2207 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002208
2209 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002210 if (!Visit(SubExpr))
2211 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002212 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2213 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002214 return true;
2215 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002216
Eli Friedman2a523ee2011-03-25 00:54:52 +00002217 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002218 ComplexValue V;
2219 if (!EvaluateComplex(SubExpr, V, Info))
2220 return false;
2221 Result = V.getComplexFloatReal();
2222 return true;
2223 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002224 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002225
2226 return false;
2227}
2228
Douglas Gregored8abf12010-07-08 06:14:04 +00002229bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002230 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2231 return true;
2232}
2233
John McCall56ca35d2011-02-17 10:25:35 +00002234bool FloatExprEvaluator::
2235VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
2236 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2237 if (opaque.hasError()) return false;
2238
2239 bool cond;
2240 if (!HandleConversionToBool(e->getCond(), cond, Info))
2241 return false;
2242
2243 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2244}
2245
Eli Friedman67f85fc2009-12-04 02:12:53 +00002246bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2247 bool Cond;
2248 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2249 return false;
2250
2251 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2252}
2253
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002254//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002255// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002256//===----------------------------------------------------------------------===//
2257
2258namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002259class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00002260 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002261 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00002262 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002264public:
John McCallf4cf1a12010-05-07 17:22:02 +00002265 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2266 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002268 //===--------------------------------------------------------------------===//
2269 // Visitor Methods
2270 //===--------------------------------------------------------------------===//
2271
John McCallf4cf1a12010-05-07 17:22:02 +00002272 bool VisitStmt(Stmt *S) {
2273 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002274 }
Mike Stump1eb44332009-09-09 15:08:12 +00002275
John McCallf4cf1a12010-05-07 17:22:02 +00002276 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +00002277 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
2278 return Visit(E->getResultExpr());
2279 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002280
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002281 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002282
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002283 bool VisitCastExpr(CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002284
John McCallf4cf1a12010-05-07 17:22:02 +00002285 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002286 bool VisitUnaryOperator(const UnaryOperator *E);
2287 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00002288 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
John McCallf4cf1a12010-05-07 17:22:02 +00002289 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002290 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002291 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002292 { return Visit(E->getSubExpr()); }
John McCall56ca35d2011-02-17 10:25:35 +00002293 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
2294 const APValue *value = Info.getOpaqueValue(e);
2295 if (!value)
2296 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
2297 Result.setFrom(*value);
2298 return true;
2299 }
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002300 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002301};
2302} // end anonymous namespace
2303
John McCallf4cf1a12010-05-07 17:22:02 +00002304static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2305 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002306 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002307 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002308}
2309
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002310bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2311 Expr* SubExpr = E->getSubExpr();
2312
2313 if (SubExpr->getType()->isRealFloatingType()) {
2314 Result.makeComplexFloat();
2315 APFloat &Imag = Result.FloatImag;
2316 if (!EvaluateFloat(SubExpr, Imag, Info))
2317 return false;
2318
2319 Result.FloatReal = APFloat(Imag.getSemantics());
2320 return true;
2321 } else {
2322 assert(SubExpr->getType()->isIntegerType() &&
2323 "Unexpected imaginary literal.");
2324
2325 Result.makeComplexInt();
2326 APSInt &Imag = Result.IntImag;
2327 if (!EvaluateInteger(SubExpr, Imag, Info))
2328 return false;
2329
2330 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2331 return true;
2332 }
2333}
2334
2335bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002336
John McCall8786da72010-12-14 17:51:41 +00002337 switch (E->getCastKind()) {
2338 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002339 case CK_BaseToDerived:
2340 case CK_DerivedToBase:
2341 case CK_UncheckedDerivedToBase:
2342 case CK_Dynamic:
2343 case CK_ToUnion:
2344 case CK_ArrayToPointerDecay:
2345 case CK_FunctionToPointerDecay:
2346 case CK_NullToPointer:
2347 case CK_NullToMemberPointer:
2348 case CK_BaseToDerivedMemberPointer:
2349 case CK_DerivedToBaseMemberPointer:
2350 case CK_MemberPointerToBoolean:
2351 case CK_ConstructorConversion:
2352 case CK_IntegralToPointer:
2353 case CK_PointerToIntegral:
2354 case CK_PointerToBoolean:
2355 case CK_ToVoid:
2356 case CK_VectorSplat:
2357 case CK_IntegralCast:
2358 case CK_IntegralToBoolean:
2359 case CK_IntegralToFloating:
2360 case CK_FloatingToIntegral:
2361 case CK_FloatingToBoolean:
2362 case CK_FloatingCast:
2363 case CK_AnyPointerToObjCPointerCast:
2364 case CK_AnyPointerToBlockPointerCast:
2365 case CK_ObjCObjectLValueCast:
2366 case CK_FloatingComplexToReal:
2367 case CK_FloatingComplexToBoolean:
2368 case CK_IntegralComplexToReal:
2369 case CK_IntegralComplexToBoolean:
2370 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002371
John McCall8786da72010-12-14 17:51:41 +00002372 case CK_LValueToRValue:
2373 case CK_NoOp:
2374 return Visit(E->getSubExpr());
2375
2376 case CK_Dependent:
2377 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002378 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002379 case CK_UserDefinedConversion:
2380 return false;
2381
2382 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002383 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002384 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002385 return false;
2386
John McCall8786da72010-12-14 17:51:41 +00002387 Result.makeComplexFloat();
2388 Result.FloatImag = APFloat(Real.getSemantics());
2389 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002390 }
2391
John McCall8786da72010-12-14 17:51:41 +00002392 case CK_FloatingComplexCast: {
2393 if (!Visit(E->getSubExpr()))
2394 return false;
2395
2396 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2397 QualType From
2398 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2399
2400 Result.FloatReal
2401 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2402 Result.FloatImag
2403 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2404 return true;
2405 }
2406
2407 case CK_FloatingComplexToIntegralComplex: {
2408 if (!Visit(E->getSubExpr()))
2409 return false;
2410
2411 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2412 QualType From
2413 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2414 Result.makeComplexInt();
2415 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2416 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2417 return true;
2418 }
2419
2420 case CK_IntegralRealToComplex: {
2421 APSInt &Real = Result.IntReal;
2422 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2423 return false;
2424
2425 Result.makeComplexInt();
2426 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2427 return true;
2428 }
2429
2430 case CK_IntegralComplexCast: {
2431 if (!Visit(E->getSubExpr()))
2432 return false;
2433
2434 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2435 QualType From
2436 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2437
2438 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2439 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2440 return true;
2441 }
2442
2443 case CK_IntegralComplexToFloatingComplex: {
2444 if (!Visit(E->getSubExpr()))
2445 return false;
2446
2447 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2448 QualType From
2449 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2450 Result.makeComplexFloat();
2451 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2452 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2453 return true;
2454 }
2455 }
2456
2457 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002458 return false;
2459}
2460
John McCallf4cf1a12010-05-07 17:22:02 +00002461bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002462 if (E->getOpcode() == BO_Comma) {
2463 if (!Visit(E->getRHS()))
2464 return false;
2465
2466 // If we can't evaluate the LHS, it might have side effects;
2467 // conservatively mark it.
2468 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2469 Info.EvalResult.HasSideEffects = true;
2470
2471 return true;
2472 }
John McCallf4cf1a12010-05-07 17:22:02 +00002473 if (!Visit(E->getLHS()))
2474 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002475
John McCallf4cf1a12010-05-07 17:22:02 +00002476 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002477 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002478 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002479
Daniel Dunbar3f279872009-01-29 01:32:56 +00002480 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2481 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002482 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002483 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002484 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002485 if (Result.isComplexFloat()) {
2486 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2487 APFloat::rmNearestTiesToEven);
2488 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2489 APFloat::rmNearestTiesToEven);
2490 } else {
2491 Result.getComplexIntReal() += RHS.getComplexIntReal();
2492 Result.getComplexIntImag() += RHS.getComplexIntImag();
2493 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002494 break;
John McCall2de56d12010-08-25 11:45:40 +00002495 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002496 if (Result.isComplexFloat()) {
2497 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2498 APFloat::rmNearestTiesToEven);
2499 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2500 APFloat::rmNearestTiesToEven);
2501 } else {
2502 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2503 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2504 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002505 break;
John McCall2de56d12010-08-25 11:45:40 +00002506 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002507 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002508 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002509 APFloat &LHS_r = LHS.getComplexFloatReal();
2510 APFloat &LHS_i = LHS.getComplexFloatImag();
2511 APFloat &RHS_r = RHS.getComplexFloatReal();
2512 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Daniel Dunbar3f279872009-01-29 01:32:56 +00002514 APFloat Tmp = LHS_r;
2515 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2516 Result.getComplexFloatReal() = Tmp;
2517 Tmp = LHS_i;
2518 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2519 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2520
2521 Tmp = LHS_r;
2522 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2523 Result.getComplexFloatImag() = Tmp;
2524 Tmp = LHS_i;
2525 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2526 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2527 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002528 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002529 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002530 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2531 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002532 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002533 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2534 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2535 }
2536 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002537 case BO_Div:
2538 if (Result.isComplexFloat()) {
2539 ComplexValue LHS = Result;
2540 APFloat &LHS_r = LHS.getComplexFloatReal();
2541 APFloat &LHS_i = LHS.getComplexFloatImag();
2542 APFloat &RHS_r = RHS.getComplexFloatReal();
2543 APFloat &RHS_i = RHS.getComplexFloatImag();
2544 APFloat &Res_r = Result.getComplexFloatReal();
2545 APFloat &Res_i = Result.getComplexFloatImag();
2546
2547 APFloat Den = RHS_r;
2548 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2549 APFloat Tmp = RHS_i;
2550 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2551 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2552
2553 Res_r = LHS_r;
2554 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2555 Tmp = LHS_i;
2556 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2557 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2558 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2559
2560 Res_i = LHS_i;
2561 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2562 Tmp = LHS_r;
2563 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2564 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2565 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2566 } else {
2567 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2568 // FIXME: what about diagnostics?
2569 return false;
2570 }
2571 ComplexValue LHS = Result;
2572 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2573 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2574 Result.getComplexIntReal() =
2575 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2576 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2577 Result.getComplexIntImag() =
2578 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2579 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2580 }
2581 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002582 }
2583
John McCallf4cf1a12010-05-07 17:22:02 +00002584 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002585}
2586
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002587bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2588 // Get the operand value into 'Result'.
2589 if (!Visit(E->getSubExpr()))
2590 return false;
2591
2592 switch (E->getOpcode()) {
2593 default:
2594 // FIXME: what about diagnostics?
2595 return false;
2596 case UO_Extension:
2597 return true;
2598 case UO_Plus:
2599 // The result is always just the subexpr.
2600 return true;
2601 case UO_Minus:
2602 if (Result.isComplexFloat()) {
2603 Result.getComplexFloatReal().changeSign();
2604 Result.getComplexFloatImag().changeSign();
2605 }
2606 else {
2607 Result.getComplexIntReal() = -Result.getComplexIntReal();
2608 Result.getComplexIntImag() = -Result.getComplexIntImag();
2609 }
2610 return true;
2611 case UO_Not:
2612 if (Result.isComplexFloat())
2613 Result.getComplexFloatImag().changeSign();
2614 else
2615 Result.getComplexIntImag() = -Result.getComplexIntImag();
2616 return true;
2617 }
2618}
2619
John McCall56ca35d2011-02-17 10:25:35 +00002620bool ComplexExprEvaluator::
2621VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
2622 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2623 if (opaque.hasError()) return false;
2624
2625 bool cond;
2626 if (!HandleConversionToBool(e->getCond(), cond, Info))
2627 return false;
2628
2629 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2630}
2631
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002632bool ComplexExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
2633 bool Cond;
2634 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2635 return false;
2636
2637 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2638}
2639
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002640//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002641// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002642//===----------------------------------------------------------------------===//
2643
John McCall56ca35d2011-02-17 10:25:35 +00002644static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002645 if (E->getType()->isVectorType()) {
2646 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002647 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002648 } else if (E->getType()->isIntegerType()) {
2649 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002650 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002651 if (Info.EvalResult.Val.isLValue() &&
2652 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002653 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002654 } else if (E->getType()->hasPointerRepresentation()) {
2655 LValue LV;
2656 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002657 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002658 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002659 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002660 LV.moveInto(Info.EvalResult.Val);
2661 } else if (E->getType()->isRealFloatingType()) {
2662 llvm::APFloat F(0.0);
2663 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002664 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002665
John McCallefdb83e2010-05-07 21:00:08 +00002666 Info.EvalResult.Val = APValue(F);
2667 } else if (E->getType()->isAnyComplexType()) {
2668 ComplexValue C;
2669 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002670 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002671 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002672 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002673 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002674
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002675 return true;
2676}
2677
John McCall56ca35d2011-02-17 10:25:35 +00002678/// Evaluate - Return true if this is a constant which we can fold using
2679/// any crazy technique (that has nothing to do with language standards) that
2680/// we want to. If this function returns true, it returns the folded constant
2681/// in Result.
2682bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2683 EvalInfo Info(Ctx, Result);
2684 return ::Evaluate(Info, this);
2685}
2686
Jay Foad4ba2a172011-01-12 09:06:06 +00002687bool Expr::EvaluateAsBooleanCondition(bool &Result,
2688 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002689 EvalResult Scratch;
2690 EvalInfo Info(Ctx, Scratch);
2691
2692 return HandleConversionToBool(this, Result, Info);
2693}
2694
Jay Foad4ba2a172011-01-12 09:06:06 +00002695bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002696 EvalInfo Info(Ctx, Result);
2697
John McCallefdb83e2010-05-07 21:00:08 +00002698 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002699 if (EvaluateLValue(this, LV, Info) &&
2700 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002701 IsGlobalLValue(LV.Base)) {
2702 LV.moveInto(Result.Val);
2703 return true;
2704 }
2705 return false;
2706}
2707
Jay Foad4ba2a172011-01-12 09:06:06 +00002708bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2709 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002710 EvalInfo Info(Ctx, Result);
2711
2712 LValue LV;
2713 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002714 LV.moveInto(Result.Val);
2715 return true;
2716 }
2717 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002718}
2719
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002720/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002721/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002722bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002723 EvalResult Result;
2724 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002725}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002726
Jay Foad4ba2a172011-01-12 09:06:06 +00002727bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002728 Expr::EvalResult Result;
2729 EvalInfo Info(Ctx, Result);
2730 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2731}
2732
Jay Foad4ba2a172011-01-12 09:06:06 +00002733APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002734 EvalResult EvalResult;
2735 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002736 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002737 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002738 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002739
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002740 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002741}
John McCalld905f5a2010-05-07 05:32:02 +00002742
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002743 bool Expr::EvalResult::isGlobalLValue() const {
2744 assert(Val.isLValue());
2745 return IsGlobalLValue(Val.getLValueBase());
2746 }
2747
2748
John McCalld905f5a2010-05-07 05:32:02 +00002749/// isIntegerConstantExpr - this recursive routine will test if an expression is
2750/// an integer constant expression.
2751
2752/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2753/// comma, etc
2754///
2755/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2756/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2757/// cast+dereference.
2758
2759// CheckICE - This function does the fundamental ICE checking: the returned
2760// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2761// Note that to reduce code duplication, this helper does no evaluation
2762// itself; the caller checks whether the expression is evaluatable, and
2763// in the rare cases where CheckICE actually cares about the evaluated
2764// value, it calls into Evalute.
2765//
2766// Meanings of Val:
2767// 0: This expression is an ICE if it can be evaluated by Evaluate.
2768// 1: This expression is not an ICE, but if it isn't evaluated, it's
2769// a legal subexpression for an ICE. This return value is used to handle
2770// the comma operator in C99 mode.
2771// 2: This expression is not an ICE, and is not a legal subexpression for one.
2772
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002773namespace {
2774
John McCalld905f5a2010-05-07 05:32:02 +00002775struct ICEDiag {
2776 unsigned Val;
2777 SourceLocation Loc;
2778
2779 public:
2780 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2781 ICEDiag() : Val(0) {}
2782};
2783
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002784}
2785
2786static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002787
2788static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2789 Expr::EvalResult EVResult;
2790 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2791 !EVResult.Val.isInt()) {
2792 return ICEDiag(2, E->getLocStart());
2793 }
2794 return NoDiag();
2795}
2796
2797static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2798 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002799 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002800 return ICEDiag(2, E->getLocStart());
2801 }
2802
2803 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002804#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002805#define STMT(Node, Base) case Expr::Node##Class:
2806#define EXPR(Node, Base)
2807#include "clang/AST/StmtNodes.inc"
2808 case Expr::PredefinedExprClass:
2809 case Expr::FloatingLiteralClass:
2810 case Expr::ImaginaryLiteralClass:
2811 case Expr::StringLiteralClass:
2812 case Expr::ArraySubscriptExprClass:
2813 case Expr::MemberExprClass:
2814 case Expr::CompoundAssignOperatorClass:
2815 case Expr::CompoundLiteralExprClass:
2816 case Expr::ExtVectorElementExprClass:
2817 case Expr::InitListExprClass:
2818 case Expr::DesignatedInitExprClass:
2819 case Expr::ImplicitValueInitExprClass:
2820 case Expr::ParenListExprClass:
2821 case Expr::VAArgExprClass:
2822 case Expr::AddrLabelExprClass:
2823 case Expr::StmtExprClass:
2824 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002825 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002826 case Expr::CXXDynamicCastExprClass:
2827 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002828 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002829 case Expr::CXXNullPtrLiteralExprClass:
2830 case Expr::CXXThisExprClass:
2831 case Expr::CXXThrowExprClass:
2832 case Expr::CXXNewExprClass:
2833 case Expr::CXXDeleteExprClass:
2834 case Expr::CXXPseudoDestructorExprClass:
2835 case Expr::UnresolvedLookupExprClass:
2836 case Expr::DependentScopeDeclRefExprClass:
2837 case Expr::CXXConstructExprClass:
2838 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002839 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002840 case Expr::CXXTemporaryObjectExprClass:
2841 case Expr::CXXUnresolvedConstructExprClass:
2842 case Expr::CXXDependentScopeMemberExprClass:
2843 case Expr::UnresolvedMemberExprClass:
2844 case Expr::ObjCStringLiteralClass:
2845 case Expr::ObjCEncodeExprClass:
2846 case Expr::ObjCMessageExprClass:
2847 case Expr::ObjCSelectorExprClass:
2848 case Expr::ObjCProtocolExprClass:
2849 case Expr::ObjCIvarRefExprClass:
2850 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002851 case Expr::ObjCIsaExprClass:
2852 case Expr::ShuffleVectorExprClass:
2853 case Expr::BlockExprClass:
2854 case Expr::BlockDeclRefExprClass:
2855 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002856 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002857 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002858 case Expr::SubstNonTypeTemplateParmPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002859 return ICEDiag(2, E->getLocStart());
2860
Douglas Gregoree8aff02011-01-04 17:33:58 +00002861 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002862 case Expr::GNUNullExprClass:
2863 // GCC considers the GNU __null value to be an integral constant expression.
2864 return NoDiag();
2865
2866 case Expr::ParenExprClass:
2867 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002868 case Expr::GenericSelectionExprClass:
2869 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002870 case Expr::IntegerLiteralClass:
2871 case Expr::CharacterLiteralClass:
2872 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002873 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002874 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002875 case Expr::BinaryTypeTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002876 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002877 return NoDiag();
2878 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002879 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002880 const CallExpr *CE = cast<CallExpr>(E);
2881 if (CE->isBuiltinCall(Ctx))
2882 return CheckEvalInICE(E, Ctx);
2883 return ICEDiag(2, E->getLocStart());
2884 }
2885 case Expr::DeclRefExprClass:
2886 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2887 return NoDiag();
2888 if (Ctx.getLangOptions().CPlusPlus &&
2889 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2890 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2891
2892 // Parameter variables are never constants. Without this check,
2893 // getAnyInitializer() can find a default argument, which leads
2894 // to chaos.
2895 if (isa<ParmVarDecl>(D))
2896 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2897
2898 // C++ 7.1.5.1p2
2899 // A variable of non-volatile const-qualified integral or enumeration
2900 // type initialized by an ICE can be used in ICEs.
2901 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2902 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2903 if (Quals.hasVolatile() || !Quals.hasConst())
2904 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2905
2906 // Look for a declaration of this variable that has an initializer.
2907 const VarDecl *ID = 0;
2908 const Expr *Init = Dcl->getAnyInitializer(ID);
2909 if (Init) {
2910 if (ID->isInitKnownICE()) {
2911 // We have already checked whether this subexpression is an
2912 // integral constant expression.
2913 if (ID->isInitICE())
2914 return NoDiag();
2915 else
2916 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2917 }
2918
2919 // It's an ICE whether or not the definition we found is
2920 // out-of-line. See DR 721 and the discussion in Clang PR
2921 // 6206 for details.
2922
2923 if (Dcl->isCheckingICE()) {
2924 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2925 }
2926
2927 Dcl->setCheckingICE();
2928 ICEDiag Result = CheckICE(Init, Ctx);
2929 // Cache the result of the ICE test.
2930 Dcl->setInitKnownICE(Result.Val == 0);
2931 return Result;
2932 }
2933 }
2934 }
2935 return ICEDiag(2, E->getLocStart());
2936 case Expr::UnaryOperatorClass: {
2937 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2938 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002939 case UO_PostInc:
2940 case UO_PostDec:
2941 case UO_PreInc:
2942 case UO_PreDec:
2943 case UO_AddrOf:
2944 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002945 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002946 case UO_Extension:
2947 case UO_LNot:
2948 case UO_Plus:
2949 case UO_Minus:
2950 case UO_Not:
2951 case UO_Real:
2952 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002953 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002954 }
2955
2956 // OffsetOf falls through here.
2957 }
2958 case Expr::OffsetOfExprClass: {
2959 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2960 // Evaluate matches the proposed gcc behavior for cases like
2961 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2962 // compliance: we should warn earlier for offsetof expressions with
2963 // array subscripts that aren't ICEs, and if the array subscripts
2964 // are ICEs, the value of the offsetof must be an integer constant.
2965 return CheckEvalInICE(E, Ctx);
2966 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002967 case Expr::UnaryExprOrTypeTraitExprClass: {
2968 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2969 if ((Exp->getKind() == UETT_SizeOf) &&
2970 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002971 return ICEDiag(2, E->getLocStart());
2972 return NoDiag();
2973 }
2974 case Expr::BinaryOperatorClass: {
2975 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2976 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002977 case BO_PtrMemD:
2978 case BO_PtrMemI:
2979 case BO_Assign:
2980 case BO_MulAssign:
2981 case BO_DivAssign:
2982 case BO_RemAssign:
2983 case BO_AddAssign:
2984 case BO_SubAssign:
2985 case BO_ShlAssign:
2986 case BO_ShrAssign:
2987 case BO_AndAssign:
2988 case BO_XorAssign:
2989 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002990 return ICEDiag(2, E->getLocStart());
2991
John McCall2de56d12010-08-25 11:45:40 +00002992 case BO_Mul:
2993 case BO_Div:
2994 case BO_Rem:
2995 case BO_Add:
2996 case BO_Sub:
2997 case BO_Shl:
2998 case BO_Shr:
2999 case BO_LT:
3000 case BO_GT:
3001 case BO_LE:
3002 case BO_GE:
3003 case BO_EQ:
3004 case BO_NE:
3005 case BO_And:
3006 case BO_Xor:
3007 case BO_Or:
3008 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00003009 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3010 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00003011 if (Exp->getOpcode() == BO_Div ||
3012 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00003013 // Evaluate gives an error for undefined Div/Rem, so make sure
3014 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00003015 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00003016 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
3017 if (REval == 0)
3018 return ICEDiag(1, E->getLocStart());
3019 if (REval.isSigned() && REval.isAllOnesValue()) {
3020 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
3021 if (LEval.isMinSignedValue())
3022 return ICEDiag(1, E->getLocStart());
3023 }
3024 }
3025 }
John McCall2de56d12010-08-25 11:45:40 +00003026 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00003027 if (Ctx.getLangOptions().C99) {
3028 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3029 // if it isn't evaluated.
3030 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3031 return ICEDiag(1, E->getLocStart());
3032 } else {
3033 // In both C89 and C++, commas in ICEs are illegal.
3034 return ICEDiag(2, E->getLocStart());
3035 }
3036 }
3037 if (LHSResult.Val >= RHSResult.Val)
3038 return LHSResult;
3039 return RHSResult;
3040 }
John McCall2de56d12010-08-25 11:45:40 +00003041 case BO_LAnd:
3042 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00003043 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3044 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3045 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3046 // Rare case where the RHS has a comma "side-effect"; we need
3047 // to actually check the condition to see whether the side
3048 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003049 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00003050 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3051 return RHSResult;
3052 return NoDiag();
3053 }
3054
3055 if (LHSResult.Val >= RHSResult.Val)
3056 return LHSResult;
3057 return RHSResult;
3058 }
3059 }
3060 }
3061 case Expr::ImplicitCastExprClass:
3062 case Expr::CStyleCastExprClass:
3063 case Expr::CXXFunctionalCastExprClass:
3064 case Expr::CXXStaticCastExprClass:
3065 case Expr::CXXReinterpretCastExprClass:
3066 case Expr::CXXConstCastExprClass: {
3067 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003068 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003069 return CheckICE(SubExpr, Ctx);
3070 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3071 return NoDiag();
3072 return ICEDiag(2, E->getLocStart());
3073 }
John McCall56ca35d2011-02-17 10:25:35 +00003074 case Expr::BinaryConditionalOperatorClass: {
3075 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3076 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3077 if (CommonResult.Val == 2) return CommonResult;
3078 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3079 if (FalseResult.Val == 2) return FalseResult;
3080 if (CommonResult.Val == 1) return CommonResult;
3081 if (FalseResult.Val == 1 &&
3082 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3083 return FalseResult;
3084 }
John McCalld905f5a2010-05-07 05:32:02 +00003085 case Expr::ConditionalOperatorClass: {
3086 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3087 // If the condition (ignoring parens) is a __builtin_constant_p call,
3088 // then only the true side is actually considered in an integer constant
3089 // expression, and it is fully evaluated. This is an important GNU
3090 // extension. See GCC PR38377 for discussion.
3091 if (const CallExpr *CallCE
3092 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3093 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3094 Expr::EvalResult EVResult;
3095 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3096 !EVResult.Val.isInt()) {
3097 return ICEDiag(2, E->getLocStart());
3098 }
3099 return NoDiag();
3100 }
3101 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
3102 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3103 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3104 if (CondResult.Val == 2)
3105 return CondResult;
3106 if (TrueResult.Val == 2)
3107 return TrueResult;
3108 if (FalseResult.Val == 2)
3109 return FalseResult;
3110 if (CondResult.Val == 1)
3111 return CondResult;
3112 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3113 return NoDiag();
3114 // Rare case where the diagnostics depend on which side is evaluated
3115 // Note that if we get here, CondResult is 0, and at least one of
3116 // TrueResult and FalseResult is non-zero.
3117 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3118 return FalseResult;
3119 }
3120 return TrueResult;
3121 }
3122 case Expr::CXXDefaultArgExprClass:
3123 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3124 case Expr::ChooseExprClass: {
3125 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3126 }
3127 }
3128
3129 // Silence a GCC warning
3130 return ICEDiag(2, E->getLocStart());
3131}
3132
3133bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3134 SourceLocation *Loc, bool isEvaluated) const {
3135 ICEDiag d = CheckICE(this, Ctx);
3136 if (d.Val != 0) {
3137 if (Loc) *Loc = d.Loc;
3138 return false;
3139 }
3140 EvalResult EvalResult;
3141 if (!Evaluate(EvalResult, Ctx))
3142 llvm_unreachable("ICE cannot be evaluated!");
3143 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3144 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3145 Result = EvalResult.Val.getInt();
3146 return true;
3147}