blob: cb7381016369fa8e553cd19e5d3491df477230ee [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
Ken Dyck4e26caa2011-01-14 02:01:36 +0000407 Result.Offset +=
408 CharUnits::fromQuantity(RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
John McCallefdb83e2010-05-07 21:00:08 +0000409 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000410}
411
John McCallefdb83e2010-05-07 21:00:08 +0000412bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000413 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000414 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Anders Carlsson3068d112008-11-16 19:01:22 +0000416 APSInt Index;
417 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000418 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000419
Ken Dyck199c3d62010-01-11 17:06:35 +0000420 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000421 Result.Offset += Index.getSExtValue() * ElementSize;
422 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000423}
Eli Friedman4efaa272008-11-12 09:44:48 +0000424
John McCallefdb83e2010-05-07 21:00:08 +0000425bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
426 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000427}
428
Eli Friedman4efaa272008-11-12 09:44:48 +0000429//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000430// Pointer Evaluation
431//===----------------------------------------------------------------------===//
432
Anders Carlssonc754aa62008-07-08 05:13:58 +0000433namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000434class PointerExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000435 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000436 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000437 LValue &Result;
438
439 bool Success(Expr *E) {
440 Result.Base = E;
441 Result.Offset = CharUnits::Zero();
442 return true;
443 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000444public:
Mike Stump1eb44332009-09-09 15:08:12 +0000445
John McCallefdb83e2010-05-07 21:00:08 +0000446 PointerExprEvaluator(EvalInfo &info, LValue &Result)
447 : Info(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000448
John McCallefdb83e2010-05-07 21:00:08 +0000449 bool VisitStmt(Stmt *S) {
450 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000451 }
452
John McCallefdb83e2010-05-07 21:00:08 +0000453 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000454
John McCallefdb83e2010-05-07 21:00:08 +0000455 bool VisitBinaryOperator(const BinaryOperator *E);
456 bool VisitCastExpr(CastExpr* E);
457 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman2217c872009-02-22 11:46:18 +0000458 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000459 bool VisitUnaryAddrOf(const UnaryOperator *E);
460 bool VisitObjCStringLiteral(ObjCStringLiteral *E)
461 { return Success(E); }
462 bool VisitAddrLabelExpr(AddrLabelExpr *E)
463 { return Success(E); }
464 bool VisitCallExpr(CallExpr *E);
465 bool VisitBlockExpr(BlockExpr *E) {
Mike Stumpb83d2872009-02-19 22:01:56 +0000466 if (!E->hasBlockDeclRefExprs())
John McCallefdb83e2010-05-07 21:00:08 +0000467 return Success(E);
468 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000469 }
John McCallefdb83e2010-05-07 21:00:08 +0000470 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
471 { return Success((Expr*)0); }
472 bool VisitConditionalOperator(ConditionalOperator *E);
473 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000474 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallefdb83e2010-05-07 21:00:08 +0000475 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
476 { return Success((Expr*)0); }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000477 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000478};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000479} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000480
John McCallefdb83e2010-05-07 21:00:08 +0000481static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000482 assert(E->getType()->hasPointerRepresentation());
John McCallefdb83e2010-05-07 21:00:08 +0000483 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000484}
485
John McCallefdb83e2010-05-07 21:00:08 +0000486bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000487 if (E->getOpcode() != BO_Add &&
488 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000489 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000491 const Expr *PExp = E->getLHS();
492 const Expr *IExp = E->getRHS();
493 if (IExp->getType()->isPointerType())
494 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000495
John McCallefdb83e2010-05-07 21:00:08 +0000496 if (!EvaluatePointer(PExp, Result, Info))
497 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000498
John McCallefdb83e2010-05-07 21:00:08 +0000499 llvm::APSInt Offset;
500 if (!EvaluateInteger(IExp, Offset, Info))
501 return false;
502 int64_t AdditionalOffset
503 = Offset.isSigned() ? Offset.getSExtValue()
504 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000505
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000506 // Compute the new offset in the appropriate width.
507
508 QualType PointeeType =
509 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000510 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000512 // Explicitly handle GNU void* and function pointer arithmetic extensions.
513 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000514 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000515 else
John McCallefdb83e2010-05-07 21:00:08 +0000516 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000517
John McCall2de56d12010-08-25 11:45:40 +0000518 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000519 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000520 else
John McCallefdb83e2010-05-07 21:00:08 +0000521 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000522
John McCallefdb83e2010-05-07 21:00:08 +0000523 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000524}
Eli Friedman4efaa272008-11-12 09:44:48 +0000525
John McCallefdb83e2010-05-07 21:00:08 +0000526bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
527 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000528}
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000530
John McCallefdb83e2010-05-07 21:00:08 +0000531bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000532 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000533
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000534 switch (E->getCastKind()) {
535 default:
536 break;
537
John McCall2de56d12010-08-25 11:45:40 +0000538 case CK_NoOp:
539 case CK_BitCast:
540 case CK_LValueBitCast:
541 case CK_AnyPointerToObjCPointerCast:
542 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000543 return Visit(SubExpr);
544
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000545 case CK_DerivedToBase:
546 case CK_UncheckedDerivedToBase: {
547 LValue BaseLV;
548 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
549 return false;
550
551 // Now figure out the necessary offset to add to the baseLV to get from
552 // the derived class to the base class.
553 uint64_t Offset = 0;
554
555 QualType Ty = E->getSubExpr()->getType();
556 const CXXRecordDecl *DerivedDecl =
557 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
558
559 for (CastExpr::path_const_iterator PathI = E->path_begin(),
560 PathE = E->path_end(); PathI != PathE; ++PathI) {
561 const CXXBaseSpecifier *Base = *PathI;
562
563 // FIXME: If the base is virtual, we'd need to determine the type of the
564 // most derived class and we don't support that right now.
565 if (Base->isVirtual())
566 return false;
567
568 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
569 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
570
Anders Carlssona14f5972010-10-31 23:22:37 +0000571 Offset += Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000572 DerivedDecl = BaseDecl;
573 }
574
575 Result.Base = BaseLV.getLValueBase();
576 Result.Offset = BaseLV.getLValueOffset() +
577 CharUnits::fromQuantity(Offset / Info.Ctx.getCharWidth());
578 return true;
579 }
580
John McCall404cd162010-11-13 01:35:44 +0000581 case CK_NullToPointer: {
582 Result.Base = 0;
583 Result.Offset = CharUnits::Zero();
584 return true;
585 }
586
John McCall2de56d12010-08-25 11:45:40 +0000587 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000588 APValue Value;
589 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000590 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000591
John McCallefdb83e2010-05-07 21:00:08 +0000592 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000593 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000594 Result.Base = 0;
595 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
596 return true;
597 } else {
598 // Cast is of an lvalue, no need to change value.
599 Result.Base = Value.getLValueBase();
600 Result.Offset = Value.getLValueOffset();
601 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000602 }
603 }
John McCall2de56d12010-08-25 11:45:40 +0000604 case CK_ArrayToPointerDecay:
605 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000606 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000607 }
608
John McCallefdb83e2010-05-07 21:00:08 +0000609 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000610}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000611
John McCallefdb83e2010-05-07 21:00:08 +0000612bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000613 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000614 Builtin::BI__builtin___CFStringMakeConstantString ||
615 E->isBuiltinCall(Info.Ctx) ==
616 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000617 return Success(E);
618 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000619}
620
John McCallefdb83e2010-05-07 21:00:08 +0000621bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000622 bool BoolResult;
623 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000624 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000625
626 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000627 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000628}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000629
630//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000631// Vector Evaluation
632//===----------------------------------------------------------------------===//
633
634namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000635 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000636 : public StmtVisitor<VectorExprEvaluator, APValue> {
637 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000638 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000639 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Nate Begeman59b5da62009-01-18 03:20:47 +0000641 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Nate Begeman59b5da62009-01-18 03:20:47 +0000643 APValue VisitStmt(Stmt *S) {
644 return APValue();
645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Eli Friedman91110ee2009-02-23 04:23:56 +0000647 APValue VisitParenExpr(ParenExpr *E)
648 { return Visit(E->getSubExpr()); }
649 APValue VisitUnaryExtension(const UnaryOperator *E)
650 { return Visit(E->getSubExpr()); }
651 APValue VisitUnaryPlus(const UnaryOperator *E)
652 { return Visit(E->getSubExpr()); }
653 APValue VisitUnaryReal(const UnaryOperator *E)
654 { return Visit(E->getSubExpr()); }
655 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
656 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000657 APValue VisitCastExpr(const CastExpr* E);
658 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
659 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000660 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000661 APValue VisitChooseExpr(const ChooseExpr *E)
662 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000663 APValue VisitUnaryImag(const UnaryOperator *E);
664 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000665 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000666 // shufflevector, ExtVectorElementExpr
667 // (Note that these require implementing conversions
668 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000669 };
670} // end anonymous namespace
671
672static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
673 if (!E->getType()->isVectorType())
674 return false;
675 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
676 return !Result.isUninit();
677}
678
679APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000680 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000681 QualType EltTy = VTy->getElementType();
682 unsigned NElts = VTy->getNumElements();
683 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Nate Begeman59b5da62009-01-18 03:20:47 +0000685 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000686 QualType SETy = SE->getType();
687 APValue Result = APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000688
Nate Begemane8c9e922009-06-26 18:22:18 +0000689 // Check for vector->vector bitcast and scalar->vector splat.
690 if (SETy->isVectorType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000691 return this->Visit(const_cast<Expr*>(SE));
Nate Begemane8c9e922009-06-26 18:22:18 +0000692 } else if (SETy->isIntegerType()) {
693 APSInt IntResult;
Daniel Dunbard906dc72009-07-01 20:37:45 +0000694 if (!EvaluateInteger(SE, IntResult, Info))
695 return APValue();
696 Result = APValue(IntResult);
Nate Begemane8c9e922009-06-26 18:22:18 +0000697 } else if (SETy->isRealFloatingType()) {
698 APFloat F(0.0);
Daniel Dunbard906dc72009-07-01 20:37:45 +0000699 if (!EvaluateFloat(SE, F, Info))
700 return APValue();
701 Result = APValue(F);
702 } else
Nate Begemanc0b8b192009-07-01 07:50:47 +0000703 return APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000704
Nate Begemanc0b8b192009-07-01 07:50:47 +0000705 // For casts of a scalar to ExtVector, convert the scalar to the element type
706 // and splat it to all elements.
707 if (E->getType()->isExtVectorType()) {
708 if (EltTy->isIntegerType() && Result.isInt())
709 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
710 Info.Ctx));
711 else if (EltTy->isIntegerType())
712 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
713 Info.Ctx));
714 else if (EltTy->isRealFloatingType() && Result.isInt())
715 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
716 Info.Ctx));
717 else if (EltTy->isRealFloatingType())
718 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
719 Info.Ctx));
720 else
721 return APValue();
722
723 // Splat and create vector APValue.
724 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
725 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000726 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000727
728 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
729 // to the vector. To construct the APValue vector initializer, bitcast the
730 // initializing value to an APInt, and shift out the bits pertaining to each
731 // element.
732 APSInt Init;
733 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Nate Begemanc0b8b192009-07-01 07:50:47 +0000735 llvm::SmallVector<APValue, 4> Elts;
736 for (unsigned i = 0; i != NElts; ++i) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000737 APSInt Tmp = Init.extOrTrunc(EltWidth);
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Nate Begemanc0b8b192009-07-01 07:50:47 +0000739 if (EltTy->isIntegerType())
740 Elts.push_back(APValue(Tmp));
741 else if (EltTy->isRealFloatingType())
742 Elts.push_back(APValue(APFloat(Tmp)));
743 else
744 return APValue();
745
746 Init >>= EltWidth;
747 }
748 return APValue(&Elts[0], Elts.size());
Nate Begeman59b5da62009-01-18 03:20:47 +0000749}
750
Mike Stump1eb44332009-09-09 15:08:12 +0000751APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000752VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
753 return this->Visit(const_cast<Expr*>(E->getInitializer()));
754}
755
Mike Stump1eb44332009-09-09 15:08:12 +0000756APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000757VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000758 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000759 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000760 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Nate Begeman59b5da62009-01-18 03:20:47 +0000762 QualType EltTy = VT->getElementType();
763 llvm::SmallVector<APValue, 4> Elements;
764
John McCalla7d6c222010-06-11 17:54:15 +0000765 // If a vector is initialized with a single element, that value
766 // becomes every element of the vector, not just the first.
767 // This is the behavior described in the IBM AltiVec documentation.
768 if (NumInits == 1) {
769 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000770 if (EltTy->isIntegerType()) {
771 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000772 if (!EvaluateInteger(E->getInit(0), sInt, Info))
773 return APValue();
774 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000775 } else {
776 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000777 if (!EvaluateFloat(E->getInit(0), f, Info))
778 return APValue();
779 InitValue = APValue(f);
780 }
781 for (unsigned i = 0; i < NumElements; i++) {
782 Elements.push_back(InitValue);
783 }
784 } else {
785 for (unsigned i = 0; i < NumElements; i++) {
786 if (EltTy->isIntegerType()) {
787 llvm::APSInt sInt(32);
788 if (i < NumInits) {
789 if (!EvaluateInteger(E->getInit(i), sInt, Info))
790 return APValue();
791 } else {
792 sInt = Info.Ctx.MakeIntValue(0, EltTy);
793 }
794 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000795 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000796 llvm::APFloat f(0.0);
797 if (i < NumInits) {
798 if (!EvaluateFloat(E->getInit(i), f, Info))
799 return APValue();
800 } else {
801 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
802 }
803 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000804 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000805 }
806 }
807 return APValue(&Elements[0], Elements.size());
808}
809
Mike Stump1eb44332009-09-09 15:08:12 +0000810APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000811VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000812 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000813 QualType EltTy = VT->getElementType();
814 APValue ZeroElement;
815 if (EltTy->isIntegerType())
816 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
817 else
818 ZeroElement =
819 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
820
821 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
822 return APValue(&Elements[0], Elements.size());
823}
824
825APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
826 bool BoolResult;
827 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
828 return APValue();
829
830 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
831
832 APValue Result;
833 if (EvaluateVector(EvalExpr, Result, Info))
834 return Result;
835 return APValue();
836}
837
Eli Friedman91110ee2009-02-23 04:23:56 +0000838APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
839 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
840 Info.EvalResult.HasSideEffects = true;
841 return GetZeroVector(E->getType());
842}
843
Nate Begeman59b5da62009-01-18 03:20:47 +0000844//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000845// Integer Evaluation
846//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000847
848namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000849class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000850 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000851 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000852 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000853public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000854 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000855 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000856
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000857 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000858 assert(E->getType()->isIntegralOrEnumerationType() &&
859 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000860 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000861 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000862 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000863 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000864 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000865 return true;
866 }
867
Daniel Dunbar131eb432009-02-19 09:06:44 +0000868 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000869 assert(E->getType()->isIntegralOrEnumerationType() &&
870 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000871 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000872 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000873 Result = APValue(APSInt(I));
874 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000875 return true;
876 }
877
878 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000879 assert(E->getType()->isIntegralOrEnumerationType() &&
880 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000881 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000882 return true;
883 }
884
Anders Carlsson82206e22008-11-30 18:14:57 +0000885 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000886 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000887 if (Info.EvalResult.Diag == 0) {
888 Info.EvalResult.DiagLoc = L;
889 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000890 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000891 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000892 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000893 }
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Anders Carlssonc754aa62008-07-08 05:13:58 +0000895 //===--------------------------------------------------------------------===//
896 // Visitor Methods
897 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Chris Lattner32fea9d2008-11-12 07:43:42 +0000899 bool VisitStmt(Stmt *) {
900 assert(0 && "This should be called on integers, stmts are not integers");
901 return false;
902 }
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner32fea9d2008-11-12 07:43:42 +0000904 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000905 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000906 }
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Chris Lattnerb542afe2008-07-11 19:10:17 +0000908 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000909
Chris Lattner4c4867e2008-07-12 00:38:25 +0000910 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000911 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000912 }
913 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000914 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000915 }
Eli Friedman04309752009-11-24 05:28:59 +0000916
917 bool CheckReferencedDecl(const Expr *E, const Decl *D);
918 bool VisitDeclRefExpr(const DeclRefExpr *E) {
919 return CheckReferencedDecl(E, E->getDecl());
920 }
921 bool VisitMemberExpr(const MemberExpr *E) {
922 if (CheckReferencedDecl(E, E->getMemberDecl())) {
923 // Conservatively assume a MemberExpr will have side-effects
924 Info.EvalResult.HasSideEffects = true;
925 return true;
926 }
927 return false;
928 }
929
Eli Friedmanc4a26382010-02-13 00:10:10 +0000930 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000931 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000932 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000933 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000934 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000935
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000936 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000937 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
938
Anders Carlsson3068d112008-11-16 19:01:22 +0000939 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000940 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Anders Carlsson3f704562008-12-21 22:39:40 +0000943 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000944 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +0000945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Douglas Gregored8abf12010-07-08 06:14:04 +0000947 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000948 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000949 }
950
Eli Friedman664a1042009-02-27 04:45:43 +0000951 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
952 return Success(0, E);
953 }
954
Sebastian Redl64b45f72009-01-05 20:52:13 +0000955 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +0000956 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000957 }
958
Francois Pichet6ad6f282010-12-07 00:08:36 +0000959 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
960 return Success(E->getValue(), E);
961 }
962
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000963 bool VisitChooseExpr(const ChooseExpr *E) {
964 return Visit(E->getChosenSubExpr(Info.Ctx));
965 }
966
Eli Friedman722c7172009-02-28 03:59:05 +0000967 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000968 bool VisitUnaryImag(const UnaryOperator *E);
969
Sebastian Redl295995c2010-09-10 20:55:47 +0000970 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +0000971 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
972
Chris Lattnerfcee0012008-07-11 21:24:13 +0000973private:
Ken Dyck8b752f12010-01-27 17:10:57 +0000974 CharUnits GetAlignOfExpr(const Expr *E);
975 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +0000976 static QualType GetObjectType(const Expr *E);
977 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000978 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000979};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000980} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000981
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000982static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000983 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000984 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
985}
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000986
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000987static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000988 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +0000989
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000990 APValue Val;
991 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
992 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000993 Result = Val.getInt();
994 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +0000995}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000996
Eli Friedman04309752009-11-24 05:28:59 +0000997bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000998 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +0000999 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1000 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001001
1002 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001003 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001004 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1005 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001006
1007 if (isa<ParmVarDecl>(D))
1008 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1009
Eli Friedman04309752009-11-24 05:28:59 +00001010 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001011 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001012 if (APValue *V = VD->getEvaluatedValue()) {
1013 if (V->isInt())
1014 return Success(V->getInt(), E);
1015 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1016 }
1017
1018 if (VD->isEvaluatingValue())
1019 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1020
1021 VD->setEvaluatingValue();
1022
Eli Friedmana7dedf72010-09-06 00:10:32 +00001023 Expr::EvalResult EResult;
1024 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1025 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001026 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001027 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001028 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001029 return true;
1030 }
1031
Eli Friedmanc0131182009-12-03 20:31:57 +00001032 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001033 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001034 }
1035 }
1036
Chris Lattner4c4867e2008-07-12 00:38:25 +00001037 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001038 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001039}
1040
Chris Lattnera4d55d82008-10-06 06:40:35 +00001041/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1042/// as GCC.
1043static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1044 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001045 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001046 enum gcc_type_class {
1047 no_type_class = -1,
1048 void_type_class, integer_type_class, char_type_class,
1049 enumeral_type_class, boolean_type_class,
1050 pointer_type_class, reference_type_class, offset_type_class,
1051 real_type_class, complex_type_class,
1052 function_type_class, method_type_class,
1053 record_type_class, union_type_class,
1054 array_type_class, string_type_class,
1055 lang_type_class
1056 };
Mike Stump1eb44332009-09-09 15:08:12 +00001057
1058 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001059 // ideal, however it is what gcc does.
1060 if (E->getNumArgs() == 0)
1061 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Chris Lattnera4d55d82008-10-06 06:40:35 +00001063 QualType ArgTy = E->getArg(0)->getType();
1064 if (ArgTy->isVoidType())
1065 return void_type_class;
1066 else if (ArgTy->isEnumeralType())
1067 return enumeral_type_class;
1068 else if (ArgTy->isBooleanType())
1069 return boolean_type_class;
1070 else if (ArgTy->isCharType())
1071 return string_type_class; // gcc doesn't appear to use char_type_class
1072 else if (ArgTy->isIntegerType())
1073 return integer_type_class;
1074 else if (ArgTy->isPointerType())
1075 return pointer_type_class;
1076 else if (ArgTy->isReferenceType())
1077 return reference_type_class;
1078 else if (ArgTy->isRealType())
1079 return real_type_class;
1080 else if (ArgTy->isComplexType())
1081 return complex_type_class;
1082 else if (ArgTy->isFunctionType())
1083 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001084 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001085 return record_type_class;
1086 else if (ArgTy->isUnionType())
1087 return union_type_class;
1088 else if (ArgTy->isArrayType())
1089 return array_type_class;
1090 else if (ArgTy->isUnionType())
1091 return union_type_class;
1092 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1093 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1094 return -1;
1095}
1096
John McCall42c8f872010-05-10 23:27:23 +00001097/// Retrieves the "underlying object type" of the given expression,
1098/// as used by __builtin_object_size.
1099QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1100 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1101 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1102 return VD->getType();
1103 } else if (isa<CompoundLiteralExpr>(E)) {
1104 return E->getType();
1105 }
1106
1107 return QualType();
1108}
1109
1110bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1111 // TODO: Perhaps we should let LLVM lower this?
1112 LValue Base;
1113 if (!EvaluatePointer(E->getArg(0), Base, Info))
1114 return false;
1115
1116 // If we can prove the base is null, lower to zero now.
1117 const Expr *LVBase = Base.getLValueBase();
1118 if (!LVBase) return Success(0, E);
1119
1120 QualType T = GetObjectType(LVBase);
1121 if (T.isNull() ||
1122 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001123 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001124 T->isVariablyModifiedType() ||
1125 T->isDependentType())
1126 return false;
1127
1128 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1129 CharUnits Offset = Base.getLValueOffset();
1130
1131 if (!Offset.isNegative() && Offset <= Size)
1132 Size -= Offset;
1133 else
1134 Size = CharUnits::Zero();
1135 return Success(Size.getQuantity(), E);
1136}
1137
Eli Friedmanc4a26382010-02-13 00:10:10 +00001138bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001139 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001140 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001141 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001142
1143 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001144 if (TryEvaluateBuiltinObjectSize(E))
1145 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001146
Eric Christopherb2aaf512010-01-19 22:58:35 +00001147 // If evaluating the argument has side-effects we can't determine
1148 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001149 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001150 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001151 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001152 return Success(0, E);
1153 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001154
Mike Stump64eda9e2009-10-26 18:35:08 +00001155 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1156 }
1157
Chris Lattner019f4e82008-10-06 05:28:25 +00001158 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001159 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001161 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001162 // __builtin_constant_p always has one operand: it returns true if that
1163 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001164 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001165
1166 case Builtin::BI__builtin_eh_return_data_regno: {
1167 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1168 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1169 return Success(Operand, E);
1170 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001171
1172 case Builtin::BI__builtin_expect:
1173 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001174
1175 case Builtin::BIstrlen:
1176 case Builtin::BI__builtin_strlen:
1177 // As an extension, we support strlen() and __builtin_strlen() as constant
1178 // expressions when the argument is a string literal.
1179 if (StringLiteral *S
1180 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1181 // The string literal may have embedded null characters. Find the first
1182 // one and truncate there.
1183 llvm::StringRef Str = S->getString();
1184 llvm::StringRef::size_type Pos = Str.find(0);
1185 if (Pos != llvm::StringRef::npos)
1186 Str = Str.substr(0, Pos);
1187
1188 return Success(Str.size(), E);
1189 }
1190
1191 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001192 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001193}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001194
Chris Lattnerb542afe2008-07-11 19:10:17 +00001195bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001196 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001197 if (!Visit(E->getRHS()))
1198 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001199
Eli Friedman33ef1452009-02-26 10:19:36 +00001200 // If we can't evaluate the LHS, it might have side effects;
1201 // conservatively mark it.
1202 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1203 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001204
Anders Carlsson027f62e2008-12-01 02:07:06 +00001205 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001206 }
1207
1208 if (E->isLogicalOp()) {
1209 // These need to be handled specially because the operands aren't
1210 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001211 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001213 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001214 // We were able to evaluate the LHS, see if we can get away with not
1215 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001216 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001217 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001218
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001219 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001220 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001221 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001222 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001223 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001224 }
1225 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001226 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001227 // We can't evaluate the LHS; however, sometimes the result
1228 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001229 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1230 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001231 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001232 // must have had side effects.
1233 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001234
1235 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001236 }
1237 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001238 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001239
Eli Friedmana6afa762008-11-13 06:09:17 +00001240 return false;
1241 }
1242
Anders Carlsson286f85e2008-11-16 07:17:21 +00001243 QualType LHSTy = E->getLHS()->getType();
1244 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001245
1246 if (LHSTy->isAnyComplexType()) {
1247 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001248 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001249
1250 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1251 return false;
1252
1253 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1254 return false;
1255
1256 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001257 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001258 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001259 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001260 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1261
John McCall2de56d12010-08-25 11:45:40 +00001262 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001263 return Success((CR_r == APFloat::cmpEqual &&
1264 CR_i == APFloat::cmpEqual), E);
1265 else {
John McCall2de56d12010-08-25 11:45:40 +00001266 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001267 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001268 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001269 CR_r == APFloat::cmpLessThan ||
1270 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001271 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001272 CR_i == APFloat::cmpLessThan ||
1273 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001274 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001275 } else {
John McCall2de56d12010-08-25 11:45:40 +00001276 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001277 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1278 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1279 else {
John McCall2de56d12010-08-25 11:45:40 +00001280 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001281 "Invalid compex comparison.");
1282 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1283 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1284 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001285 }
1286 }
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Anders Carlsson286f85e2008-11-16 07:17:21 +00001288 if (LHSTy->isRealFloatingType() &&
1289 RHSTy->isRealFloatingType()) {
1290 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Anders Carlsson286f85e2008-11-16 07:17:21 +00001292 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1293 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Anders Carlsson286f85e2008-11-16 07:17:21 +00001295 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1296 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Anders Carlsson286f85e2008-11-16 07:17:21 +00001298 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001299
Anders Carlsson286f85e2008-11-16 07:17:21 +00001300 switch (E->getOpcode()) {
1301 default:
1302 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001303 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001304 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001305 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001306 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001307 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001308 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001309 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001310 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001311 E);
John McCall2de56d12010-08-25 11:45:40 +00001312 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001313 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001314 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001315 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001316 || CR == APFloat::cmpLessThan
1317 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001318 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001319 }
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001321 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001322 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001323 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001324 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1325 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001326
John McCallefdb83e2010-05-07 21:00:08 +00001327 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001328 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1329 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001330
Eli Friedman5bc86102009-06-14 02:17:33 +00001331 // Reject any bases from the normal codepath; we special-case comparisons
1332 // to null.
1333 if (LHSValue.getLValueBase()) {
1334 if (!E->isEqualityOp())
1335 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001336 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001337 return false;
1338 bool bres;
1339 if (!EvalPointerValueAsBool(LHSValue, bres))
1340 return false;
John McCall2de56d12010-08-25 11:45:40 +00001341 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001342 } else if (RHSValue.getLValueBase()) {
1343 if (!E->isEqualityOp())
1344 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001345 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001346 return false;
1347 bool bres;
1348 if (!EvalPointerValueAsBool(RHSValue, bres))
1349 return false;
John McCall2de56d12010-08-25 11:45:40 +00001350 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001351 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001352
John McCall2de56d12010-08-25 11:45:40 +00001353 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001354 QualType Type = E->getLHS()->getType();
1355 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001356
Ken Dycka7305832010-01-15 12:37:54 +00001357 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001358 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001359 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001360
Ken Dycka7305832010-01-15 12:37:54 +00001361 CharUnits Diff = LHSValue.getLValueOffset() -
1362 RHSValue.getLValueOffset();
1363 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001364 }
1365 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001366 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001367 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001368 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001369 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1370 }
1371 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001372 }
1373 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001374 if (!LHSTy->isIntegralOrEnumerationType() ||
1375 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001376 // We can't continue from here for non-integral types, and they
1377 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001378 return false;
1379 }
1380
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001381 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001382 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001383 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001384
Eli Friedman42edd0d2009-03-24 01:14:50 +00001385 APValue RHSVal;
1386 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001387 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001388
1389 // Handle cases like (unsigned long)&a + 4.
1390 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001391 CharUnits Offset = Result.getLValueOffset();
1392 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1393 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001394 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001395 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001396 else
Ken Dycka7305832010-01-15 12:37:54 +00001397 Offset -= AdditionalOffset;
1398 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001399 return true;
1400 }
1401
1402 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001403 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001404 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001405 CharUnits Offset = RHSVal.getLValueOffset();
1406 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1407 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001408 return true;
1409 }
1410
1411 // All the following cases expect both operands to be an integer
1412 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001413 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001414
Eli Friedman42edd0d2009-03-24 01:14:50 +00001415 APSInt& RHS = RHSVal.getInt();
1416
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001417 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001418 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001419 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001420 case BO_Mul: return Success(Result.getInt() * RHS, E);
1421 case BO_Add: return Success(Result.getInt() + RHS, E);
1422 case BO_Sub: return Success(Result.getInt() - RHS, E);
1423 case BO_And: return Success(Result.getInt() & RHS, E);
1424 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1425 case BO_Or: return Success(Result.getInt() | RHS, E);
1426 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001427 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001428 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001429 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001430 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001431 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001432 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001433 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001434 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001435 // During constant-folding, a negative shift is an opposite shift.
1436 if (RHS.isSigned() && RHS.isNegative()) {
1437 RHS = -RHS;
1438 goto shift_right;
1439 }
1440
1441 shift_left:
1442 unsigned SA
1443 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001444 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001445 }
John McCall2de56d12010-08-25 11:45:40 +00001446 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001447 // During constant-folding, a negative shift is an opposite shift.
1448 if (RHS.isSigned() && RHS.isNegative()) {
1449 RHS = -RHS;
1450 goto shift_left;
1451 }
1452
1453 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001454 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001455 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1456 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001457 }
Mike Stump1eb44332009-09-09 15:08:12 +00001458
John McCall2de56d12010-08-25 11:45:40 +00001459 case BO_LT: return Success(Result.getInt() < RHS, E);
1460 case BO_GT: return Success(Result.getInt() > RHS, E);
1461 case BO_LE: return Success(Result.getInt() <= RHS, E);
1462 case BO_GE: return Success(Result.getInt() >= RHS, E);
1463 case BO_EQ: return Success(Result.getInt() == RHS, E);
1464 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001465 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001466}
1467
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001468bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001469 bool Cond;
1470 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001471 return false;
1472
Nuno Lopesa25bd552008-11-16 22:06:39 +00001473 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001474}
1475
Ken Dyck8b752f12010-01-27 17:10:57 +00001476CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001477 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1478 // the result is the size of the referenced type."
1479 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1480 // result shall be the alignment of the referenced type."
1481 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1482 T = Ref->getPointeeType();
1483
Chris Lattnere9feb472009-01-24 21:09:06 +00001484 // Get information about the alignment.
1485 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Douglas Gregor18857642009-04-30 17:32:17 +00001486
Eli Friedman2be58612009-05-30 21:09:44 +00001487 // __alignof is defined to return the preferred alignment.
Ken Dyck8b752f12010-01-27 17:10:57 +00001488 return CharUnits::fromQuantity(
1489 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
Chris Lattnere9feb472009-01-24 21:09:06 +00001490}
1491
Ken Dyck8b752f12010-01-27 17:10:57 +00001492CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001493 E = E->IgnoreParens();
1494
1495 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001496 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001497 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001498 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1499 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001500
Chris Lattneraf707ab2009-01-24 21:53:27 +00001501 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001502 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1503 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001504
Chris Lattnere9feb472009-01-24 21:09:06 +00001505 return GetAlignOfType(E->getType());
1506}
1507
1508
Sebastian Redl05189992008-11-11 17:56:53 +00001509/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1510/// expression's type.
1511bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001512 // Handle alignof separately.
1513 if (!E->isSizeOf()) {
1514 if (E->isArgumentType())
Ken Dyck8b752f12010-01-27 17:10:57 +00001515 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001516 else
Ken Dyck8b752f12010-01-27 17:10:57 +00001517 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001518 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001519
Sebastian Redl05189992008-11-11 17:56:53 +00001520 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl5d484e82009-11-23 17:18:46 +00001521 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1522 // the result is the size of the referenced type."
1523 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1524 // result shall be the alignment of the referenced type."
1525 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1526 SrcTy = Ref->getPointeeType();
Sebastian Redl05189992008-11-11 17:56:53 +00001527
Daniel Dunbar131eb432009-02-19 09:06:44 +00001528 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1529 // extension.
1530 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1531 return Success(1, E);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001532
Chris Lattnerfcee0012008-07-11 21:24:13 +00001533 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001534 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001535 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001536
Chris Lattnere9feb472009-01-24 21:09:06 +00001537 // Get information about the size.
Ken Dyck199c3d62010-01-11 17:06:35 +00001538 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001539}
1540
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001541bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1542 CharUnits Result;
1543 unsigned n = E->getNumComponents();
1544 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1545 if (n == 0)
1546 return false;
1547 QualType CurrentType = E->getTypeSourceInfo()->getType();
1548 for (unsigned i = 0; i != n; ++i) {
1549 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1550 switch (ON.getKind()) {
1551 case OffsetOfExpr::OffsetOfNode::Array: {
1552 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1553 APSInt IdxResult;
1554 if (!EvaluateInteger(Idx, IdxResult, Info))
1555 return false;
1556 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1557 if (!AT)
1558 return false;
1559 CurrentType = AT->getElementType();
1560 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1561 Result += IdxResult.getSExtValue() * ElementSize;
1562 break;
1563 }
1564
1565 case OffsetOfExpr::OffsetOfNode::Field: {
1566 FieldDecl *MemberDecl = ON.getField();
1567 const RecordType *RT = CurrentType->getAs<RecordType>();
1568 if (!RT)
1569 return false;
1570 RecordDecl *RD = RT->getDecl();
1571 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1572 unsigned i = 0;
1573 // FIXME: It would be nice if we didn't have to loop here!
1574 for (RecordDecl::field_iterator Field = RD->field_begin(),
1575 FieldEnd = RD->field_end();
1576 Field != FieldEnd; (void)++Field, ++i) {
1577 if (*Field == MemberDecl)
1578 break;
1579 }
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001580 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1581 Result += CharUnits::fromQuantity(
1582 RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001583 CurrentType = MemberDecl->getType().getNonReferenceType();
1584 break;
1585 }
1586
1587 case OffsetOfExpr::OffsetOfNode::Identifier:
1588 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001589 return false;
1590
1591 case OffsetOfExpr::OffsetOfNode::Base: {
1592 CXXBaseSpecifier *BaseSpec = ON.getBase();
1593 if (BaseSpec->isVirtual())
1594 return false;
1595
1596 // Find the layout of the class whose base we are looking into.
1597 const RecordType *RT = CurrentType->getAs<RecordType>();
1598 if (!RT)
1599 return false;
1600 RecordDecl *RD = RT->getDecl();
1601 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1602
1603 // Find the base class itself.
1604 CurrentType = BaseSpec->getType();
1605 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1606 if (!BaseRT)
1607 return false;
1608
1609 // Add the offset to the base.
1610 Result += CharUnits::fromQuantity(
Anders Carlssona14f5972010-10-31 23:22:37 +00001611 RL.getBaseClassOffsetInBits(cast<CXXRecordDecl>(BaseRT->getDecl()))
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001612 / Info.Ctx.getCharWidth());
1613 break;
1614 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001615 }
1616 }
1617 return Success(Result.getQuantity(), E);
1618}
1619
Chris Lattnerb542afe2008-07-11 19:10:17 +00001620bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001621 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001622 // LNot's operand isn't necessarily an integer, so we handle it specially.
1623 bool bres;
1624 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1625 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001626 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001627 }
1628
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001629 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001630 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001631 return false;
1632
Chris Lattner87eae5e2008-07-11 22:52:41 +00001633 // Get the operand value into 'Result'.
1634 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001635 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001636
Chris Lattner75a48812008-07-11 22:15:16 +00001637 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001638 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001639 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1640 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001641 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001642 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001643 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1644 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001645 return true;
John McCall2de56d12010-08-25 11:45:40 +00001646 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001647 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001648 return true;
John McCall2de56d12010-08-25 11:45:40 +00001649 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001650 if (!Result.isInt()) return false;
1651 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001652 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001653 if (!Result.isInt()) return false;
1654 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001655 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001656}
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Chris Lattner732b2232008-07-12 01:15:53 +00001658/// HandleCast - This is used to evaluate implicit or explicit casts where the
1659/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001660bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001661 Expr *SubExpr = E->getSubExpr();
1662 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001663 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001664
Eli Friedman4efaa272008-11-12 09:44:48 +00001665 if (DestType->isBooleanType()) {
1666 bool BoolResult;
1667 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1668 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001669 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001670 }
1671
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001672 // Handle simple integer->integer casts.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001673 if (SrcType->isIntegralOrEnumerationType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001674 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001675 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001676
Eli Friedmanbe265702009-02-20 01:15:07 +00001677 if (!Result.isInt()) {
1678 // Only allow casts of lvalues if they are lossless.
1679 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1680 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001681
Daniel Dunbardd211642009-02-19 22:24:01 +00001682 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001683 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001684 }
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Chris Lattner732b2232008-07-12 01:15:53 +00001686 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001687 if (SrcType->isPointerType()) {
John McCallefdb83e2010-05-07 21:00:08 +00001688 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001689 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001690 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001691
Daniel Dunbardd211642009-02-19 22:24:01 +00001692 if (LV.getLValueBase()) {
1693 // Only allow based lvalue casts if they are lossless.
1694 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1695 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001696
John McCallefdb83e2010-05-07 21:00:08 +00001697 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001698 return true;
1699 }
1700
Ken Dycka7305832010-01-15 12:37:54 +00001701 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1702 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001703 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001704 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001705
Eli Friedmanbe265702009-02-20 01:15:07 +00001706 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1707 // This handles double-conversion cases, where there's both
1708 // an l-value promotion and an implicit conversion to int.
John McCallefdb83e2010-05-07 21:00:08 +00001709 LValue LV;
Eli Friedmanbe265702009-02-20 01:15:07 +00001710 if (!EvaluateLValue(SubExpr, LV, Info))
1711 return false;
1712
1713 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1714 return false;
1715
John McCallefdb83e2010-05-07 21:00:08 +00001716 LV.moveInto(Result);
Eli Friedmanbe265702009-02-20 01:15:07 +00001717 return true;
1718 }
1719
Eli Friedman1725f682009-04-22 19:23:09 +00001720 if (SrcType->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001721 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001722 if (!EvaluateComplex(SubExpr, C, Info))
1723 return false;
1724 if (C.isComplexFloat())
1725 return Success(HandleFloatToIntCast(DestType, SrcType,
1726 C.getComplexFloatReal(), Info.Ctx),
1727 E);
1728 else
1729 return Success(HandleIntToIntCast(DestType, SrcType,
1730 C.getComplexIntReal(), Info.Ctx), E);
1731 }
Eli Friedman2217c872009-02-22 11:46:18 +00001732 // FIXME: Handle vectors
1733
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001734 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001735 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001736
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001737 APFloat F(0.0);
1738 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001739 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001741 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001742}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001743
Eli Friedman722c7172009-02-28 03:59:05 +00001744bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1745 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001746 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001747 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1748 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1749 return Success(LV.getComplexIntReal(), E);
1750 }
1751
1752 return Visit(E->getSubExpr());
1753}
1754
Eli Friedman664a1042009-02-27 04:45:43 +00001755bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001756 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001757 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001758 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1759 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1760 return Success(LV.getComplexIntImag(), E);
1761 }
1762
Eli Friedman664a1042009-02-27 04:45:43 +00001763 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1764 Info.EvalResult.HasSideEffects = true;
1765 return Success(0, E);
1766}
1767
Douglas Gregoree8aff02011-01-04 17:33:58 +00001768bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1769 return Success(E->getPackLength(), E);
1770}
1771
Sebastian Redl295995c2010-09-10 20:55:47 +00001772bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1773 return Success(E->getValue(), E);
1774}
1775
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001776//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001777// Float Evaluation
1778//===----------------------------------------------------------------------===//
1779
1780namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001781class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001782 : public StmtVisitor<FloatExprEvaluator, bool> {
1783 EvalInfo &Info;
1784 APFloat &Result;
1785public:
1786 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1787 : Info(info), Result(result) {}
1788
1789 bool VisitStmt(Stmt *S) {
1790 return false;
1791 }
1792
1793 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001794 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001795
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001796 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001797 bool VisitBinaryOperator(const BinaryOperator *E);
1798 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001799 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001800 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001801 bool VisitConditionalOperator(ConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001802
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001803 bool VisitChooseExpr(const ChooseExpr *E)
1804 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1805 bool VisitUnaryExtension(const UnaryOperator *E)
1806 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001807 bool VisitUnaryReal(const UnaryOperator *E);
1808 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001809
John McCall189d6ef2010-10-09 01:34:31 +00001810 bool VisitDeclRefExpr(const DeclRefExpr *E);
1811
John McCallabd3a852010-05-07 22:08:54 +00001812 // FIXME: Missing: array subscript of vector, member of vector,
1813 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001814};
1815} // end anonymous namespace
1816
1817static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001818 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001819 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1820}
1821
Jay Foad4ba2a172011-01-12 09:06:06 +00001822static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001823 QualType ResultTy,
1824 const Expr *Arg,
1825 bool SNaN,
1826 llvm::APFloat &Result) {
1827 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1828 if (!S) return false;
1829
1830 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1831
1832 llvm::APInt fill;
1833
1834 // Treat empty strings as if they were zero.
1835 if (S->getString().empty())
1836 fill = llvm::APInt(32, 0);
1837 else if (S->getString().getAsInteger(0, fill))
1838 return false;
1839
1840 if (SNaN)
1841 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1842 else
1843 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1844 return true;
1845}
1846
Chris Lattner019f4e82008-10-06 05:28:25 +00001847bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001848 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001849 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001850 case Builtin::BI__builtin_huge_val:
1851 case Builtin::BI__builtin_huge_valf:
1852 case Builtin::BI__builtin_huge_vall:
1853 case Builtin::BI__builtin_inf:
1854 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001855 case Builtin::BI__builtin_infl: {
1856 const llvm::fltSemantics &Sem =
1857 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001858 Result = llvm::APFloat::getInf(Sem);
1859 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001860 }
Mike Stump1eb44332009-09-09 15:08:12 +00001861
John McCalldb7b72a2010-02-28 13:00:19 +00001862 case Builtin::BI__builtin_nans:
1863 case Builtin::BI__builtin_nansf:
1864 case Builtin::BI__builtin_nansl:
1865 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1866 true, Result);
1867
Chris Lattner9e621712008-10-06 06:31:58 +00001868 case Builtin::BI__builtin_nan:
1869 case Builtin::BI__builtin_nanf:
1870 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00001871 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00001872 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00001873 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1874 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001875
1876 case Builtin::BI__builtin_fabs:
1877 case Builtin::BI__builtin_fabsf:
1878 case Builtin::BI__builtin_fabsl:
1879 if (!EvaluateFloat(E->getArg(0), Result, Info))
1880 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001882 if (Result.isNegative())
1883 Result.changeSign();
1884 return true;
1885
Mike Stump1eb44332009-09-09 15:08:12 +00001886 case Builtin::BI__builtin_copysign:
1887 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001888 case Builtin::BI__builtin_copysignl: {
1889 APFloat RHS(0.);
1890 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1891 !EvaluateFloat(E->getArg(1), RHS, Info))
1892 return false;
1893 Result.copySign(RHS);
1894 return true;
1895 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001896 }
1897}
1898
John McCall189d6ef2010-10-09 01:34:31 +00001899bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
1900 const Decl *D = E->getDecl();
1901 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
1902 const VarDecl *VD = cast<VarDecl>(D);
1903
1904 // Require the qualifiers to be const and not volatile.
1905 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
1906 if (!T.isConstQualified() || T.isVolatileQualified())
1907 return false;
1908
1909 const Expr *Init = VD->getAnyInitializer();
1910 if (!Init) return false;
1911
1912 if (APValue *V = VD->getEvaluatedValue()) {
1913 if (V->isFloat()) {
1914 Result = V->getFloat();
1915 return true;
1916 }
1917 return false;
1918 }
1919
1920 if (VD->isEvaluatingValue())
1921 return false;
1922
1923 VD->setEvaluatingValue();
1924
1925 Expr::EvalResult InitResult;
1926 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
1927 InitResult.Val.isFloat()) {
1928 // Cache the evaluated value in the variable declaration.
1929 Result = InitResult.Val.getFloat();
1930 VD->setEvaluatedValue(InitResult.Val);
1931 return true;
1932 }
1933
1934 VD->setEvaluatedValue(APValue());
1935 return false;
1936}
1937
John McCallabd3a852010-05-07 22:08:54 +00001938bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00001939 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1940 ComplexValue CV;
1941 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1942 return false;
1943 Result = CV.FloatReal;
1944 return true;
1945 }
1946
1947 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00001948}
1949
1950bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00001951 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1952 ComplexValue CV;
1953 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1954 return false;
1955 Result = CV.FloatImag;
1956 return true;
1957 }
1958
1959 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1960 Info.EvalResult.HasSideEffects = true;
1961 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
1962 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00001963 return true;
1964}
1965
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001966bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001967 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00001968 return false;
1969
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001970 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1971 return false;
1972
1973 switch (E->getOpcode()) {
1974 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00001975 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001976 return true;
John McCall2de56d12010-08-25 11:45:40 +00001977 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001978 Result.changeSign();
1979 return true;
1980 }
1981}
Chris Lattner019f4e82008-10-06 05:28:25 +00001982
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001983bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001984 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00001985 if (!EvaluateFloat(E->getRHS(), Result, Info))
1986 return false;
1987
1988 // If we can't evaluate the LHS, it might have side effects;
1989 // conservatively mark it.
1990 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1991 Info.EvalResult.HasSideEffects = true;
1992
1993 return true;
1994 }
1995
Anders Carlsson96e93662010-10-31 01:21:47 +00001996 // We can't evaluate pointer-to-member operations.
1997 if (E->isPtrMemOp())
1998 return false;
1999
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002000 // FIXME: Diagnostics? I really don't understand how the warnings
2001 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002002 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002003 if (!EvaluateFloat(E->getLHS(), Result, Info))
2004 return false;
2005 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2006 return false;
2007
2008 switch (E->getOpcode()) {
2009 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002010 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002011 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2012 return true;
John McCall2de56d12010-08-25 11:45:40 +00002013 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002014 Result.add(RHS, APFloat::rmNearestTiesToEven);
2015 return true;
John McCall2de56d12010-08-25 11:45:40 +00002016 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002017 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2018 return true;
John McCall2de56d12010-08-25 11:45:40 +00002019 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002020 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2021 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002022 }
2023}
2024
2025bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2026 Result = E->getValue();
2027 return true;
2028}
2029
Eli Friedman4efaa272008-11-12 09:44:48 +00002030bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2031 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002033 if (SubExpr->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002034 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002035 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002036 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002037 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002038 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002039 return true;
2040 }
2041 if (SubExpr->getType()->isRealFloatingType()) {
2042 if (!Visit(SubExpr))
2043 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002044 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2045 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002046 return true;
2047 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002048
2049 if (E->getCastKind() == CK_FloatingComplexToReal) {
2050 ComplexValue V;
2051 if (!EvaluateComplex(SubExpr, V, Info))
2052 return false;
2053 Result = V.getComplexFloatReal();
2054 return true;
2055 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002056
2057 return false;
2058}
2059
Douglas Gregored8abf12010-07-08 06:14:04 +00002060bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002061 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2062 return true;
2063}
2064
Eli Friedman67f85fc2009-12-04 02:12:53 +00002065bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2066 bool Cond;
2067 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2068 return false;
2069
2070 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2071}
2072
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002073//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002074// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002075//===----------------------------------------------------------------------===//
2076
2077namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002078class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00002079 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002080 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00002081 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002083public:
John McCallf4cf1a12010-05-07 17:22:02 +00002084 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2085 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002087 //===--------------------------------------------------------------------===//
2088 // Visitor Methods
2089 //===--------------------------------------------------------------------===//
2090
John McCallf4cf1a12010-05-07 17:22:02 +00002091 bool VisitStmt(Stmt *S) {
2092 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094
John McCallf4cf1a12010-05-07 17:22:02 +00002095 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002096
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002097 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002098
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002099 bool VisitCastExpr(CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002100
John McCallf4cf1a12010-05-07 17:22:02 +00002101 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002102 bool VisitUnaryOperator(const UnaryOperator *E);
2103 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCallf4cf1a12010-05-07 17:22:02 +00002104 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002105 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002106 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002107 { return Visit(E->getSubExpr()); }
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002108 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002109};
2110} // end anonymous namespace
2111
John McCallf4cf1a12010-05-07 17:22:02 +00002112static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2113 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002114 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002115 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002116}
2117
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002118bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2119 Expr* SubExpr = E->getSubExpr();
2120
2121 if (SubExpr->getType()->isRealFloatingType()) {
2122 Result.makeComplexFloat();
2123 APFloat &Imag = Result.FloatImag;
2124 if (!EvaluateFloat(SubExpr, Imag, Info))
2125 return false;
2126
2127 Result.FloatReal = APFloat(Imag.getSemantics());
2128 return true;
2129 } else {
2130 assert(SubExpr->getType()->isIntegerType() &&
2131 "Unexpected imaginary literal.");
2132
2133 Result.makeComplexInt();
2134 APSInt &Imag = Result.IntImag;
2135 if (!EvaluateInteger(SubExpr, Imag, Info))
2136 return false;
2137
2138 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2139 return true;
2140 }
2141}
2142
2143bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002144
John McCall8786da72010-12-14 17:51:41 +00002145 switch (E->getCastKind()) {
2146 case CK_BitCast:
2147 case CK_LValueBitCast:
2148 case CK_BaseToDerived:
2149 case CK_DerivedToBase:
2150 case CK_UncheckedDerivedToBase:
2151 case CK_Dynamic:
2152 case CK_ToUnion:
2153 case CK_ArrayToPointerDecay:
2154 case CK_FunctionToPointerDecay:
2155 case CK_NullToPointer:
2156 case CK_NullToMemberPointer:
2157 case CK_BaseToDerivedMemberPointer:
2158 case CK_DerivedToBaseMemberPointer:
2159 case CK_MemberPointerToBoolean:
2160 case CK_ConstructorConversion:
2161 case CK_IntegralToPointer:
2162 case CK_PointerToIntegral:
2163 case CK_PointerToBoolean:
2164 case CK_ToVoid:
2165 case CK_VectorSplat:
2166 case CK_IntegralCast:
2167 case CK_IntegralToBoolean:
2168 case CK_IntegralToFloating:
2169 case CK_FloatingToIntegral:
2170 case CK_FloatingToBoolean:
2171 case CK_FloatingCast:
2172 case CK_AnyPointerToObjCPointerCast:
2173 case CK_AnyPointerToBlockPointerCast:
2174 case CK_ObjCObjectLValueCast:
2175 case CK_FloatingComplexToReal:
2176 case CK_FloatingComplexToBoolean:
2177 case CK_IntegralComplexToReal:
2178 case CK_IntegralComplexToBoolean:
2179 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002180
John McCall8786da72010-12-14 17:51:41 +00002181 case CK_LValueToRValue:
2182 case CK_NoOp:
2183 return Visit(E->getSubExpr());
2184
2185 case CK_Dependent:
2186 case CK_GetObjCProperty:
2187 case CK_UserDefinedConversion:
2188 return false;
2189
2190 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002191 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002192 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002193 return false;
2194
John McCall8786da72010-12-14 17:51:41 +00002195 Result.makeComplexFloat();
2196 Result.FloatImag = APFloat(Real.getSemantics());
2197 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002198 }
2199
John McCall8786da72010-12-14 17:51:41 +00002200 case CK_FloatingComplexCast: {
2201 if (!Visit(E->getSubExpr()))
2202 return false;
2203
2204 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2205 QualType From
2206 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2207
2208 Result.FloatReal
2209 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2210 Result.FloatImag
2211 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2212 return true;
2213 }
2214
2215 case CK_FloatingComplexToIntegralComplex: {
2216 if (!Visit(E->getSubExpr()))
2217 return false;
2218
2219 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2220 QualType From
2221 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2222 Result.makeComplexInt();
2223 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2224 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2225 return true;
2226 }
2227
2228 case CK_IntegralRealToComplex: {
2229 APSInt &Real = Result.IntReal;
2230 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2231 return false;
2232
2233 Result.makeComplexInt();
2234 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2235 return true;
2236 }
2237
2238 case CK_IntegralComplexCast: {
2239 if (!Visit(E->getSubExpr()))
2240 return false;
2241
2242 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2243 QualType From
2244 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2245
2246 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2247 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2248 return true;
2249 }
2250
2251 case CK_IntegralComplexToFloatingComplex: {
2252 if (!Visit(E->getSubExpr()))
2253 return false;
2254
2255 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2256 QualType From
2257 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2258 Result.makeComplexFloat();
2259 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2260 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2261 return true;
2262 }
2263 }
2264
2265 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002266 return false;
2267}
2268
John McCallf4cf1a12010-05-07 17:22:02 +00002269bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002270 if (E->getOpcode() == BO_Comma) {
2271 if (!Visit(E->getRHS()))
2272 return false;
2273
2274 // If we can't evaluate the LHS, it might have side effects;
2275 // conservatively mark it.
2276 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2277 Info.EvalResult.HasSideEffects = true;
2278
2279 return true;
2280 }
John McCallf4cf1a12010-05-07 17:22:02 +00002281 if (!Visit(E->getLHS()))
2282 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002283
John McCallf4cf1a12010-05-07 17:22:02 +00002284 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002285 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002286 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002287
Daniel Dunbar3f279872009-01-29 01:32:56 +00002288 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2289 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002290 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002291 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002292 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002293 if (Result.isComplexFloat()) {
2294 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2295 APFloat::rmNearestTiesToEven);
2296 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2297 APFloat::rmNearestTiesToEven);
2298 } else {
2299 Result.getComplexIntReal() += RHS.getComplexIntReal();
2300 Result.getComplexIntImag() += RHS.getComplexIntImag();
2301 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002302 break;
John McCall2de56d12010-08-25 11:45:40 +00002303 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002304 if (Result.isComplexFloat()) {
2305 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2306 APFloat::rmNearestTiesToEven);
2307 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2308 APFloat::rmNearestTiesToEven);
2309 } else {
2310 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2311 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2312 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002313 break;
John McCall2de56d12010-08-25 11:45:40 +00002314 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002315 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002316 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002317 APFloat &LHS_r = LHS.getComplexFloatReal();
2318 APFloat &LHS_i = LHS.getComplexFloatImag();
2319 APFloat &RHS_r = RHS.getComplexFloatReal();
2320 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Daniel Dunbar3f279872009-01-29 01:32:56 +00002322 APFloat Tmp = LHS_r;
2323 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2324 Result.getComplexFloatReal() = Tmp;
2325 Tmp = LHS_i;
2326 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2327 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2328
2329 Tmp = LHS_r;
2330 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2331 Result.getComplexFloatImag() = Tmp;
2332 Tmp = LHS_i;
2333 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2334 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2335 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002336 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002337 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002338 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2339 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002340 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002341 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2342 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2343 }
2344 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002345 case BO_Div:
2346 if (Result.isComplexFloat()) {
2347 ComplexValue LHS = Result;
2348 APFloat &LHS_r = LHS.getComplexFloatReal();
2349 APFloat &LHS_i = LHS.getComplexFloatImag();
2350 APFloat &RHS_r = RHS.getComplexFloatReal();
2351 APFloat &RHS_i = RHS.getComplexFloatImag();
2352 APFloat &Res_r = Result.getComplexFloatReal();
2353 APFloat &Res_i = Result.getComplexFloatImag();
2354
2355 APFloat Den = RHS_r;
2356 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2357 APFloat Tmp = RHS_i;
2358 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2359 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2360
2361 Res_r = LHS_r;
2362 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2363 Tmp = LHS_i;
2364 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2365 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2366 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2367
2368 Res_i = LHS_i;
2369 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2370 Tmp = LHS_r;
2371 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2372 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2373 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2374 } else {
2375 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2376 // FIXME: what about diagnostics?
2377 return false;
2378 }
2379 ComplexValue LHS = Result;
2380 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2381 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2382 Result.getComplexIntReal() =
2383 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2384 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2385 Result.getComplexIntImag() =
2386 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2387 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2388 }
2389 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002390 }
2391
John McCallf4cf1a12010-05-07 17:22:02 +00002392 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002393}
2394
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002395bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2396 // Get the operand value into 'Result'.
2397 if (!Visit(E->getSubExpr()))
2398 return false;
2399
2400 switch (E->getOpcode()) {
2401 default:
2402 // FIXME: what about diagnostics?
2403 return false;
2404 case UO_Extension:
2405 return true;
2406 case UO_Plus:
2407 // The result is always just the subexpr.
2408 return true;
2409 case UO_Minus:
2410 if (Result.isComplexFloat()) {
2411 Result.getComplexFloatReal().changeSign();
2412 Result.getComplexFloatImag().changeSign();
2413 }
2414 else {
2415 Result.getComplexIntReal() = -Result.getComplexIntReal();
2416 Result.getComplexIntImag() = -Result.getComplexIntImag();
2417 }
2418 return true;
2419 case UO_Not:
2420 if (Result.isComplexFloat())
2421 Result.getComplexFloatImag().changeSign();
2422 else
2423 Result.getComplexIntImag() = -Result.getComplexIntImag();
2424 return true;
2425 }
2426}
2427
2428bool ComplexExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
2429 bool Cond;
2430 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2431 return false;
2432
2433 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2434}
2435
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002436//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002437// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002438//===----------------------------------------------------------------------===//
2439
John McCall42c8f872010-05-10 23:27:23 +00002440/// Evaluate - Return true if this is a constant which we can fold using
2441/// any crazy technique (that has nothing to do with language standards) that
2442/// we want to. If this function returns true, it returns the folded constant
2443/// in Result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002444bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
John McCall42c8f872010-05-10 23:27:23 +00002445 const Expr *E = this;
2446 EvalInfo Info(Ctx, Result);
John McCallefdb83e2010-05-07 21:00:08 +00002447 if (E->getType()->isVectorType()) {
2448 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002449 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002450 } else if (E->getType()->isIntegerType()) {
2451 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002452 return false;
John McCall0f2b6922010-07-07 05:08:32 +00002453 if (Result.Val.isLValue() && !IsGlobalLValue(Result.Val.getLValueBase()))
2454 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002455 } else if (E->getType()->hasPointerRepresentation()) {
2456 LValue LV;
2457 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002458 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002459 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002460 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002461 LV.moveInto(Info.EvalResult.Val);
2462 } else if (E->getType()->isRealFloatingType()) {
2463 llvm::APFloat F(0.0);
2464 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002465 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002466
John McCallefdb83e2010-05-07 21:00:08 +00002467 Info.EvalResult.Val = APValue(F);
2468 } else if (E->getType()->isAnyComplexType()) {
2469 ComplexValue C;
2470 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002471 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002472 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002473 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002474 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002475
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002476 return true;
2477}
2478
Jay Foad4ba2a172011-01-12 09:06:06 +00002479bool Expr::EvaluateAsBooleanCondition(bool &Result,
2480 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002481 EvalResult Scratch;
2482 EvalInfo Info(Ctx, Scratch);
2483
2484 return HandleConversionToBool(this, Result, Info);
2485}
2486
Jay Foad4ba2a172011-01-12 09:06:06 +00002487bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002488 EvalInfo Info(Ctx, Result);
2489
John McCallefdb83e2010-05-07 21:00:08 +00002490 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002491 if (EvaluateLValue(this, LV, Info) &&
2492 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002493 IsGlobalLValue(LV.Base)) {
2494 LV.moveInto(Result.Val);
2495 return true;
2496 }
2497 return false;
2498}
2499
Jay Foad4ba2a172011-01-12 09:06:06 +00002500bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2501 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002502 EvalInfo Info(Ctx, Result);
2503
2504 LValue LV;
2505 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002506 LV.moveInto(Result.Val);
2507 return true;
2508 }
2509 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002510}
2511
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002512/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002513/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002514bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002515 EvalResult Result;
2516 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002517}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002518
Jay Foad4ba2a172011-01-12 09:06:06 +00002519bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002520 Expr::EvalResult Result;
2521 EvalInfo Info(Ctx, Result);
2522 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2523}
2524
Jay Foad4ba2a172011-01-12 09:06:06 +00002525APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002526 EvalResult EvalResult;
2527 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002528 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002529 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002530 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002531
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002532 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002533}
John McCalld905f5a2010-05-07 05:32:02 +00002534
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002535 bool Expr::EvalResult::isGlobalLValue() const {
2536 assert(Val.isLValue());
2537 return IsGlobalLValue(Val.getLValueBase());
2538 }
2539
2540
John McCalld905f5a2010-05-07 05:32:02 +00002541/// isIntegerConstantExpr - this recursive routine will test if an expression is
2542/// an integer constant expression.
2543
2544/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2545/// comma, etc
2546///
2547/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2548/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2549/// cast+dereference.
2550
2551// CheckICE - This function does the fundamental ICE checking: the returned
2552// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2553// Note that to reduce code duplication, this helper does no evaluation
2554// itself; the caller checks whether the expression is evaluatable, and
2555// in the rare cases where CheckICE actually cares about the evaluated
2556// value, it calls into Evalute.
2557//
2558// Meanings of Val:
2559// 0: This expression is an ICE if it can be evaluated by Evaluate.
2560// 1: This expression is not an ICE, but if it isn't evaluated, it's
2561// a legal subexpression for an ICE. This return value is used to handle
2562// the comma operator in C99 mode.
2563// 2: This expression is not an ICE, and is not a legal subexpression for one.
2564
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002565namespace {
2566
John McCalld905f5a2010-05-07 05:32:02 +00002567struct ICEDiag {
2568 unsigned Val;
2569 SourceLocation Loc;
2570
2571 public:
2572 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2573 ICEDiag() : Val(0) {}
2574};
2575
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002576}
2577
2578static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002579
2580static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2581 Expr::EvalResult EVResult;
2582 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2583 !EVResult.Val.isInt()) {
2584 return ICEDiag(2, E->getLocStart());
2585 }
2586 return NoDiag();
2587}
2588
2589static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2590 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002591 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002592 return ICEDiag(2, E->getLocStart());
2593 }
2594
2595 switch (E->getStmtClass()) {
2596#define STMT(Node, Base) case Expr::Node##Class:
2597#define EXPR(Node, Base)
2598#include "clang/AST/StmtNodes.inc"
2599 case Expr::PredefinedExprClass:
2600 case Expr::FloatingLiteralClass:
2601 case Expr::ImaginaryLiteralClass:
2602 case Expr::StringLiteralClass:
2603 case Expr::ArraySubscriptExprClass:
2604 case Expr::MemberExprClass:
2605 case Expr::CompoundAssignOperatorClass:
2606 case Expr::CompoundLiteralExprClass:
2607 case Expr::ExtVectorElementExprClass:
2608 case Expr::InitListExprClass:
2609 case Expr::DesignatedInitExprClass:
2610 case Expr::ImplicitValueInitExprClass:
2611 case Expr::ParenListExprClass:
2612 case Expr::VAArgExprClass:
2613 case Expr::AddrLabelExprClass:
2614 case Expr::StmtExprClass:
2615 case Expr::CXXMemberCallExprClass:
2616 case Expr::CXXDynamicCastExprClass:
2617 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002618 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002619 case Expr::CXXNullPtrLiteralExprClass:
2620 case Expr::CXXThisExprClass:
2621 case Expr::CXXThrowExprClass:
2622 case Expr::CXXNewExprClass:
2623 case Expr::CXXDeleteExprClass:
2624 case Expr::CXXPseudoDestructorExprClass:
2625 case Expr::UnresolvedLookupExprClass:
2626 case Expr::DependentScopeDeclRefExprClass:
2627 case Expr::CXXConstructExprClass:
2628 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002629 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002630 case Expr::CXXTemporaryObjectExprClass:
2631 case Expr::CXXUnresolvedConstructExprClass:
2632 case Expr::CXXDependentScopeMemberExprClass:
2633 case Expr::UnresolvedMemberExprClass:
2634 case Expr::ObjCStringLiteralClass:
2635 case Expr::ObjCEncodeExprClass:
2636 case Expr::ObjCMessageExprClass:
2637 case Expr::ObjCSelectorExprClass:
2638 case Expr::ObjCProtocolExprClass:
2639 case Expr::ObjCIvarRefExprClass:
2640 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002641 case Expr::ObjCIsaExprClass:
2642 case Expr::ShuffleVectorExprClass:
2643 case Expr::BlockExprClass:
2644 case Expr::BlockDeclRefExprClass:
2645 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002646 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002647 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002648 case Expr::SubstNonTypeTemplateParmPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002649 return ICEDiag(2, E->getLocStart());
2650
Douglas Gregoree8aff02011-01-04 17:33:58 +00002651 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002652 case Expr::GNUNullExprClass:
2653 // GCC considers the GNU __null value to be an integral constant expression.
2654 return NoDiag();
2655
2656 case Expr::ParenExprClass:
2657 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2658 case Expr::IntegerLiteralClass:
2659 case Expr::CharacterLiteralClass:
2660 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002661 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002662 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002663 case Expr::BinaryTypeTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002664 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002665 return NoDiag();
2666 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002667 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002668 const CallExpr *CE = cast<CallExpr>(E);
2669 if (CE->isBuiltinCall(Ctx))
2670 return CheckEvalInICE(E, Ctx);
2671 return ICEDiag(2, E->getLocStart());
2672 }
2673 case Expr::DeclRefExprClass:
2674 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2675 return NoDiag();
2676 if (Ctx.getLangOptions().CPlusPlus &&
2677 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2678 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2679
2680 // Parameter variables are never constants. Without this check,
2681 // getAnyInitializer() can find a default argument, which leads
2682 // to chaos.
2683 if (isa<ParmVarDecl>(D))
2684 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2685
2686 // C++ 7.1.5.1p2
2687 // A variable of non-volatile const-qualified integral or enumeration
2688 // type initialized by an ICE can be used in ICEs.
2689 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2690 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2691 if (Quals.hasVolatile() || !Quals.hasConst())
2692 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2693
2694 // Look for a declaration of this variable that has an initializer.
2695 const VarDecl *ID = 0;
2696 const Expr *Init = Dcl->getAnyInitializer(ID);
2697 if (Init) {
2698 if (ID->isInitKnownICE()) {
2699 // We have already checked whether this subexpression is an
2700 // integral constant expression.
2701 if (ID->isInitICE())
2702 return NoDiag();
2703 else
2704 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2705 }
2706
2707 // It's an ICE whether or not the definition we found is
2708 // out-of-line. See DR 721 and the discussion in Clang PR
2709 // 6206 for details.
2710
2711 if (Dcl->isCheckingICE()) {
2712 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2713 }
2714
2715 Dcl->setCheckingICE();
2716 ICEDiag Result = CheckICE(Init, Ctx);
2717 // Cache the result of the ICE test.
2718 Dcl->setInitKnownICE(Result.Val == 0);
2719 return Result;
2720 }
2721 }
2722 }
2723 return ICEDiag(2, E->getLocStart());
2724 case Expr::UnaryOperatorClass: {
2725 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2726 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002727 case UO_PostInc:
2728 case UO_PostDec:
2729 case UO_PreInc:
2730 case UO_PreDec:
2731 case UO_AddrOf:
2732 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002733 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002734 case UO_Extension:
2735 case UO_LNot:
2736 case UO_Plus:
2737 case UO_Minus:
2738 case UO_Not:
2739 case UO_Real:
2740 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002741 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002742 }
2743
2744 // OffsetOf falls through here.
2745 }
2746 case Expr::OffsetOfExprClass: {
2747 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2748 // Evaluate matches the proposed gcc behavior for cases like
2749 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2750 // compliance: we should warn earlier for offsetof expressions with
2751 // array subscripts that aren't ICEs, and if the array subscripts
2752 // are ICEs, the value of the offsetof must be an integer constant.
2753 return CheckEvalInICE(E, Ctx);
2754 }
2755 case Expr::SizeOfAlignOfExprClass: {
2756 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2757 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2758 return ICEDiag(2, E->getLocStart());
2759 return NoDiag();
2760 }
2761 case Expr::BinaryOperatorClass: {
2762 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2763 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002764 case BO_PtrMemD:
2765 case BO_PtrMemI:
2766 case BO_Assign:
2767 case BO_MulAssign:
2768 case BO_DivAssign:
2769 case BO_RemAssign:
2770 case BO_AddAssign:
2771 case BO_SubAssign:
2772 case BO_ShlAssign:
2773 case BO_ShrAssign:
2774 case BO_AndAssign:
2775 case BO_XorAssign:
2776 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002777 return ICEDiag(2, E->getLocStart());
2778
John McCall2de56d12010-08-25 11:45:40 +00002779 case BO_Mul:
2780 case BO_Div:
2781 case BO_Rem:
2782 case BO_Add:
2783 case BO_Sub:
2784 case BO_Shl:
2785 case BO_Shr:
2786 case BO_LT:
2787 case BO_GT:
2788 case BO_LE:
2789 case BO_GE:
2790 case BO_EQ:
2791 case BO_NE:
2792 case BO_And:
2793 case BO_Xor:
2794 case BO_Or:
2795 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002796 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2797 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002798 if (Exp->getOpcode() == BO_Div ||
2799 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002800 // Evaluate gives an error for undefined Div/Rem, so make sure
2801 // we don't evaluate one.
2802 if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2803 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2804 if (REval == 0)
2805 return ICEDiag(1, E->getLocStart());
2806 if (REval.isSigned() && REval.isAllOnesValue()) {
2807 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2808 if (LEval.isMinSignedValue())
2809 return ICEDiag(1, E->getLocStart());
2810 }
2811 }
2812 }
John McCall2de56d12010-08-25 11:45:40 +00002813 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002814 if (Ctx.getLangOptions().C99) {
2815 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2816 // if it isn't evaluated.
2817 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2818 return ICEDiag(1, E->getLocStart());
2819 } else {
2820 // In both C89 and C++, commas in ICEs are illegal.
2821 return ICEDiag(2, E->getLocStart());
2822 }
2823 }
2824 if (LHSResult.Val >= RHSResult.Val)
2825 return LHSResult;
2826 return RHSResult;
2827 }
John McCall2de56d12010-08-25 11:45:40 +00002828 case BO_LAnd:
2829 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002830 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2831 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2832 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2833 // Rare case where the RHS has a comma "side-effect"; we need
2834 // to actually check the condition to see whether the side
2835 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00002836 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00002837 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2838 return RHSResult;
2839 return NoDiag();
2840 }
2841
2842 if (LHSResult.Val >= RHSResult.Val)
2843 return LHSResult;
2844 return RHSResult;
2845 }
2846 }
2847 }
2848 case Expr::ImplicitCastExprClass:
2849 case Expr::CStyleCastExprClass:
2850 case Expr::CXXFunctionalCastExprClass:
2851 case Expr::CXXStaticCastExprClass:
2852 case Expr::CXXReinterpretCastExprClass:
2853 case Expr::CXXConstCastExprClass: {
2854 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002855 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00002856 return CheckICE(SubExpr, Ctx);
2857 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2858 return NoDiag();
2859 return ICEDiag(2, E->getLocStart());
2860 }
2861 case Expr::ConditionalOperatorClass: {
2862 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2863 // If the condition (ignoring parens) is a __builtin_constant_p call,
2864 // then only the true side is actually considered in an integer constant
2865 // expression, and it is fully evaluated. This is an important GNU
2866 // extension. See GCC PR38377 for discussion.
2867 if (const CallExpr *CallCE
2868 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2869 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2870 Expr::EvalResult EVResult;
2871 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2872 !EVResult.Val.isInt()) {
2873 return ICEDiag(2, E->getLocStart());
2874 }
2875 return NoDiag();
2876 }
2877 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2878 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2879 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2880 if (CondResult.Val == 2)
2881 return CondResult;
2882 if (TrueResult.Val == 2)
2883 return TrueResult;
2884 if (FalseResult.Val == 2)
2885 return FalseResult;
2886 if (CondResult.Val == 1)
2887 return CondResult;
2888 if (TrueResult.Val == 0 && FalseResult.Val == 0)
2889 return NoDiag();
2890 // Rare case where the diagnostics depend on which side is evaluated
2891 // Note that if we get here, CondResult is 0, and at least one of
2892 // TrueResult and FalseResult is non-zero.
2893 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2894 return FalseResult;
2895 }
2896 return TrueResult;
2897 }
2898 case Expr::CXXDefaultArgExprClass:
2899 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2900 case Expr::ChooseExprClass: {
2901 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2902 }
2903 }
2904
2905 // Silence a GCC warning
2906 return ICEDiag(2, E->getLocStart());
2907}
2908
2909bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2910 SourceLocation *Loc, bool isEvaluated) const {
2911 ICEDiag d = CheckICE(this, Ctx);
2912 if (d.Val != 0) {
2913 if (Loc) *Loc = d.Loc;
2914 return false;
2915 }
2916 EvalResult EvalResult;
2917 if (!Evaluate(EvalResult, Ctx))
2918 llvm_unreachable("ICE cannot be evaluated!");
2919 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2920 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2921 Result = EvalResult.Val.getInt();
2922 return true;
2923}