blob: 8761aa3f9401b9b6b676d7d5cf3b493cb9d3788d [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.
45struct EvalInfo {
Jay Foad4ba2a172011-01-12 09:06:06 +000046 const ASTContext &Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +000047
Anders Carlsson54da0492008-11-30 16:38:33 +000048 /// EvalResult - Contains information about the evaluation.
49 Expr::EvalResult &EvalResult;
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +000050
Jay Foad4ba2a172011-01-12 09:06:06 +000051 EvalInfo(const ASTContext &ctx, Expr::EvalResult& evalresult)
John McCall42c8f872010-05-10 23:27:23 +000052 : Ctx(ctx), EvalResult(evalresult) {}
Chris Lattner87eae5e2008-07-11 22:52:41 +000053};
54
John McCallf4cf1a12010-05-07 17:22:02 +000055namespace {
56 struct ComplexValue {
57 private:
58 bool IsInt;
59
60 public:
61 APSInt IntReal, IntImag;
62 APFloat FloatReal, FloatImag;
63
64 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
65
66 void makeComplexFloat() { IsInt = false; }
67 bool isComplexFloat() const { return !IsInt; }
68 APFloat &getComplexFloatReal() { return FloatReal; }
69 APFloat &getComplexFloatImag() { return FloatImag; }
70
71 void makeComplexInt() { IsInt = true; }
72 bool isComplexInt() const { return IsInt; }
73 APSInt &getComplexIntReal() { return IntReal; }
74 APSInt &getComplexIntImag() { return IntImag; }
75
76 void moveInto(APValue &v) {
77 if (isComplexFloat())
78 v = APValue(FloatReal, FloatImag);
79 else
80 v = APValue(IntReal, IntImag);
81 }
82 };
John McCallefdb83e2010-05-07 21:00:08 +000083
84 struct LValue {
85 Expr *Base;
86 CharUnits Offset;
87
88 Expr *getLValueBase() { return Base; }
89 CharUnits getLValueOffset() { return Offset; }
90
91 void moveInto(APValue &v) {
92 v = APValue(Base, Offset);
93 }
94 };
John McCallf4cf1a12010-05-07 17:22:02 +000095}
Chris Lattner87eae5e2008-07-11 22:52:41 +000096
John McCallefdb83e2010-05-07 21:00:08 +000097static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
98static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +000099static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000100static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
101 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000102static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000103static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000104
105//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000106// Misc utilities
107//===----------------------------------------------------------------------===//
108
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000109static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000110 if (!E) return true;
111
112 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
113 if (isa<FunctionDecl>(DRE->getDecl()))
114 return true;
115 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
116 return VD->hasGlobalStorage();
117 return false;
118 }
119
120 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
121 return CLE->isFileScope();
122
123 return true;
124}
125
John McCallefdb83e2010-05-07 21:00:08 +0000126static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
127 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000128
John McCall35542832010-05-07 21:34:32 +0000129 // A null base expression indicates a null pointer. These are always
130 // evaluatable, and they are false unless the offset is zero.
131 if (!Base) {
132 Result = !Value.Offset.isZero();
133 return true;
134 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000135
John McCall42c8f872010-05-10 23:27:23 +0000136 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000137 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000138
John McCall35542832010-05-07 21:34:32 +0000139 // We have a non-null base expression. These are generally known to
140 // be true, but if it'a decl-ref to a weak symbol it can be null at
141 // runtime.
John McCall35542832010-05-07 21:34:32 +0000142 Result = true;
143
144 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000145 if (!DeclRef)
146 return true;
147
John McCall35542832010-05-07 21:34:32 +0000148 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000149 const ValueDecl* Decl = DeclRef->getDecl();
150 if (Decl->hasAttr<WeakAttr>() ||
151 Decl->hasAttr<WeakRefAttr>() ||
152 Decl->hasAttr<WeakImportAttr>())
153 return false;
154
Eli Friedman5bc86102009-06-14 02:17:33 +0000155 return true;
156}
157
John McCallcd7a4452010-01-05 23:42:56 +0000158static bool HandleConversionToBool(const Expr* E, bool& Result,
159 EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000160 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000161 APSInt IntResult;
162 if (!EvaluateInteger(E, IntResult, Info))
163 return false;
164 Result = IntResult != 0;
165 return true;
166 } else if (E->getType()->isRealFloatingType()) {
167 APFloat FloatResult(0.0);
168 if (!EvaluateFloat(E, FloatResult, Info))
169 return false;
170 Result = !FloatResult.isZero();
171 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000172 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000173 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000174 if (!EvaluatePointer(E, PointerResult, Info))
175 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000176 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000177 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000178 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000179 if (!EvaluateComplex(E, ComplexResult, Info))
180 return false;
181 if (ComplexResult.isComplexFloat()) {
182 Result = !ComplexResult.getComplexFloatReal().isZero() ||
183 !ComplexResult.getComplexFloatImag().isZero();
184 } else {
185 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
186 ComplexResult.getComplexIntImag().getBoolValue();
187 }
188 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000189 }
190
191 return false;
192}
193
Mike Stump1eb44332009-09-09 15:08:12 +0000194static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000195 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000196 unsigned DestWidth = Ctx.getIntWidth(DestType);
197 // Determine whether we are converting to unsigned or signed.
198 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000200 // FIXME: Warning for overflow.
201 uint64_t Space[4];
202 bool ignored;
203 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
204 llvm::APFloat::rmTowardZero, &ignored);
205 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
206}
207
Mike Stump1eb44332009-09-09 15:08:12 +0000208static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000209 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000210 bool ignored;
211 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000212 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000213 APFloat::rmNearestTiesToEven, &ignored);
214 return Result;
215}
216
Mike Stump1eb44332009-09-09 15:08:12 +0000217static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000218 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000219 unsigned DestWidth = Ctx.getIntWidth(DestType);
220 APSInt Result = Value;
221 // Figure out if this is a truncate, extend or noop cast.
222 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000223 Result = Result.extOrTrunc(DestWidth);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000224 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
225 return Result;
226}
227
Mike Stump1eb44332009-09-09 15:08:12 +0000228static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000229 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000230
231 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
232 Result.convertFromAPInt(Value, Value.isSigned(),
233 APFloat::rmNearestTiesToEven);
234 return Result;
235}
236
Mike Stumpc4c90452009-10-27 22:09:17 +0000237namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000238class HasSideEffect
Mike Stumpc4c90452009-10-27 22:09:17 +0000239 : public StmtVisitor<HasSideEffect, bool> {
240 EvalInfo &Info;
241public:
242
243 HasSideEffect(EvalInfo &info) : Info(info) {}
244
245 // Unhandled nodes conservatively default to having side effects.
246 bool VisitStmt(Stmt *S) {
247 return true;
248 }
249
250 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
251 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000252 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000253 return true;
254 return false;
255 }
256 // We don't want to evaluate BlockExprs multiple times, as they generate
257 // a ton of code.
258 bool VisitBlockExpr(BlockExpr *E) { return true; }
259 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
260 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
261 { return Visit(E->getInitializer()); }
262 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
263 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
264 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
265 bool VisitStringLiteral(StringLiteral *E) { return false; }
266 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
267 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
268 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000269 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000270 bool VisitChooseExpr(ChooseExpr *E)
271 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
272 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
273 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stump3f0147e2009-10-29 23:34:20 +0000274 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stump980ca222009-10-29 20:48:09 +0000275 bool VisitBinaryOperator(BinaryOperator *E)
276 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000277 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
278 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
279 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
280 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
281 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000282 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000283 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000284 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000285 }
286 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000287
288 // Has side effects if any element does.
289 bool VisitInitListExpr(InitListExpr *E) {
290 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
291 if (Visit(E->getInit(i))) return true;
292 return false;
293 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000294
295 bool VisitSizeOfPackExpr(SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000296};
297
Mike Stumpc4c90452009-10-27 22:09:17 +0000298} // end anonymous namespace
299
Eli Friedman4efaa272008-11-12 09:44:48 +0000300//===----------------------------------------------------------------------===//
301// LValue Evaluation
302//===----------------------------------------------------------------------===//
303namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000304class LValueExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000305 : public StmtVisitor<LValueExprEvaluator, bool> {
Eli Friedman4efaa272008-11-12 09:44:48 +0000306 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000307 LValue &Result;
308
309 bool Success(Expr *E) {
310 Result.Base = E;
311 Result.Offset = CharUnits::Zero();
312 return true;
313 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000314public:
Mike Stump1eb44332009-09-09 15:08:12 +0000315
John McCallefdb83e2010-05-07 21:00:08 +0000316 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
317 Info(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000318
John McCallefdb83e2010-05-07 21:00:08 +0000319 bool VisitStmt(Stmt *S) {
320 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000321 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000322
John McCallefdb83e2010-05-07 21:00:08 +0000323 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
324 bool VisitDeclRefExpr(DeclRefExpr *E);
325 bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); }
326 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
327 bool VisitMemberExpr(MemberExpr *E);
328 bool VisitStringLiteral(StringLiteral *E) { return Success(E); }
329 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); }
330 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E);
331 bool VisitUnaryDeref(UnaryOperator *E);
332 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000333 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000334 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000335 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlsson26bc2202009-10-03 16:30:22 +0000336
John McCallefdb83e2010-05-07 21:00:08 +0000337 bool VisitCastExpr(CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000338 switch (E->getCastKind()) {
339 default:
John McCallefdb83e2010-05-07 21:00:08 +0000340 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000341
John McCall2de56d12010-08-25 11:45:40 +0000342 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000343 return Visit(E->getSubExpr());
344 }
345 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000346 // FIXME: Missing: __real__, __imag__
Eli Friedman4efaa272008-11-12 09:44:48 +0000347};
348} // end anonymous namespace
349
John McCallefdb83e2010-05-07 21:00:08 +0000350static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
351 return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Eli Friedman4efaa272008-11-12 09:44:48 +0000352}
353
John McCallefdb83e2010-05-07 21:00:08 +0000354bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000355 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000356 return Success(E);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000357 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
358 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000359 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000360 // Reference parameters can refer to anything even if they have an
361 // "initializer" in the form of a default argument.
362 if (isa<ParmVarDecl>(VD))
363 return false;
Eli Friedmand933a012009-08-29 19:09:59 +0000364 // FIXME: Check whether VD might be overridden!
Sebastian Redl31310a22010-02-01 20:16:42 +0000365 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000366 return Visit(const_cast<Expr *>(Init));
Eli Friedman50c39ea2009-05-27 06:04:58 +0000367 }
368
John McCallefdb83e2010-05-07 21:00:08 +0000369 return false;
Anders Carlsson35873c42008-11-24 04:41:22 +0000370}
371
John McCallefdb83e2010-05-07 21:00:08 +0000372bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000373 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000374}
375
John McCallefdb83e2010-05-07 21:00:08 +0000376bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000377 QualType Ty;
378 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000379 if (!EvaluatePointer(E->getBase(), Result, Info))
380 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000381 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000382 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000383 if (!Visit(E->getBase()))
384 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000385 Ty = E->getBase()->getType();
386 }
387
Ted Kremenek6217b802009-07-29 21:53:49 +0000388 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000389 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000390
391 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
392 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000393 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000394
395 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000396 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000397
Eli Friedman4efaa272008-11-12 09:44:48 +0000398 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000399 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000400 for (RecordDecl::field_iterator Field = RD->field_begin(),
401 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000402 Field != FieldEnd; (void)++Field, ++i) {
403 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000404 break;
405 }
406
John McCallefdb83e2010-05-07 21:00:08 +0000407 Result.Offset += CharUnits::fromQuantity(RL.getFieldOffset(i) / 8);
408 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000409}
410
John McCallefdb83e2010-05-07 21:00:08 +0000411bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000412 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000413 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Anders Carlsson3068d112008-11-16 19:01:22 +0000415 APSInt Index;
416 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000417 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000418
Ken Dyck199c3d62010-01-11 17:06:35 +0000419 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000420 Result.Offset += Index.getSExtValue() * ElementSize;
421 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000422}
Eli Friedman4efaa272008-11-12 09:44:48 +0000423
John McCallefdb83e2010-05-07 21:00:08 +0000424bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
425 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000426}
427
Eli Friedman4efaa272008-11-12 09:44:48 +0000428//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000429// Pointer Evaluation
430//===----------------------------------------------------------------------===//
431
Anders Carlssonc754aa62008-07-08 05:13:58 +0000432namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000433class PointerExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000434 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000435 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000436 LValue &Result;
437
438 bool Success(Expr *E) {
439 Result.Base = E;
440 Result.Offset = CharUnits::Zero();
441 return true;
442 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000443public:
Mike Stump1eb44332009-09-09 15:08:12 +0000444
John McCallefdb83e2010-05-07 21:00:08 +0000445 PointerExprEvaluator(EvalInfo &info, LValue &Result)
446 : Info(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000447
John McCallefdb83e2010-05-07 21:00:08 +0000448 bool VisitStmt(Stmt *S) {
449 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000450 }
451
John McCallefdb83e2010-05-07 21:00:08 +0000452 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000453
John McCallefdb83e2010-05-07 21:00:08 +0000454 bool VisitBinaryOperator(const BinaryOperator *E);
455 bool VisitCastExpr(CastExpr* E);
456 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman2217c872009-02-22 11:46:18 +0000457 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000458 bool VisitUnaryAddrOf(const UnaryOperator *E);
459 bool VisitObjCStringLiteral(ObjCStringLiteral *E)
460 { return Success(E); }
461 bool VisitAddrLabelExpr(AddrLabelExpr *E)
462 { return Success(E); }
463 bool VisitCallExpr(CallExpr *E);
464 bool VisitBlockExpr(BlockExpr *E) {
Mike Stumpb83d2872009-02-19 22:01:56 +0000465 if (!E->hasBlockDeclRefExprs())
John McCallefdb83e2010-05-07 21:00:08 +0000466 return Success(E);
467 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000468 }
John McCallefdb83e2010-05-07 21:00:08 +0000469 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
470 { return Success((Expr*)0); }
471 bool VisitConditionalOperator(ConditionalOperator *E);
472 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000473 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallefdb83e2010-05-07 21:00:08 +0000474 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
475 { return Success((Expr*)0); }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000476 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000477};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000478} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000479
John McCallefdb83e2010-05-07 21:00:08 +0000480static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000481 assert(E->getType()->hasPointerRepresentation());
John McCallefdb83e2010-05-07 21:00:08 +0000482 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000483}
484
John McCallefdb83e2010-05-07 21:00:08 +0000485bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000486 if (E->getOpcode() != BO_Add &&
487 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000488 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000490 const Expr *PExp = E->getLHS();
491 const Expr *IExp = E->getRHS();
492 if (IExp->getType()->isPointerType())
493 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000494
John McCallefdb83e2010-05-07 21:00:08 +0000495 if (!EvaluatePointer(PExp, Result, Info))
496 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000497
John McCallefdb83e2010-05-07 21:00:08 +0000498 llvm::APSInt Offset;
499 if (!EvaluateInteger(IExp, Offset, Info))
500 return false;
501 int64_t AdditionalOffset
502 = Offset.isSigned() ? Offset.getSExtValue()
503 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000504
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000505 // Compute the new offset in the appropriate width.
506
507 QualType PointeeType =
508 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000509 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000511 // Explicitly handle GNU void* and function pointer arithmetic extensions.
512 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000513 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000514 else
John McCallefdb83e2010-05-07 21:00:08 +0000515 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000516
John McCall2de56d12010-08-25 11:45:40 +0000517 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000518 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000519 else
John McCallefdb83e2010-05-07 21:00:08 +0000520 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000521
John McCallefdb83e2010-05-07 21:00:08 +0000522 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000523}
Eli Friedman4efaa272008-11-12 09:44:48 +0000524
John McCallefdb83e2010-05-07 21:00:08 +0000525bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
526 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000527}
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000529
John McCallefdb83e2010-05-07 21:00:08 +0000530bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000531 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000532
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000533 switch (E->getCastKind()) {
534 default:
535 break;
536
John McCall2de56d12010-08-25 11:45:40 +0000537 case CK_NoOp:
538 case CK_BitCast:
539 case CK_LValueBitCast:
540 case CK_AnyPointerToObjCPointerCast:
541 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000542 return Visit(SubExpr);
543
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000544 case CK_DerivedToBase:
545 case CK_UncheckedDerivedToBase: {
546 LValue BaseLV;
547 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
548 return false;
549
550 // Now figure out the necessary offset to add to the baseLV to get from
551 // the derived class to the base class.
552 uint64_t Offset = 0;
553
554 QualType Ty = E->getSubExpr()->getType();
555 const CXXRecordDecl *DerivedDecl =
556 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
557
558 for (CastExpr::path_const_iterator PathI = E->path_begin(),
559 PathE = E->path_end(); PathI != PathE; ++PathI) {
560 const CXXBaseSpecifier *Base = *PathI;
561
562 // FIXME: If the base is virtual, we'd need to determine the type of the
563 // most derived class and we don't support that right now.
564 if (Base->isVirtual())
565 return false;
566
567 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
568 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
569
Anders Carlssona14f5972010-10-31 23:22:37 +0000570 Offset += Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000571 DerivedDecl = BaseDecl;
572 }
573
574 Result.Base = BaseLV.getLValueBase();
575 Result.Offset = BaseLV.getLValueOffset() +
576 CharUnits::fromQuantity(Offset / Info.Ctx.getCharWidth());
577 return true;
578 }
579
John McCall404cd162010-11-13 01:35:44 +0000580 case CK_NullToPointer: {
581 Result.Base = 0;
582 Result.Offset = CharUnits::Zero();
583 return true;
584 }
585
John McCall2de56d12010-08-25 11:45:40 +0000586 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000587 APValue Value;
588 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000589 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000590
John McCallefdb83e2010-05-07 21:00:08 +0000591 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000592 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000593 Result.Base = 0;
594 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
595 return true;
596 } else {
597 // Cast is of an lvalue, no need to change value.
598 Result.Base = Value.getLValueBase();
599 Result.Offset = Value.getLValueOffset();
600 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000601 }
602 }
John McCall2de56d12010-08-25 11:45:40 +0000603 case CK_ArrayToPointerDecay:
604 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000605 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000606 }
607
John McCallefdb83e2010-05-07 21:00:08 +0000608 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000609}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000610
John McCallefdb83e2010-05-07 21:00:08 +0000611bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000612 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000613 Builtin::BI__builtin___CFStringMakeConstantString ||
614 E->isBuiltinCall(Info.Ctx) ==
615 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000616 return Success(E);
617 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000618}
619
John McCallefdb83e2010-05-07 21:00:08 +0000620bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000621 bool BoolResult;
622 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000623 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000624
625 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000626 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000627}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000628
629//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000630// Vector Evaluation
631//===----------------------------------------------------------------------===//
632
633namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000634 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000635 : public StmtVisitor<VectorExprEvaluator, APValue> {
636 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000637 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000638 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Nate Begeman59b5da62009-01-18 03:20:47 +0000640 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Nate Begeman59b5da62009-01-18 03:20:47 +0000642 APValue VisitStmt(Stmt *S) {
643 return APValue();
644 }
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Eli Friedman91110ee2009-02-23 04:23:56 +0000646 APValue VisitParenExpr(ParenExpr *E)
647 { return Visit(E->getSubExpr()); }
648 APValue VisitUnaryExtension(const UnaryOperator *E)
649 { return Visit(E->getSubExpr()); }
650 APValue VisitUnaryPlus(const UnaryOperator *E)
651 { return Visit(E->getSubExpr()); }
652 APValue VisitUnaryReal(const UnaryOperator *E)
653 { return Visit(E->getSubExpr()); }
654 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
655 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000656 APValue VisitCastExpr(const CastExpr* E);
657 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
658 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000659 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000660 APValue VisitChooseExpr(const ChooseExpr *E)
661 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000662 APValue VisitUnaryImag(const UnaryOperator *E);
663 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000664 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000665 // shufflevector, ExtVectorElementExpr
666 // (Note that these require implementing conversions
667 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000668 };
669} // end anonymous namespace
670
671static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
672 if (!E->getType()->isVectorType())
673 return false;
674 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
675 return !Result.isUninit();
676}
677
678APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000679 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000680 QualType EltTy = VTy->getElementType();
681 unsigned NElts = VTy->getNumElements();
682 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Nate Begeman59b5da62009-01-18 03:20:47 +0000684 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000685 QualType SETy = SE->getType();
686 APValue Result = APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000687
Nate Begemane8c9e922009-06-26 18:22:18 +0000688 // Check for vector->vector bitcast and scalar->vector splat.
689 if (SETy->isVectorType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000690 return this->Visit(const_cast<Expr*>(SE));
Nate Begemane8c9e922009-06-26 18:22:18 +0000691 } else if (SETy->isIntegerType()) {
692 APSInt IntResult;
Daniel Dunbard906dc72009-07-01 20:37:45 +0000693 if (!EvaluateInteger(SE, IntResult, Info))
694 return APValue();
695 Result = APValue(IntResult);
Nate Begemane8c9e922009-06-26 18:22:18 +0000696 } else if (SETy->isRealFloatingType()) {
697 APFloat F(0.0);
Daniel Dunbard906dc72009-07-01 20:37:45 +0000698 if (!EvaluateFloat(SE, F, Info))
699 return APValue();
700 Result = APValue(F);
701 } else
Nate Begemanc0b8b192009-07-01 07:50:47 +0000702 return APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000703
Nate Begemanc0b8b192009-07-01 07:50:47 +0000704 // For casts of a scalar to ExtVector, convert the scalar to the element type
705 // and splat it to all elements.
706 if (E->getType()->isExtVectorType()) {
707 if (EltTy->isIntegerType() && Result.isInt())
708 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
709 Info.Ctx));
710 else if (EltTy->isIntegerType())
711 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
712 Info.Ctx));
713 else if (EltTy->isRealFloatingType() && Result.isInt())
714 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
715 Info.Ctx));
716 else if (EltTy->isRealFloatingType())
717 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
718 Info.Ctx));
719 else
720 return APValue();
721
722 // Splat and create vector APValue.
723 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
724 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000725 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000726
727 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
728 // to the vector. To construct the APValue vector initializer, bitcast the
729 // initializing value to an APInt, and shift out the bits pertaining to each
730 // element.
731 APSInt Init;
732 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Nate Begemanc0b8b192009-07-01 07:50:47 +0000734 llvm::SmallVector<APValue, 4> Elts;
735 for (unsigned i = 0; i != NElts; ++i) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000736 APSInt Tmp = Init.extOrTrunc(EltWidth);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Nate Begemanc0b8b192009-07-01 07:50:47 +0000738 if (EltTy->isIntegerType())
739 Elts.push_back(APValue(Tmp));
740 else if (EltTy->isRealFloatingType())
741 Elts.push_back(APValue(APFloat(Tmp)));
742 else
743 return APValue();
744
745 Init >>= EltWidth;
746 }
747 return APValue(&Elts[0], Elts.size());
Nate Begeman59b5da62009-01-18 03:20:47 +0000748}
749
Mike Stump1eb44332009-09-09 15:08:12 +0000750APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000751VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
752 return this->Visit(const_cast<Expr*>(E->getInitializer()));
753}
754
Mike Stump1eb44332009-09-09 15:08:12 +0000755APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000756VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000757 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000758 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000759 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Nate Begeman59b5da62009-01-18 03:20:47 +0000761 QualType EltTy = VT->getElementType();
762 llvm::SmallVector<APValue, 4> Elements;
763
John McCalla7d6c222010-06-11 17:54:15 +0000764 // If a vector is initialized with a single element, that value
765 // becomes every element of the vector, not just the first.
766 // This is the behavior described in the IBM AltiVec documentation.
767 if (NumInits == 1) {
768 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000769 if (EltTy->isIntegerType()) {
770 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000771 if (!EvaluateInteger(E->getInit(0), sInt, Info))
772 return APValue();
773 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000774 } else {
775 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000776 if (!EvaluateFloat(E->getInit(0), f, Info))
777 return APValue();
778 InitValue = APValue(f);
779 }
780 for (unsigned i = 0; i < NumElements; i++) {
781 Elements.push_back(InitValue);
782 }
783 } else {
784 for (unsigned i = 0; i < NumElements; i++) {
785 if (EltTy->isIntegerType()) {
786 llvm::APSInt sInt(32);
787 if (i < NumInits) {
788 if (!EvaluateInteger(E->getInit(i), sInt, Info))
789 return APValue();
790 } else {
791 sInt = Info.Ctx.MakeIntValue(0, EltTy);
792 }
793 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000794 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000795 llvm::APFloat f(0.0);
796 if (i < NumInits) {
797 if (!EvaluateFloat(E->getInit(i), f, Info))
798 return APValue();
799 } else {
800 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
801 }
802 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000803 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000804 }
805 }
806 return APValue(&Elements[0], Elements.size());
807}
808
Mike Stump1eb44332009-09-09 15:08:12 +0000809APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000810VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000811 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000812 QualType EltTy = VT->getElementType();
813 APValue ZeroElement;
814 if (EltTy->isIntegerType())
815 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
816 else
817 ZeroElement =
818 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
819
820 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
821 return APValue(&Elements[0], Elements.size());
822}
823
824APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
825 bool BoolResult;
826 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
827 return APValue();
828
829 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
830
831 APValue Result;
832 if (EvaluateVector(EvalExpr, Result, Info))
833 return Result;
834 return APValue();
835}
836
Eli Friedman91110ee2009-02-23 04:23:56 +0000837APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
838 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
839 Info.EvalResult.HasSideEffects = true;
840 return GetZeroVector(E->getType());
841}
842
Nate Begeman59b5da62009-01-18 03:20:47 +0000843//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000844// Integer Evaluation
845//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000846
847namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000848class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000849 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000850 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000851 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000852public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000853 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000854 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000855
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000856 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000857 assert(E->getType()->isIntegralOrEnumerationType() &&
858 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000859 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000860 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000861 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000862 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000863 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000864 return true;
865 }
866
Daniel Dunbar131eb432009-02-19 09:06:44 +0000867 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000868 assert(E->getType()->isIntegralOrEnumerationType() &&
869 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000870 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000871 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000872 Result = APValue(APSInt(I));
873 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000874 return true;
875 }
876
877 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000878 assert(E->getType()->isIntegralOrEnumerationType() &&
879 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000880 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000881 return true;
882 }
883
Anders Carlsson82206e22008-11-30 18:14:57 +0000884 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000885 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000886 if (Info.EvalResult.Diag == 0) {
887 Info.EvalResult.DiagLoc = L;
888 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000889 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000890 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000891 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000892 }
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Anders Carlssonc754aa62008-07-08 05:13:58 +0000894 //===--------------------------------------------------------------------===//
895 // Visitor Methods
896 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Chris Lattner32fea9d2008-11-12 07:43:42 +0000898 bool VisitStmt(Stmt *) {
899 assert(0 && "This should be called on integers, stmts are not integers");
900 return false;
901 }
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Chris Lattner32fea9d2008-11-12 07:43:42 +0000903 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000904 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000905 }
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Chris Lattnerb542afe2008-07-11 19:10:17 +0000907 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000908
Chris Lattner4c4867e2008-07-12 00:38:25 +0000909 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000910 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000911 }
912 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000913 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000914 }
Eli Friedman04309752009-11-24 05:28:59 +0000915
916 bool CheckReferencedDecl(const Expr *E, const Decl *D);
917 bool VisitDeclRefExpr(const DeclRefExpr *E) {
918 return CheckReferencedDecl(E, E->getDecl());
919 }
920 bool VisitMemberExpr(const MemberExpr *E) {
921 if (CheckReferencedDecl(E, E->getMemberDecl())) {
922 // Conservatively assume a MemberExpr will have side-effects
923 Info.EvalResult.HasSideEffects = true;
924 return true;
925 }
926 return false;
927 }
928
Eli Friedmanc4a26382010-02-13 00:10:10 +0000929 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000930 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000931 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000932 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000933 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000934
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000935 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000936 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
937
Anders Carlsson3068d112008-11-16 19:01:22 +0000938 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000939 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000940 }
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Anders Carlsson3f704562008-12-21 22:39:40 +0000942 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000943 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +0000944 }
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Douglas Gregored8abf12010-07-08 06:14:04 +0000946 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000947 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000948 }
949
Eli Friedman664a1042009-02-27 04:45:43 +0000950 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
951 return Success(0, E);
952 }
953
Sebastian Redl64b45f72009-01-05 20:52:13 +0000954 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +0000955 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000956 }
957
Francois Pichet6ad6f282010-12-07 00:08:36 +0000958 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
959 return Success(E->getValue(), E);
960 }
961
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000962 bool VisitChooseExpr(const ChooseExpr *E) {
963 return Visit(E->getChosenSubExpr(Info.Ctx));
964 }
965
Eli Friedman722c7172009-02-28 03:59:05 +0000966 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000967 bool VisitUnaryImag(const UnaryOperator *E);
968
Sebastian Redl295995c2010-09-10 20:55:47 +0000969 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +0000970 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
971
Chris Lattnerfcee0012008-07-11 21:24:13 +0000972private:
Ken Dyck8b752f12010-01-27 17:10:57 +0000973 CharUnits GetAlignOfExpr(const Expr *E);
974 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +0000975 static QualType GetObjectType(const Expr *E);
976 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000977 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000978};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000979} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000980
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000981static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000982 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000983 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
984}
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000985
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000986static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000987 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +0000988
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000989 APValue Val;
990 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
991 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000992 Result = Val.getInt();
993 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +0000994}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000995
Eli Friedman04309752009-11-24 05:28:59 +0000996bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000997 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +0000998 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
999 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001000
1001 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001002 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001003 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1004 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001005
1006 if (isa<ParmVarDecl>(D))
1007 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1008
Eli Friedman04309752009-11-24 05:28:59 +00001009 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001010 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001011 if (APValue *V = VD->getEvaluatedValue()) {
1012 if (V->isInt())
1013 return Success(V->getInt(), E);
1014 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1015 }
1016
1017 if (VD->isEvaluatingValue())
1018 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1019
1020 VD->setEvaluatingValue();
1021
Eli Friedmana7dedf72010-09-06 00:10:32 +00001022 Expr::EvalResult EResult;
1023 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1024 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001025 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001026 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001027 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001028 return true;
1029 }
1030
Eli Friedmanc0131182009-12-03 20:31:57 +00001031 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001032 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001033 }
1034 }
1035
Chris Lattner4c4867e2008-07-12 00:38:25 +00001036 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001037 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001038}
1039
Chris Lattnera4d55d82008-10-06 06:40:35 +00001040/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1041/// as GCC.
1042static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1043 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001044 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001045 enum gcc_type_class {
1046 no_type_class = -1,
1047 void_type_class, integer_type_class, char_type_class,
1048 enumeral_type_class, boolean_type_class,
1049 pointer_type_class, reference_type_class, offset_type_class,
1050 real_type_class, complex_type_class,
1051 function_type_class, method_type_class,
1052 record_type_class, union_type_class,
1053 array_type_class, string_type_class,
1054 lang_type_class
1055 };
Mike Stump1eb44332009-09-09 15:08:12 +00001056
1057 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001058 // ideal, however it is what gcc does.
1059 if (E->getNumArgs() == 0)
1060 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Chris Lattnera4d55d82008-10-06 06:40:35 +00001062 QualType ArgTy = E->getArg(0)->getType();
1063 if (ArgTy->isVoidType())
1064 return void_type_class;
1065 else if (ArgTy->isEnumeralType())
1066 return enumeral_type_class;
1067 else if (ArgTy->isBooleanType())
1068 return boolean_type_class;
1069 else if (ArgTy->isCharType())
1070 return string_type_class; // gcc doesn't appear to use char_type_class
1071 else if (ArgTy->isIntegerType())
1072 return integer_type_class;
1073 else if (ArgTy->isPointerType())
1074 return pointer_type_class;
1075 else if (ArgTy->isReferenceType())
1076 return reference_type_class;
1077 else if (ArgTy->isRealType())
1078 return real_type_class;
1079 else if (ArgTy->isComplexType())
1080 return complex_type_class;
1081 else if (ArgTy->isFunctionType())
1082 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001083 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001084 return record_type_class;
1085 else if (ArgTy->isUnionType())
1086 return union_type_class;
1087 else if (ArgTy->isArrayType())
1088 return array_type_class;
1089 else if (ArgTy->isUnionType())
1090 return union_type_class;
1091 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1092 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1093 return -1;
1094}
1095
John McCall42c8f872010-05-10 23:27:23 +00001096/// Retrieves the "underlying object type" of the given expression,
1097/// as used by __builtin_object_size.
1098QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1099 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1100 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1101 return VD->getType();
1102 } else if (isa<CompoundLiteralExpr>(E)) {
1103 return E->getType();
1104 }
1105
1106 return QualType();
1107}
1108
1109bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1110 // TODO: Perhaps we should let LLVM lower this?
1111 LValue Base;
1112 if (!EvaluatePointer(E->getArg(0), Base, Info))
1113 return false;
1114
1115 // If we can prove the base is null, lower to zero now.
1116 const Expr *LVBase = Base.getLValueBase();
1117 if (!LVBase) return Success(0, E);
1118
1119 QualType T = GetObjectType(LVBase);
1120 if (T.isNull() ||
1121 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001122 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001123 T->isVariablyModifiedType() ||
1124 T->isDependentType())
1125 return false;
1126
1127 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1128 CharUnits Offset = Base.getLValueOffset();
1129
1130 if (!Offset.isNegative() && Offset <= Size)
1131 Size -= Offset;
1132 else
1133 Size = CharUnits::Zero();
1134 return Success(Size.getQuantity(), E);
1135}
1136
Eli Friedmanc4a26382010-02-13 00:10:10 +00001137bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001138 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001139 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001140 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001141
1142 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001143 if (TryEvaluateBuiltinObjectSize(E))
1144 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001145
Eric Christopherb2aaf512010-01-19 22:58:35 +00001146 // If evaluating the argument has side-effects we can't determine
1147 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001148 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001149 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001150 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001151 return Success(0, E);
1152 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001153
Mike Stump64eda9e2009-10-26 18:35:08 +00001154 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1155 }
1156
Chris Lattner019f4e82008-10-06 05:28:25 +00001157 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001158 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001160 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001161 // __builtin_constant_p always has one operand: it returns true if that
1162 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001163 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001164
1165 case Builtin::BI__builtin_eh_return_data_regno: {
1166 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1167 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1168 return Success(Operand, E);
1169 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001170
1171 case Builtin::BI__builtin_expect:
1172 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001173
1174 case Builtin::BIstrlen:
1175 case Builtin::BI__builtin_strlen:
1176 // As an extension, we support strlen() and __builtin_strlen() as constant
1177 // expressions when the argument is a string literal.
1178 if (StringLiteral *S
1179 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1180 // The string literal may have embedded null characters. Find the first
1181 // one and truncate there.
1182 llvm::StringRef Str = S->getString();
1183 llvm::StringRef::size_type Pos = Str.find(0);
1184 if (Pos != llvm::StringRef::npos)
1185 Str = Str.substr(0, Pos);
1186
1187 return Success(Str.size(), E);
1188 }
1189
1190 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001191 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001192}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001193
Chris Lattnerb542afe2008-07-11 19:10:17 +00001194bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001195 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001196 if (!Visit(E->getRHS()))
1197 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001198
Eli Friedman33ef1452009-02-26 10:19:36 +00001199 // If we can't evaluate the LHS, it might have side effects;
1200 // conservatively mark it.
1201 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1202 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001203
Anders Carlsson027f62e2008-12-01 02:07:06 +00001204 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001205 }
1206
1207 if (E->isLogicalOp()) {
1208 // These need to be handled specially because the operands aren't
1209 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001210 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001212 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001213 // We were able to evaluate the LHS, see if we can get away with not
1214 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001215 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001216 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001217
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001218 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001219 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001220 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001221 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001222 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001223 }
1224 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001225 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001226 // We can't evaluate the LHS; however, sometimes the result
1227 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001228 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1229 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001230 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001231 // must have had side effects.
1232 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001233
1234 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001235 }
1236 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001237 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001238
Eli Friedmana6afa762008-11-13 06:09:17 +00001239 return false;
1240 }
1241
Anders Carlsson286f85e2008-11-16 07:17:21 +00001242 QualType LHSTy = E->getLHS()->getType();
1243 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001244
1245 if (LHSTy->isAnyComplexType()) {
1246 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001247 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001248
1249 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1250 return false;
1251
1252 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1253 return false;
1254
1255 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001256 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001257 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001258 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001259 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1260
John McCall2de56d12010-08-25 11:45:40 +00001261 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001262 return Success((CR_r == APFloat::cmpEqual &&
1263 CR_i == APFloat::cmpEqual), E);
1264 else {
John McCall2de56d12010-08-25 11:45:40 +00001265 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001266 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001267 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001268 CR_r == APFloat::cmpLessThan ||
1269 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001270 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001271 CR_i == APFloat::cmpLessThan ||
1272 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001273 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001274 } else {
John McCall2de56d12010-08-25 11:45:40 +00001275 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001276 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1277 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1278 else {
John McCall2de56d12010-08-25 11:45:40 +00001279 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001280 "Invalid compex comparison.");
1281 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1282 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1283 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001284 }
1285 }
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Anders Carlsson286f85e2008-11-16 07:17:21 +00001287 if (LHSTy->isRealFloatingType() &&
1288 RHSTy->isRealFloatingType()) {
1289 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Anders Carlsson286f85e2008-11-16 07:17:21 +00001291 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1292 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Anders Carlsson286f85e2008-11-16 07:17:21 +00001294 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1295 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Anders Carlsson286f85e2008-11-16 07:17:21 +00001297 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001298
Anders Carlsson286f85e2008-11-16 07:17:21 +00001299 switch (E->getOpcode()) {
1300 default:
1301 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001302 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001303 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001304 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001305 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001306 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001307 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001308 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001309 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001310 E);
John McCall2de56d12010-08-25 11:45:40 +00001311 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001312 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001313 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001314 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001315 || CR == APFloat::cmpLessThan
1316 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001317 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001318 }
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001320 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001321 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001322 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001323 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1324 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001325
John McCallefdb83e2010-05-07 21:00:08 +00001326 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001327 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1328 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001329
Eli Friedman5bc86102009-06-14 02:17:33 +00001330 // Reject any bases from the normal codepath; we special-case comparisons
1331 // to null.
1332 if (LHSValue.getLValueBase()) {
1333 if (!E->isEqualityOp())
1334 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001335 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001336 return false;
1337 bool bres;
1338 if (!EvalPointerValueAsBool(LHSValue, bres))
1339 return false;
John McCall2de56d12010-08-25 11:45:40 +00001340 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001341 } else if (RHSValue.getLValueBase()) {
1342 if (!E->isEqualityOp())
1343 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001344 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001345 return false;
1346 bool bres;
1347 if (!EvalPointerValueAsBool(RHSValue, bres))
1348 return false;
John McCall2de56d12010-08-25 11:45:40 +00001349 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001350 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001351
John McCall2de56d12010-08-25 11:45:40 +00001352 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001353 QualType Type = E->getLHS()->getType();
1354 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001355
Ken Dycka7305832010-01-15 12:37:54 +00001356 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001357 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001358 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001359
Ken Dycka7305832010-01-15 12:37:54 +00001360 CharUnits Diff = LHSValue.getLValueOffset() -
1361 RHSValue.getLValueOffset();
1362 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001363 }
1364 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001365 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001366 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001367 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001368 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1369 }
1370 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001371 }
1372 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001373 if (!LHSTy->isIntegralOrEnumerationType() ||
1374 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001375 // We can't continue from here for non-integral types, and they
1376 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001377 return false;
1378 }
1379
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001380 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001381 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001382 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001383
Eli Friedman42edd0d2009-03-24 01:14:50 +00001384 APValue RHSVal;
1385 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001386 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001387
1388 // Handle cases like (unsigned long)&a + 4.
1389 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001390 CharUnits Offset = Result.getLValueOffset();
1391 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1392 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001393 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001394 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001395 else
Ken Dycka7305832010-01-15 12:37:54 +00001396 Offset -= AdditionalOffset;
1397 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001398 return true;
1399 }
1400
1401 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001402 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001403 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001404 CharUnits Offset = RHSVal.getLValueOffset();
1405 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1406 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001407 return true;
1408 }
1409
1410 // All the following cases expect both operands to be an integer
1411 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001412 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001413
Eli Friedman42edd0d2009-03-24 01:14:50 +00001414 APSInt& RHS = RHSVal.getInt();
1415
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001416 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001417 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001418 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001419 case BO_Mul: return Success(Result.getInt() * RHS, E);
1420 case BO_Add: return Success(Result.getInt() + RHS, E);
1421 case BO_Sub: return Success(Result.getInt() - RHS, E);
1422 case BO_And: return Success(Result.getInt() & RHS, E);
1423 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1424 case BO_Or: return Success(Result.getInt() | RHS, E);
1425 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001426 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001427 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001428 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001429 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001430 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001431 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001432 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001433 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001434 // During constant-folding, a negative shift is an opposite shift.
1435 if (RHS.isSigned() && RHS.isNegative()) {
1436 RHS = -RHS;
1437 goto shift_right;
1438 }
1439
1440 shift_left:
1441 unsigned SA
1442 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001443 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001444 }
John McCall2de56d12010-08-25 11:45:40 +00001445 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001446 // During constant-folding, a negative shift is an opposite shift.
1447 if (RHS.isSigned() && RHS.isNegative()) {
1448 RHS = -RHS;
1449 goto shift_left;
1450 }
1451
1452 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001453 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001454 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1455 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001456 }
Mike Stump1eb44332009-09-09 15:08:12 +00001457
John McCall2de56d12010-08-25 11:45:40 +00001458 case BO_LT: return Success(Result.getInt() < RHS, E);
1459 case BO_GT: return Success(Result.getInt() > RHS, E);
1460 case BO_LE: return Success(Result.getInt() <= RHS, E);
1461 case BO_GE: return Success(Result.getInt() >= RHS, E);
1462 case BO_EQ: return Success(Result.getInt() == RHS, E);
1463 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001464 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001465}
1466
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001467bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001468 bool Cond;
1469 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001470 return false;
1471
Nuno Lopesa25bd552008-11-16 22:06:39 +00001472 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001473}
1474
Ken Dyck8b752f12010-01-27 17:10:57 +00001475CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001476 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1477 // the result is the size of the referenced type."
1478 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1479 // result shall be the alignment of the referenced type."
1480 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1481 T = Ref->getPointeeType();
1482
Chris Lattnere9feb472009-01-24 21:09:06 +00001483 // Get information about the alignment.
1484 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Douglas Gregor18857642009-04-30 17:32:17 +00001485
Eli Friedman2be58612009-05-30 21:09:44 +00001486 // __alignof is defined to return the preferred alignment.
Ken Dyck8b752f12010-01-27 17:10:57 +00001487 return CharUnits::fromQuantity(
1488 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
Chris Lattnere9feb472009-01-24 21:09:06 +00001489}
1490
Ken Dyck8b752f12010-01-27 17:10:57 +00001491CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001492 E = E->IgnoreParens();
1493
1494 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001495 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001496 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001497 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1498 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001499
Chris Lattneraf707ab2009-01-24 21:53:27 +00001500 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001501 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1502 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001503
Chris Lattnere9feb472009-01-24 21:09:06 +00001504 return GetAlignOfType(E->getType());
1505}
1506
1507
Sebastian Redl05189992008-11-11 17:56:53 +00001508/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1509/// expression's type.
1510bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001511 // Handle alignof separately.
1512 if (!E->isSizeOf()) {
1513 if (E->isArgumentType())
Ken Dyck8b752f12010-01-27 17:10:57 +00001514 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001515 else
Ken Dyck8b752f12010-01-27 17:10:57 +00001516 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001517 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001518
Sebastian Redl05189992008-11-11 17:56:53 +00001519 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl5d484e82009-11-23 17:18:46 +00001520 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1521 // the result is the size of the referenced type."
1522 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1523 // result shall be the alignment of the referenced type."
1524 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1525 SrcTy = Ref->getPointeeType();
Sebastian Redl05189992008-11-11 17:56:53 +00001526
Daniel Dunbar131eb432009-02-19 09:06:44 +00001527 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1528 // extension.
1529 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1530 return Success(1, E);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001531
Chris Lattnerfcee0012008-07-11 21:24:13 +00001532 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001533 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001534 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001535
Chris Lattnere9feb472009-01-24 21:09:06 +00001536 // Get information about the size.
Ken Dyck199c3d62010-01-11 17:06:35 +00001537 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001538}
1539
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001540bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1541 CharUnits Result;
1542 unsigned n = E->getNumComponents();
1543 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1544 if (n == 0)
1545 return false;
1546 QualType CurrentType = E->getTypeSourceInfo()->getType();
1547 for (unsigned i = 0; i != n; ++i) {
1548 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1549 switch (ON.getKind()) {
1550 case OffsetOfExpr::OffsetOfNode::Array: {
1551 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1552 APSInt IdxResult;
1553 if (!EvaluateInteger(Idx, IdxResult, Info))
1554 return false;
1555 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1556 if (!AT)
1557 return false;
1558 CurrentType = AT->getElementType();
1559 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1560 Result += IdxResult.getSExtValue() * ElementSize;
1561 break;
1562 }
1563
1564 case OffsetOfExpr::OffsetOfNode::Field: {
1565 FieldDecl *MemberDecl = ON.getField();
1566 const RecordType *RT = CurrentType->getAs<RecordType>();
1567 if (!RT)
1568 return false;
1569 RecordDecl *RD = RT->getDecl();
1570 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1571 unsigned i = 0;
1572 // FIXME: It would be nice if we didn't have to loop here!
1573 for (RecordDecl::field_iterator Field = RD->field_begin(),
1574 FieldEnd = RD->field_end();
1575 Field != FieldEnd; (void)++Field, ++i) {
1576 if (*Field == MemberDecl)
1577 break;
1578 }
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001579 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1580 Result += CharUnits::fromQuantity(
1581 RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001582 CurrentType = MemberDecl->getType().getNonReferenceType();
1583 break;
1584 }
1585
1586 case OffsetOfExpr::OffsetOfNode::Identifier:
1587 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001588 return false;
1589
1590 case OffsetOfExpr::OffsetOfNode::Base: {
1591 CXXBaseSpecifier *BaseSpec = ON.getBase();
1592 if (BaseSpec->isVirtual())
1593 return false;
1594
1595 // Find the layout of the class whose base we are looking into.
1596 const RecordType *RT = CurrentType->getAs<RecordType>();
1597 if (!RT)
1598 return false;
1599 RecordDecl *RD = RT->getDecl();
1600 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1601
1602 // Find the base class itself.
1603 CurrentType = BaseSpec->getType();
1604 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1605 if (!BaseRT)
1606 return false;
1607
1608 // Add the offset to the base.
1609 Result += CharUnits::fromQuantity(
Anders Carlssona14f5972010-10-31 23:22:37 +00001610 RL.getBaseClassOffsetInBits(cast<CXXRecordDecl>(BaseRT->getDecl()))
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001611 / Info.Ctx.getCharWidth());
1612 break;
1613 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001614 }
1615 }
1616 return Success(Result.getQuantity(), E);
1617}
1618
Chris Lattnerb542afe2008-07-11 19:10:17 +00001619bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001620 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001621 // LNot's operand isn't necessarily an integer, so we handle it specially.
1622 bool bres;
1623 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1624 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001625 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001626 }
1627
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001628 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001629 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001630 return false;
1631
Chris Lattner87eae5e2008-07-11 22:52:41 +00001632 // Get the operand value into 'Result'.
1633 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001634 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001635
Chris Lattner75a48812008-07-11 22:15:16 +00001636 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001637 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001638 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1639 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001640 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001641 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001642 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1643 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001644 return true;
John McCall2de56d12010-08-25 11:45:40 +00001645 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001646 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001647 return true;
John McCall2de56d12010-08-25 11:45:40 +00001648 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001649 if (!Result.isInt()) return false;
1650 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001651 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001652 if (!Result.isInt()) return false;
1653 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001654 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001655}
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Chris Lattner732b2232008-07-12 01:15:53 +00001657/// HandleCast - This is used to evaluate implicit or explicit casts where the
1658/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001659bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001660 Expr *SubExpr = E->getSubExpr();
1661 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001662 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001663
Eli Friedman4efaa272008-11-12 09:44:48 +00001664 if (DestType->isBooleanType()) {
1665 bool BoolResult;
1666 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1667 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001668 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001669 }
1670
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001671 // Handle simple integer->integer casts.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001672 if (SrcType->isIntegralOrEnumerationType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001673 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001674 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001675
Eli Friedmanbe265702009-02-20 01:15:07 +00001676 if (!Result.isInt()) {
1677 // Only allow casts of lvalues if they are lossless.
1678 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1679 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001680
Daniel Dunbardd211642009-02-19 22:24:01 +00001681 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001682 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001683 }
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Chris Lattner732b2232008-07-12 01:15:53 +00001685 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001686 if (SrcType->isPointerType()) {
John McCallefdb83e2010-05-07 21:00:08 +00001687 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001688 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001689 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001690
Daniel Dunbardd211642009-02-19 22:24:01 +00001691 if (LV.getLValueBase()) {
1692 // Only allow based lvalue casts if they are lossless.
1693 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1694 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001695
John McCallefdb83e2010-05-07 21:00:08 +00001696 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001697 return true;
1698 }
1699
Ken Dycka7305832010-01-15 12:37:54 +00001700 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1701 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001702 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001703 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001704
Eli Friedmanbe265702009-02-20 01:15:07 +00001705 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1706 // This handles double-conversion cases, where there's both
1707 // an l-value promotion and an implicit conversion to int.
John McCallefdb83e2010-05-07 21:00:08 +00001708 LValue LV;
Eli Friedmanbe265702009-02-20 01:15:07 +00001709 if (!EvaluateLValue(SubExpr, LV, Info))
1710 return false;
1711
1712 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1713 return false;
1714
John McCallefdb83e2010-05-07 21:00:08 +00001715 LV.moveInto(Result);
Eli Friedmanbe265702009-02-20 01:15:07 +00001716 return true;
1717 }
1718
Eli Friedman1725f682009-04-22 19:23:09 +00001719 if (SrcType->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001720 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001721 if (!EvaluateComplex(SubExpr, C, Info))
1722 return false;
1723 if (C.isComplexFloat())
1724 return Success(HandleFloatToIntCast(DestType, SrcType,
1725 C.getComplexFloatReal(), Info.Ctx),
1726 E);
1727 else
1728 return Success(HandleIntToIntCast(DestType, SrcType,
1729 C.getComplexIntReal(), Info.Ctx), E);
1730 }
Eli Friedman2217c872009-02-22 11:46:18 +00001731 // FIXME: Handle vectors
1732
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001733 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001734 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001735
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001736 APFloat F(0.0);
1737 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001738 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001740 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001741}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001742
Eli Friedman722c7172009-02-28 03:59:05 +00001743bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1744 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001745 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001746 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1747 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1748 return Success(LV.getComplexIntReal(), E);
1749 }
1750
1751 return Visit(E->getSubExpr());
1752}
1753
Eli Friedman664a1042009-02-27 04:45:43 +00001754bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001755 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001756 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001757 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1758 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1759 return Success(LV.getComplexIntImag(), E);
1760 }
1761
Eli Friedman664a1042009-02-27 04:45:43 +00001762 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1763 Info.EvalResult.HasSideEffects = true;
1764 return Success(0, E);
1765}
1766
Douglas Gregoree8aff02011-01-04 17:33:58 +00001767bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1768 return Success(E->getPackLength(), E);
1769}
1770
Sebastian Redl295995c2010-09-10 20:55:47 +00001771bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1772 return Success(E->getValue(), E);
1773}
1774
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001775//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001776// Float Evaluation
1777//===----------------------------------------------------------------------===//
1778
1779namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001780class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001781 : public StmtVisitor<FloatExprEvaluator, bool> {
1782 EvalInfo &Info;
1783 APFloat &Result;
1784public:
1785 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1786 : Info(info), Result(result) {}
1787
1788 bool VisitStmt(Stmt *S) {
1789 return false;
1790 }
1791
1792 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001793 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001794
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001795 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001796 bool VisitBinaryOperator(const BinaryOperator *E);
1797 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001798 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001799 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001800 bool VisitConditionalOperator(ConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001801
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001802 bool VisitChooseExpr(const ChooseExpr *E)
1803 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1804 bool VisitUnaryExtension(const UnaryOperator *E)
1805 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001806 bool VisitUnaryReal(const UnaryOperator *E);
1807 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001808
John McCall189d6ef2010-10-09 01:34:31 +00001809 bool VisitDeclRefExpr(const DeclRefExpr *E);
1810
John McCallabd3a852010-05-07 22:08:54 +00001811 // FIXME: Missing: array subscript of vector, member of vector,
1812 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001813};
1814} // end anonymous namespace
1815
1816static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001817 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001818 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1819}
1820
Jay Foad4ba2a172011-01-12 09:06:06 +00001821static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001822 QualType ResultTy,
1823 const Expr *Arg,
1824 bool SNaN,
1825 llvm::APFloat &Result) {
1826 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1827 if (!S) return false;
1828
1829 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1830
1831 llvm::APInt fill;
1832
1833 // Treat empty strings as if they were zero.
1834 if (S->getString().empty())
1835 fill = llvm::APInt(32, 0);
1836 else if (S->getString().getAsInteger(0, fill))
1837 return false;
1838
1839 if (SNaN)
1840 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1841 else
1842 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1843 return true;
1844}
1845
Chris Lattner019f4e82008-10-06 05:28:25 +00001846bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001847 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001848 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001849 case Builtin::BI__builtin_huge_val:
1850 case Builtin::BI__builtin_huge_valf:
1851 case Builtin::BI__builtin_huge_vall:
1852 case Builtin::BI__builtin_inf:
1853 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001854 case Builtin::BI__builtin_infl: {
1855 const llvm::fltSemantics &Sem =
1856 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001857 Result = llvm::APFloat::getInf(Sem);
1858 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001859 }
Mike Stump1eb44332009-09-09 15:08:12 +00001860
John McCalldb7b72a2010-02-28 13:00:19 +00001861 case Builtin::BI__builtin_nans:
1862 case Builtin::BI__builtin_nansf:
1863 case Builtin::BI__builtin_nansl:
1864 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1865 true, Result);
1866
Chris Lattner9e621712008-10-06 06:31:58 +00001867 case Builtin::BI__builtin_nan:
1868 case Builtin::BI__builtin_nanf:
1869 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00001870 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00001871 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00001872 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1873 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001874
1875 case Builtin::BI__builtin_fabs:
1876 case Builtin::BI__builtin_fabsf:
1877 case Builtin::BI__builtin_fabsl:
1878 if (!EvaluateFloat(E->getArg(0), Result, Info))
1879 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001881 if (Result.isNegative())
1882 Result.changeSign();
1883 return true;
1884
Mike Stump1eb44332009-09-09 15:08:12 +00001885 case Builtin::BI__builtin_copysign:
1886 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001887 case Builtin::BI__builtin_copysignl: {
1888 APFloat RHS(0.);
1889 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1890 !EvaluateFloat(E->getArg(1), RHS, Info))
1891 return false;
1892 Result.copySign(RHS);
1893 return true;
1894 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001895 }
1896}
1897
John McCall189d6ef2010-10-09 01:34:31 +00001898bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
1899 const Decl *D = E->getDecl();
1900 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
1901 const VarDecl *VD = cast<VarDecl>(D);
1902
1903 // Require the qualifiers to be const and not volatile.
1904 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
1905 if (!T.isConstQualified() || T.isVolatileQualified())
1906 return false;
1907
1908 const Expr *Init = VD->getAnyInitializer();
1909 if (!Init) return false;
1910
1911 if (APValue *V = VD->getEvaluatedValue()) {
1912 if (V->isFloat()) {
1913 Result = V->getFloat();
1914 return true;
1915 }
1916 return false;
1917 }
1918
1919 if (VD->isEvaluatingValue())
1920 return false;
1921
1922 VD->setEvaluatingValue();
1923
1924 Expr::EvalResult InitResult;
1925 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
1926 InitResult.Val.isFloat()) {
1927 // Cache the evaluated value in the variable declaration.
1928 Result = InitResult.Val.getFloat();
1929 VD->setEvaluatedValue(InitResult.Val);
1930 return true;
1931 }
1932
1933 VD->setEvaluatedValue(APValue());
1934 return false;
1935}
1936
John McCallabd3a852010-05-07 22:08:54 +00001937bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00001938 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1939 ComplexValue CV;
1940 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1941 return false;
1942 Result = CV.FloatReal;
1943 return true;
1944 }
1945
1946 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00001947}
1948
1949bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00001950 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1951 ComplexValue CV;
1952 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1953 return false;
1954 Result = CV.FloatImag;
1955 return true;
1956 }
1957
1958 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1959 Info.EvalResult.HasSideEffects = true;
1960 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
1961 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00001962 return true;
1963}
1964
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001965bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001966 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00001967 return false;
1968
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001969 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1970 return false;
1971
1972 switch (E->getOpcode()) {
1973 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00001974 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001975 return true;
John McCall2de56d12010-08-25 11:45:40 +00001976 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001977 Result.changeSign();
1978 return true;
1979 }
1980}
Chris Lattner019f4e82008-10-06 05:28:25 +00001981
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001982bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001983 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00001984 if (!EvaluateFloat(E->getRHS(), Result, Info))
1985 return false;
1986
1987 // If we can't evaluate the LHS, it might have side effects;
1988 // conservatively mark it.
1989 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1990 Info.EvalResult.HasSideEffects = true;
1991
1992 return true;
1993 }
1994
Anders Carlsson96e93662010-10-31 01:21:47 +00001995 // We can't evaluate pointer-to-member operations.
1996 if (E->isPtrMemOp())
1997 return false;
1998
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001999 // FIXME: Diagnostics? I really don't understand how the warnings
2000 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002001 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002002 if (!EvaluateFloat(E->getLHS(), Result, Info))
2003 return false;
2004 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2005 return false;
2006
2007 switch (E->getOpcode()) {
2008 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002009 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002010 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2011 return true;
John McCall2de56d12010-08-25 11:45:40 +00002012 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002013 Result.add(RHS, APFloat::rmNearestTiesToEven);
2014 return true;
John McCall2de56d12010-08-25 11:45:40 +00002015 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002016 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2017 return true;
John McCall2de56d12010-08-25 11:45:40 +00002018 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002019 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2020 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002021 }
2022}
2023
2024bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2025 Result = E->getValue();
2026 return true;
2027}
2028
Eli Friedman4efaa272008-11-12 09:44:48 +00002029bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2030 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002032 if (SubExpr->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002033 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002034 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002035 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002036 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002037 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002038 return true;
2039 }
2040 if (SubExpr->getType()->isRealFloatingType()) {
2041 if (!Visit(SubExpr))
2042 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002043 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2044 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002045 return true;
2046 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002047
2048 if (E->getCastKind() == CK_FloatingComplexToReal) {
2049 ComplexValue V;
2050 if (!EvaluateComplex(SubExpr, V, Info))
2051 return false;
2052 Result = V.getComplexFloatReal();
2053 return true;
2054 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002055
2056 return false;
2057}
2058
Douglas Gregored8abf12010-07-08 06:14:04 +00002059bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002060 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2061 return true;
2062}
2063
Eli Friedman67f85fc2009-12-04 02:12:53 +00002064bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2065 bool Cond;
2066 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2067 return false;
2068
2069 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2070}
2071
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002072//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002073// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002074//===----------------------------------------------------------------------===//
2075
2076namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002077class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00002078 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002079 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00002080 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002082public:
John McCallf4cf1a12010-05-07 17:22:02 +00002083 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2084 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002086 //===--------------------------------------------------------------------===//
2087 // Visitor Methods
2088 //===--------------------------------------------------------------------===//
2089
John McCallf4cf1a12010-05-07 17:22:02 +00002090 bool VisitStmt(Stmt *S) {
2091 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002092 }
Mike Stump1eb44332009-09-09 15:08:12 +00002093
John McCallf4cf1a12010-05-07 17:22:02 +00002094 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002095
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002096 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002097
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002098 bool VisitCastExpr(CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002099
John McCallf4cf1a12010-05-07 17:22:02 +00002100 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002101 bool VisitUnaryOperator(const UnaryOperator *E);
2102 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCallf4cf1a12010-05-07 17:22:02 +00002103 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002104 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002105 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002106 { return Visit(E->getSubExpr()); }
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002107 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002108};
2109} // end anonymous namespace
2110
John McCallf4cf1a12010-05-07 17:22:02 +00002111static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2112 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002113 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002114 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002115}
2116
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002117bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2118 Expr* SubExpr = E->getSubExpr();
2119
2120 if (SubExpr->getType()->isRealFloatingType()) {
2121 Result.makeComplexFloat();
2122 APFloat &Imag = Result.FloatImag;
2123 if (!EvaluateFloat(SubExpr, Imag, Info))
2124 return false;
2125
2126 Result.FloatReal = APFloat(Imag.getSemantics());
2127 return true;
2128 } else {
2129 assert(SubExpr->getType()->isIntegerType() &&
2130 "Unexpected imaginary literal.");
2131
2132 Result.makeComplexInt();
2133 APSInt &Imag = Result.IntImag;
2134 if (!EvaluateInteger(SubExpr, Imag, Info))
2135 return false;
2136
2137 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2138 return true;
2139 }
2140}
2141
2142bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002143
John McCall8786da72010-12-14 17:51:41 +00002144 switch (E->getCastKind()) {
2145 case CK_BitCast:
2146 case CK_LValueBitCast:
2147 case CK_BaseToDerived:
2148 case CK_DerivedToBase:
2149 case CK_UncheckedDerivedToBase:
2150 case CK_Dynamic:
2151 case CK_ToUnion:
2152 case CK_ArrayToPointerDecay:
2153 case CK_FunctionToPointerDecay:
2154 case CK_NullToPointer:
2155 case CK_NullToMemberPointer:
2156 case CK_BaseToDerivedMemberPointer:
2157 case CK_DerivedToBaseMemberPointer:
2158 case CK_MemberPointerToBoolean:
2159 case CK_ConstructorConversion:
2160 case CK_IntegralToPointer:
2161 case CK_PointerToIntegral:
2162 case CK_PointerToBoolean:
2163 case CK_ToVoid:
2164 case CK_VectorSplat:
2165 case CK_IntegralCast:
2166 case CK_IntegralToBoolean:
2167 case CK_IntegralToFloating:
2168 case CK_FloatingToIntegral:
2169 case CK_FloatingToBoolean:
2170 case CK_FloatingCast:
2171 case CK_AnyPointerToObjCPointerCast:
2172 case CK_AnyPointerToBlockPointerCast:
2173 case CK_ObjCObjectLValueCast:
2174 case CK_FloatingComplexToReal:
2175 case CK_FloatingComplexToBoolean:
2176 case CK_IntegralComplexToReal:
2177 case CK_IntegralComplexToBoolean:
2178 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002179
John McCall8786da72010-12-14 17:51:41 +00002180 case CK_LValueToRValue:
2181 case CK_NoOp:
2182 return Visit(E->getSubExpr());
2183
2184 case CK_Dependent:
2185 case CK_GetObjCProperty:
2186 case CK_UserDefinedConversion:
2187 return false;
2188
2189 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002190 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002191 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002192 return false;
2193
John McCall8786da72010-12-14 17:51:41 +00002194 Result.makeComplexFloat();
2195 Result.FloatImag = APFloat(Real.getSemantics());
2196 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002197 }
2198
John McCall8786da72010-12-14 17:51:41 +00002199 case CK_FloatingComplexCast: {
2200 if (!Visit(E->getSubExpr()))
2201 return false;
2202
2203 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2204 QualType From
2205 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2206
2207 Result.FloatReal
2208 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2209 Result.FloatImag
2210 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2211 return true;
2212 }
2213
2214 case CK_FloatingComplexToIntegralComplex: {
2215 if (!Visit(E->getSubExpr()))
2216 return false;
2217
2218 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2219 QualType From
2220 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2221 Result.makeComplexInt();
2222 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2223 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2224 return true;
2225 }
2226
2227 case CK_IntegralRealToComplex: {
2228 APSInt &Real = Result.IntReal;
2229 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2230 return false;
2231
2232 Result.makeComplexInt();
2233 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2234 return true;
2235 }
2236
2237 case CK_IntegralComplexCast: {
2238 if (!Visit(E->getSubExpr()))
2239 return false;
2240
2241 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2242 QualType From
2243 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2244
2245 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2246 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2247 return true;
2248 }
2249
2250 case CK_IntegralComplexToFloatingComplex: {
2251 if (!Visit(E->getSubExpr()))
2252 return false;
2253
2254 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2255 QualType From
2256 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2257 Result.makeComplexFloat();
2258 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2259 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2260 return true;
2261 }
2262 }
2263
2264 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002265 return false;
2266}
2267
John McCallf4cf1a12010-05-07 17:22:02 +00002268bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002269 if (E->getOpcode() == BO_Comma) {
2270 if (!Visit(E->getRHS()))
2271 return false;
2272
2273 // If we can't evaluate the LHS, it might have side effects;
2274 // conservatively mark it.
2275 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2276 Info.EvalResult.HasSideEffects = true;
2277
2278 return true;
2279 }
John McCallf4cf1a12010-05-07 17:22:02 +00002280 if (!Visit(E->getLHS()))
2281 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002282
John McCallf4cf1a12010-05-07 17:22:02 +00002283 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002284 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002285 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002286
Daniel Dunbar3f279872009-01-29 01:32:56 +00002287 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2288 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002289 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002290 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002291 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002292 if (Result.isComplexFloat()) {
2293 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2294 APFloat::rmNearestTiesToEven);
2295 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2296 APFloat::rmNearestTiesToEven);
2297 } else {
2298 Result.getComplexIntReal() += RHS.getComplexIntReal();
2299 Result.getComplexIntImag() += RHS.getComplexIntImag();
2300 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002301 break;
John McCall2de56d12010-08-25 11:45:40 +00002302 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002303 if (Result.isComplexFloat()) {
2304 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2305 APFloat::rmNearestTiesToEven);
2306 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2307 APFloat::rmNearestTiesToEven);
2308 } else {
2309 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2310 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2311 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002312 break;
John McCall2de56d12010-08-25 11:45:40 +00002313 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002314 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002315 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002316 APFloat &LHS_r = LHS.getComplexFloatReal();
2317 APFloat &LHS_i = LHS.getComplexFloatImag();
2318 APFloat &RHS_r = RHS.getComplexFloatReal();
2319 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Daniel Dunbar3f279872009-01-29 01:32:56 +00002321 APFloat Tmp = LHS_r;
2322 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2323 Result.getComplexFloatReal() = Tmp;
2324 Tmp = LHS_i;
2325 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2326 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2327
2328 Tmp = LHS_r;
2329 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2330 Result.getComplexFloatImag() = Tmp;
2331 Tmp = LHS_i;
2332 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2333 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2334 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002335 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002336 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002337 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2338 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002339 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002340 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2341 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2342 }
2343 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002344 case BO_Div:
2345 if (Result.isComplexFloat()) {
2346 ComplexValue LHS = Result;
2347 APFloat &LHS_r = LHS.getComplexFloatReal();
2348 APFloat &LHS_i = LHS.getComplexFloatImag();
2349 APFloat &RHS_r = RHS.getComplexFloatReal();
2350 APFloat &RHS_i = RHS.getComplexFloatImag();
2351 APFloat &Res_r = Result.getComplexFloatReal();
2352 APFloat &Res_i = Result.getComplexFloatImag();
2353
2354 APFloat Den = RHS_r;
2355 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2356 APFloat Tmp = RHS_i;
2357 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2358 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2359
2360 Res_r = LHS_r;
2361 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2362 Tmp = LHS_i;
2363 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2364 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2365 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2366
2367 Res_i = LHS_i;
2368 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2369 Tmp = LHS_r;
2370 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2371 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2372 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2373 } else {
2374 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2375 // FIXME: what about diagnostics?
2376 return false;
2377 }
2378 ComplexValue LHS = Result;
2379 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2380 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2381 Result.getComplexIntReal() =
2382 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2383 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2384 Result.getComplexIntImag() =
2385 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2386 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2387 }
2388 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002389 }
2390
John McCallf4cf1a12010-05-07 17:22:02 +00002391 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002392}
2393
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002394bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2395 // Get the operand value into 'Result'.
2396 if (!Visit(E->getSubExpr()))
2397 return false;
2398
2399 switch (E->getOpcode()) {
2400 default:
2401 // FIXME: what about diagnostics?
2402 return false;
2403 case UO_Extension:
2404 return true;
2405 case UO_Plus:
2406 // The result is always just the subexpr.
2407 return true;
2408 case UO_Minus:
2409 if (Result.isComplexFloat()) {
2410 Result.getComplexFloatReal().changeSign();
2411 Result.getComplexFloatImag().changeSign();
2412 }
2413 else {
2414 Result.getComplexIntReal() = -Result.getComplexIntReal();
2415 Result.getComplexIntImag() = -Result.getComplexIntImag();
2416 }
2417 return true;
2418 case UO_Not:
2419 if (Result.isComplexFloat())
2420 Result.getComplexFloatImag().changeSign();
2421 else
2422 Result.getComplexIntImag() = -Result.getComplexIntImag();
2423 return true;
2424 }
2425}
2426
2427bool ComplexExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
2428 bool Cond;
2429 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2430 return false;
2431
2432 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2433}
2434
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002435//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002436// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002437//===----------------------------------------------------------------------===//
2438
John McCall42c8f872010-05-10 23:27:23 +00002439/// Evaluate - Return true if this is a constant which we can fold using
2440/// any crazy technique (that has nothing to do with language standards) that
2441/// we want to. If this function returns true, it returns the folded constant
2442/// in Result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002443bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
John McCall42c8f872010-05-10 23:27:23 +00002444 const Expr *E = this;
2445 EvalInfo Info(Ctx, Result);
John McCallefdb83e2010-05-07 21:00:08 +00002446 if (E->getType()->isVectorType()) {
2447 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002448 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002449 } else if (E->getType()->isIntegerType()) {
2450 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002451 return false;
John McCall0f2b6922010-07-07 05:08:32 +00002452 if (Result.Val.isLValue() && !IsGlobalLValue(Result.Val.getLValueBase()))
2453 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002454 } else if (E->getType()->hasPointerRepresentation()) {
2455 LValue LV;
2456 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002457 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002458 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002459 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002460 LV.moveInto(Info.EvalResult.Val);
2461 } else if (E->getType()->isRealFloatingType()) {
2462 llvm::APFloat F(0.0);
2463 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002464 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002465
John McCallefdb83e2010-05-07 21:00:08 +00002466 Info.EvalResult.Val = APValue(F);
2467 } else if (E->getType()->isAnyComplexType()) {
2468 ComplexValue C;
2469 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002470 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002471 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002472 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002473 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002474
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002475 return true;
2476}
2477
Jay Foad4ba2a172011-01-12 09:06:06 +00002478bool Expr::EvaluateAsBooleanCondition(bool &Result,
2479 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002480 EvalResult Scratch;
2481 EvalInfo Info(Ctx, Scratch);
2482
2483 return HandleConversionToBool(this, Result, Info);
2484}
2485
Jay Foad4ba2a172011-01-12 09:06:06 +00002486bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002487 EvalInfo Info(Ctx, Result);
2488
John McCallefdb83e2010-05-07 21:00:08 +00002489 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002490 if (EvaluateLValue(this, LV, Info) &&
2491 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002492 IsGlobalLValue(LV.Base)) {
2493 LV.moveInto(Result.Val);
2494 return true;
2495 }
2496 return false;
2497}
2498
Jay Foad4ba2a172011-01-12 09:06:06 +00002499bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2500 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002501 EvalInfo Info(Ctx, Result);
2502
2503 LValue LV;
2504 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002505 LV.moveInto(Result.Val);
2506 return true;
2507 }
2508 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002509}
2510
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002511/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002512/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002513bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002514 EvalResult Result;
2515 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002516}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002517
Jay Foad4ba2a172011-01-12 09:06:06 +00002518bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002519 Expr::EvalResult Result;
2520 EvalInfo Info(Ctx, Result);
2521 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2522}
2523
Jay Foad4ba2a172011-01-12 09:06:06 +00002524APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002525 EvalResult EvalResult;
2526 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002527 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002528 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002529 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002530
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002531 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002532}
John McCalld905f5a2010-05-07 05:32:02 +00002533
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002534 bool Expr::EvalResult::isGlobalLValue() const {
2535 assert(Val.isLValue());
2536 return IsGlobalLValue(Val.getLValueBase());
2537 }
2538
2539
John McCalld905f5a2010-05-07 05:32:02 +00002540/// isIntegerConstantExpr - this recursive routine will test if an expression is
2541/// an integer constant expression.
2542
2543/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2544/// comma, etc
2545///
2546/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2547/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2548/// cast+dereference.
2549
2550// CheckICE - This function does the fundamental ICE checking: the returned
2551// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2552// Note that to reduce code duplication, this helper does no evaluation
2553// itself; the caller checks whether the expression is evaluatable, and
2554// in the rare cases where CheckICE actually cares about the evaluated
2555// value, it calls into Evalute.
2556//
2557// Meanings of Val:
2558// 0: This expression is an ICE if it can be evaluated by Evaluate.
2559// 1: This expression is not an ICE, but if it isn't evaluated, it's
2560// a legal subexpression for an ICE. This return value is used to handle
2561// the comma operator in C99 mode.
2562// 2: This expression is not an ICE, and is not a legal subexpression for one.
2563
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002564namespace {
2565
John McCalld905f5a2010-05-07 05:32:02 +00002566struct ICEDiag {
2567 unsigned Val;
2568 SourceLocation Loc;
2569
2570 public:
2571 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2572 ICEDiag() : Val(0) {}
2573};
2574
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002575}
2576
2577static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002578
2579static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2580 Expr::EvalResult EVResult;
2581 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2582 !EVResult.Val.isInt()) {
2583 return ICEDiag(2, E->getLocStart());
2584 }
2585 return NoDiag();
2586}
2587
2588static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2589 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002590 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002591 return ICEDiag(2, E->getLocStart());
2592 }
2593
2594 switch (E->getStmtClass()) {
2595#define STMT(Node, Base) case Expr::Node##Class:
2596#define EXPR(Node, Base)
2597#include "clang/AST/StmtNodes.inc"
2598 case Expr::PredefinedExprClass:
2599 case Expr::FloatingLiteralClass:
2600 case Expr::ImaginaryLiteralClass:
2601 case Expr::StringLiteralClass:
2602 case Expr::ArraySubscriptExprClass:
2603 case Expr::MemberExprClass:
2604 case Expr::CompoundAssignOperatorClass:
2605 case Expr::CompoundLiteralExprClass:
2606 case Expr::ExtVectorElementExprClass:
2607 case Expr::InitListExprClass:
2608 case Expr::DesignatedInitExprClass:
2609 case Expr::ImplicitValueInitExprClass:
2610 case Expr::ParenListExprClass:
2611 case Expr::VAArgExprClass:
2612 case Expr::AddrLabelExprClass:
2613 case Expr::StmtExprClass:
2614 case Expr::CXXMemberCallExprClass:
2615 case Expr::CXXDynamicCastExprClass:
2616 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002617 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002618 case Expr::CXXNullPtrLiteralExprClass:
2619 case Expr::CXXThisExprClass:
2620 case Expr::CXXThrowExprClass:
2621 case Expr::CXXNewExprClass:
2622 case Expr::CXXDeleteExprClass:
2623 case Expr::CXXPseudoDestructorExprClass:
2624 case Expr::UnresolvedLookupExprClass:
2625 case Expr::DependentScopeDeclRefExprClass:
2626 case Expr::CXXConstructExprClass:
2627 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002628 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002629 case Expr::CXXTemporaryObjectExprClass:
2630 case Expr::CXXUnresolvedConstructExprClass:
2631 case Expr::CXXDependentScopeMemberExprClass:
2632 case Expr::UnresolvedMemberExprClass:
2633 case Expr::ObjCStringLiteralClass:
2634 case Expr::ObjCEncodeExprClass:
2635 case Expr::ObjCMessageExprClass:
2636 case Expr::ObjCSelectorExprClass:
2637 case Expr::ObjCProtocolExprClass:
2638 case Expr::ObjCIvarRefExprClass:
2639 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002640 case Expr::ObjCIsaExprClass:
2641 case Expr::ShuffleVectorExprClass:
2642 case Expr::BlockExprClass:
2643 case Expr::BlockDeclRefExprClass:
2644 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002645 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002646 case Expr::PackExpansionExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002647 return ICEDiag(2, E->getLocStart());
2648
Douglas Gregoree8aff02011-01-04 17:33:58 +00002649 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002650 case Expr::GNUNullExprClass:
2651 // GCC considers the GNU __null value to be an integral constant expression.
2652 return NoDiag();
2653
2654 case Expr::ParenExprClass:
2655 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2656 case Expr::IntegerLiteralClass:
2657 case Expr::CharacterLiteralClass:
2658 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002659 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002660 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002661 case Expr::BinaryTypeTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002662 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002663 return NoDiag();
2664 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002665 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002666 const CallExpr *CE = cast<CallExpr>(E);
2667 if (CE->isBuiltinCall(Ctx))
2668 return CheckEvalInICE(E, Ctx);
2669 return ICEDiag(2, E->getLocStart());
2670 }
2671 case Expr::DeclRefExprClass:
2672 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2673 return NoDiag();
2674 if (Ctx.getLangOptions().CPlusPlus &&
2675 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2676 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2677
2678 // Parameter variables are never constants. Without this check,
2679 // getAnyInitializer() can find a default argument, which leads
2680 // to chaos.
2681 if (isa<ParmVarDecl>(D))
2682 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2683
2684 // C++ 7.1.5.1p2
2685 // A variable of non-volatile const-qualified integral or enumeration
2686 // type initialized by an ICE can be used in ICEs.
2687 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2688 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2689 if (Quals.hasVolatile() || !Quals.hasConst())
2690 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2691
2692 // Look for a declaration of this variable that has an initializer.
2693 const VarDecl *ID = 0;
2694 const Expr *Init = Dcl->getAnyInitializer(ID);
2695 if (Init) {
2696 if (ID->isInitKnownICE()) {
2697 // We have already checked whether this subexpression is an
2698 // integral constant expression.
2699 if (ID->isInitICE())
2700 return NoDiag();
2701 else
2702 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2703 }
2704
2705 // It's an ICE whether or not the definition we found is
2706 // out-of-line. See DR 721 and the discussion in Clang PR
2707 // 6206 for details.
2708
2709 if (Dcl->isCheckingICE()) {
2710 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2711 }
2712
2713 Dcl->setCheckingICE();
2714 ICEDiag Result = CheckICE(Init, Ctx);
2715 // Cache the result of the ICE test.
2716 Dcl->setInitKnownICE(Result.Val == 0);
2717 return Result;
2718 }
2719 }
2720 }
2721 return ICEDiag(2, E->getLocStart());
2722 case Expr::UnaryOperatorClass: {
2723 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2724 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002725 case UO_PostInc:
2726 case UO_PostDec:
2727 case UO_PreInc:
2728 case UO_PreDec:
2729 case UO_AddrOf:
2730 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002731 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002732 case UO_Extension:
2733 case UO_LNot:
2734 case UO_Plus:
2735 case UO_Minus:
2736 case UO_Not:
2737 case UO_Real:
2738 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002739 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002740 }
2741
2742 // OffsetOf falls through here.
2743 }
2744 case Expr::OffsetOfExprClass: {
2745 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2746 // Evaluate matches the proposed gcc behavior for cases like
2747 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2748 // compliance: we should warn earlier for offsetof expressions with
2749 // array subscripts that aren't ICEs, and if the array subscripts
2750 // are ICEs, the value of the offsetof must be an integer constant.
2751 return CheckEvalInICE(E, Ctx);
2752 }
2753 case Expr::SizeOfAlignOfExprClass: {
2754 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2755 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2756 return ICEDiag(2, E->getLocStart());
2757 return NoDiag();
2758 }
2759 case Expr::BinaryOperatorClass: {
2760 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2761 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002762 case BO_PtrMemD:
2763 case BO_PtrMemI:
2764 case BO_Assign:
2765 case BO_MulAssign:
2766 case BO_DivAssign:
2767 case BO_RemAssign:
2768 case BO_AddAssign:
2769 case BO_SubAssign:
2770 case BO_ShlAssign:
2771 case BO_ShrAssign:
2772 case BO_AndAssign:
2773 case BO_XorAssign:
2774 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002775 return ICEDiag(2, E->getLocStart());
2776
John McCall2de56d12010-08-25 11:45:40 +00002777 case BO_Mul:
2778 case BO_Div:
2779 case BO_Rem:
2780 case BO_Add:
2781 case BO_Sub:
2782 case BO_Shl:
2783 case BO_Shr:
2784 case BO_LT:
2785 case BO_GT:
2786 case BO_LE:
2787 case BO_GE:
2788 case BO_EQ:
2789 case BO_NE:
2790 case BO_And:
2791 case BO_Xor:
2792 case BO_Or:
2793 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002794 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2795 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002796 if (Exp->getOpcode() == BO_Div ||
2797 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002798 // Evaluate gives an error for undefined Div/Rem, so make sure
2799 // we don't evaluate one.
2800 if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2801 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2802 if (REval == 0)
2803 return ICEDiag(1, E->getLocStart());
2804 if (REval.isSigned() && REval.isAllOnesValue()) {
2805 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2806 if (LEval.isMinSignedValue())
2807 return ICEDiag(1, E->getLocStart());
2808 }
2809 }
2810 }
John McCall2de56d12010-08-25 11:45:40 +00002811 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002812 if (Ctx.getLangOptions().C99) {
2813 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2814 // if it isn't evaluated.
2815 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2816 return ICEDiag(1, E->getLocStart());
2817 } else {
2818 // In both C89 and C++, commas in ICEs are illegal.
2819 return ICEDiag(2, E->getLocStart());
2820 }
2821 }
2822 if (LHSResult.Val >= RHSResult.Val)
2823 return LHSResult;
2824 return RHSResult;
2825 }
John McCall2de56d12010-08-25 11:45:40 +00002826 case BO_LAnd:
2827 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002828 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2829 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2830 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2831 // Rare case where the RHS has a comma "side-effect"; we need
2832 // to actually check the condition to see whether the side
2833 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00002834 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00002835 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2836 return RHSResult;
2837 return NoDiag();
2838 }
2839
2840 if (LHSResult.Val >= RHSResult.Val)
2841 return LHSResult;
2842 return RHSResult;
2843 }
2844 }
2845 }
2846 case Expr::ImplicitCastExprClass:
2847 case Expr::CStyleCastExprClass:
2848 case Expr::CXXFunctionalCastExprClass:
2849 case Expr::CXXStaticCastExprClass:
2850 case Expr::CXXReinterpretCastExprClass:
2851 case Expr::CXXConstCastExprClass: {
2852 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002853 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00002854 return CheckICE(SubExpr, Ctx);
2855 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2856 return NoDiag();
2857 return ICEDiag(2, E->getLocStart());
2858 }
2859 case Expr::ConditionalOperatorClass: {
2860 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2861 // If the condition (ignoring parens) is a __builtin_constant_p call,
2862 // then only the true side is actually considered in an integer constant
2863 // expression, and it is fully evaluated. This is an important GNU
2864 // extension. See GCC PR38377 for discussion.
2865 if (const CallExpr *CallCE
2866 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2867 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2868 Expr::EvalResult EVResult;
2869 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2870 !EVResult.Val.isInt()) {
2871 return ICEDiag(2, E->getLocStart());
2872 }
2873 return NoDiag();
2874 }
2875 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2876 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2877 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2878 if (CondResult.Val == 2)
2879 return CondResult;
2880 if (TrueResult.Val == 2)
2881 return TrueResult;
2882 if (FalseResult.Val == 2)
2883 return FalseResult;
2884 if (CondResult.Val == 1)
2885 return CondResult;
2886 if (TrueResult.Val == 0 && FalseResult.Val == 0)
2887 return NoDiag();
2888 // Rare case where the diagnostics depend on which side is evaluated
2889 // Note that if we get here, CondResult is 0, and at least one of
2890 // TrueResult and FalseResult is non-zero.
2891 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2892 return FalseResult;
2893 }
2894 return TrueResult;
2895 }
2896 case Expr::CXXDefaultArgExprClass:
2897 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2898 case Expr::ChooseExprClass: {
2899 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2900 }
2901 }
2902
2903 // Silence a GCC warning
2904 return ICEDiag(2, E->getLocStart());
2905}
2906
2907bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2908 SourceLocation *Loc, bool isEvaluated) const {
2909 ICEDiag d = CheckICE(this, Ctx);
2910 if (d.Val != 0) {
2911 if (Loc) *Loc = d.Loc;
2912 return false;
2913 }
2914 EvalResult EvalResult;
2915 if (!Evaluate(EvalResult, Ctx))
2916 llvm_unreachable("ICE cannot be evaluated!");
2917 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2918 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2919 Result = EvalResult.Val.getInt();
2920 return true;
2921}