blob: 7f831737d14fe7e6d1f686617d0e030dabd633ea [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
45struct EvalInfo {
46 ASTContext &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +000047
Anders Carlssonbd1df8e2008-11-30 16:38:33 +000048 /// EvalResult - Contains information about the evaluation.
49 Expr::EvalResult &EvalResult;
Anders Carlsson58620012008-11-30 18:26:25 +000050
Eli Friedman7d45c482009-09-13 10:17:44 +000051 /// AnyLValue - Stack based LValue results are not discarded.
52 bool AnyLValue;
53
54 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult,
55 bool anylvalue = false)
56 : Ctx(ctx), EvalResult(evalresult), AnyLValue(anylvalue) {}
Chris Lattnercdf34e72008-07-11 22:52:41 +000057};
58
59
Eli Friedman9a156e52008-11-12 09:44:48 +000060static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +000061static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
62static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattner6c4d2552009-10-28 23:59:40 +000063static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
64 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +000065static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000066static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +000067
68//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +000069// Misc utilities
70//===----------------------------------------------------------------------===//
71
Eli Friedman334046a2009-06-14 02:17:33 +000072static bool EvalPointerValueAsBool(APValue& Value, bool& Result) {
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +000073 const Expr* Base = Value.getLValueBase();
74
75 Result = Base || !Value.getLValueOffset().isZero();
76
77 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
78 if (!DeclRef)
79 return true;
80
81 const ValueDecl* Decl = DeclRef->getDecl();
82 if (Decl->hasAttr<WeakAttr>() ||
83 Decl->hasAttr<WeakRefAttr>() ||
84 Decl->hasAttr<WeakImportAttr>())
85 return false;
86
Eli Friedman334046a2009-06-14 02:17:33 +000087 return true;
88}
89
John McCall1be1c632010-01-05 23:42:56 +000090static bool HandleConversionToBool(const Expr* E, bool& Result,
91 EvalInfo &Info) {
Eli Friedman9a156e52008-11-12 09:44:48 +000092 if (E->getType()->isIntegralType()) {
93 APSInt IntResult;
94 if (!EvaluateInteger(E, IntResult, Info))
95 return false;
96 Result = IntResult != 0;
97 return true;
98 } else if (E->getType()->isRealFloatingType()) {
99 APFloat FloatResult(0.0);
100 if (!EvaluateFloat(E, FloatResult, Info))
101 return false;
102 Result = !FloatResult.isZero();
103 return true;
Eli Friedman64004332009-03-23 04:38:34 +0000104 } else if (E->getType()->hasPointerRepresentation()) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000105 APValue PointerResult;
106 if (!EvaluatePointer(E, PointerResult, Info))
107 return false;
Eli Friedman334046a2009-06-14 02:17:33 +0000108 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +0000109 } else if (E->getType()->isAnyComplexType()) {
110 APValue ComplexResult;
111 if (!EvaluateComplex(E, ComplexResult, Info))
112 return false;
113 if (ComplexResult.isComplexFloat()) {
114 Result = !ComplexResult.getComplexFloatReal().isZero() ||
115 !ComplexResult.getComplexFloatImag().isZero();
116 } else {
117 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
118 ComplexResult.getComplexIntImag().getBoolValue();
119 }
120 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000121 }
122
123 return false;
124}
125
Mike Stump11289f42009-09-09 15:08:12 +0000126static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000127 APFloat &Value, ASTContext &Ctx) {
128 unsigned DestWidth = Ctx.getIntWidth(DestType);
129 // Determine whether we are converting to unsigned or signed.
130 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +0000131
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000132 // FIXME: Warning for overflow.
133 uint64_t Space[4];
134 bool ignored;
135 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
136 llvm::APFloat::rmTowardZero, &ignored);
137 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
138}
139
Mike Stump11289f42009-09-09 15:08:12 +0000140static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000141 APFloat &Value, ASTContext &Ctx) {
142 bool ignored;
143 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000144 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000145 APFloat::rmNearestTiesToEven, &ignored);
146 return Result;
147}
148
Mike Stump11289f42009-09-09 15:08:12 +0000149static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000150 APSInt &Value, ASTContext &Ctx) {
151 unsigned DestWidth = Ctx.getIntWidth(DestType);
152 APSInt Result = Value;
153 // Figure out if this is a truncate, extend or noop cast.
154 // If the input is signed, do a sign extend, noop, or truncate.
155 Result.extOrTrunc(DestWidth);
156 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
157 return Result;
158}
159
Mike Stump11289f42009-09-09 15:08:12 +0000160static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000161 APSInt &Value, ASTContext &Ctx) {
162
163 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
164 Result.convertFromAPInt(Value, Value.isSigned(),
165 APFloat::rmNearestTiesToEven);
166 return Result;
167}
168
Mike Stump876387b2009-10-27 22:09:17 +0000169namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000170class HasSideEffect
Mike Stump876387b2009-10-27 22:09:17 +0000171 : public StmtVisitor<HasSideEffect, bool> {
172 EvalInfo &Info;
173public:
174
175 HasSideEffect(EvalInfo &info) : Info(info) {}
176
177 // Unhandled nodes conservatively default to having side effects.
178 bool VisitStmt(Stmt *S) {
179 return true;
180 }
181
182 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
183 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000184 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000185 return true;
186 return false;
187 }
188 // We don't want to evaluate BlockExprs multiple times, as they generate
189 // a ton of code.
190 bool VisitBlockExpr(BlockExpr *E) { return true; }
191 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
192 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
193 { return Visit(E->getInitializer()); }
194 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
195 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
196 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
197 bool VisitStringLiteral(StringLiteral *E) { return false; }
198 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
199 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
200 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000201 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stump876387b2009-10-27 22:09:17 +0000202 bool VisitChooseExpr(ChooseExpr *E)
203 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
204 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
205 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stumpf3eb5ec2009-10-29 23:34:20 +0000206 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stumpfa502902009-10-29 20:48:09 +0000207 bool VisitBinaryOperator(BinaryOperator *E)
208 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stump876387b2009-10-27 22:09:17 +0000209 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
210 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
211 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
212 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
213 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000214 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000215 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000216 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000217 }
218 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000219
220 // Has side effects if any element does.
221 bool VisitInitListExpr(InitListExpr *E) {
222 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
223 if (Visit(E->getInit(i))) return true;
224 return false;
225 }
Mike Stump876387b2009-10-27 22:09:17 +0000226};
227
Mike Stump876387b2009-10-27 22:09:17 +0000228} // end anonymous namespace
229
Eli Friedman9a156e52008-11-12 09:44:48 +0000230//===----------------------------------------------------------------------===//
231// LValue Evaluation
232//===----------------------------------------------------------------------===//
233namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000234class LValueExprEvaluator
Eli Friedman9a156e52008-11-12 09:44:48 +0000235 : public StmtVisitor<LValueExprEvaluator, APValue> {
236 EvalInfo &Info;
237public:
Mike Stump11289f42009-09-09 15:08:12 +0000238
Eli Friedman9a156e52008-11-12 09:44:48 +0000239 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
240
241 APValue VisitStmt(Stmt *S) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000242 return APValue();
243 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000244
Eli Friedman9a156e52008-11-12 09:44:48 +0000245 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssona42ee442008-11-24 04:41:22 +0000246 APValue VisitDeclRefExpr(DeclRefExpr *E);
Ken Dyck02990832010-01-15 12:37:54 +0000247 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E); }
Eli Friedman9a156e52008-11-12 09:44:48 +0000248 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
249 APValue VisitMemberExpr(MemberExpr *E);
Ken Dyck02990832010-01-15 12:37:54 +0000250 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E); }
251 APValue VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return APValue(E); }
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000252 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000253 APValue VisitUnaryDeref(UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +0000254 APValue VisitUnaryExtension(const UnaryOperator *E)
255 { return Visit(E->getSubExpr()); }
256 APValue VisitChooseExpr(const ChooseExpr *E)
257 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlssonde55f642009-10-03 16:30:22 +0000258
259 APValue VisitCastExpr(CastExpr *E) {
260 switch (E->getCastKind()) {
261 default:
262 return APValue();
263
264 case CastExpr::CK_NoOp:
265 return Visit(E->getSubExpr());
266 }
267 }
Eli Friedman449fe542009-03-23 04:56:01 +0000268 // FIXME: Missing: __real__, __imag__
Eli Friedman9a156e52008-11-12 09:44:48 +0000269};
270} // end anonymous namespace
271
272static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
273 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
274 return Result.isLValue();
275}
276
Mike Stump11289f42009-09-09 15:08:12 +0000277APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000278 if (isa<FunctionDecl>(E->getDecl())) {
Ken Dyck02990832010-01-15 12:37:54 +0000279 return APValue(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000280 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman7d45c482009-09-13 10:17:44 +0000281 if (!Info.AnyLValue && !VD->hasGlobalStorage())
Eli Friedman9ab03192009-08-29 19:09:59 +0000282 return APValue();
Eli Friedman751aa72b72009-05-27 06:04:58 +0000283 if (!VD->getType()->isReferenceType())
Ken Dyck02990832010-01-15 12:37:54 +0000284 return APValue(E);
Eli Friedman9ab03192009-08-29 19:09:59 +0000285 // FIXME: Check whether VD might be overridden!
Sebastian Redl5ca79842010-02-01 20:16:42 +0000286 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregor0840cc02009-11-01 20:32:48 +0000287 return Visit(const_cast<Expr *>(Init));
Eli Friedman751aa72b72009-05-27 06:04:58 +0000288 }
289
290 return APValue();
Anders Carlssona42ee442008-11-24 04:41:22 +0000291}
292
Eli Friedman9a156e52008-11-12 09:44:48 +0000293APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
Eli Friedman7d45c482009-09-13 10:17:44 +0000294 if (!Info.AnyLValue && !E->isFileScope())
295 return APValue();
Ken Dyck02990832010-01-15 12:37:54 +0000296 return APValue(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000297}
298
299APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
300 APValue result;
301 QualType Ty;
302 if (E->isArrow()) {
303 if (!EvaluatePointer(E->getBase(), result, Info))
304 return APValue();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000305 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000306 } else {
307 result = Visit(E->getBase());
308 if (result.isUninit())
309 return APValue();
310 Ty = E->getBase()->getType();
311 }
312
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000313 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000314 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000315
316 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
317 if (!FD) // FIXME: deal with other kinds of member expressions
318 return APValue();
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000319
320 if (FD->getType()->isReferenceType())
321 return APValue();
322
Eli Friedman9a156e52008-11-12 09:44:48 +0000323 // FIXME: This is linear time.
Douglas Gregor91f84212008-12-11 16:49:14 +0000324 unsigned i = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000325 for (RecordDecl::field_iterator Field = RD->field_begin(),
326 FieldEnd = RD->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +0000327 Field != FieldEnd; (void)++Field, ++i) {
328 if (*Field == FD)
Eli Friedman9a156e52008-11-12 09:44:48 +0000329 break;
330 }
331
332 result.setLValue(result.getLValueBase(),
Ken Dyck02990832010-01-15 12:37:54 +0000333 result.getLValueOffset() +
334 CharUnits::fromQuantity(RL.getFieldOffset(i) / 8));
Eli Friedman9a156e52008-11-12 09:44:48 +0000335
336 return result;
337}
338
Mike Stump11289f42009-09-09 15:08:12 +0000339APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000340 APValue Result;
Mike Stump11289f42009-09-09 15:08:12 +0000341
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000342 if (!EvaluatePointer(E->getBase(), Result, Info))
343 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000344
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000345 APSInt Index;
346 if (!EvaluateInteger(E->getIdx(), Index, Info))
347 return APValue();
348
Ken Dyck40775002010-01-11 17:06:35 +0000349 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000350
Ken Dyck40775002010-01-11 17:06:35 +0000351 CharUnits Offset = Index.getSExtValue() * ElementSize;
Mike Stump11289f42009-09-09 15:08:12 +0000352 Result.setLValue(Result.getLValueBase(),
Ken Dyck02990832010-01-15 12:37:54 +0000353 Result.getLValueOffset() + Offset);
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000354 return Result;
355}
Eli Friedman9a156e52008-11-12 09:44:48 +0000356
Mike Stump11289f42009-09-09 15:08:12 +0000357APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
Eli Friedman0b8337c2009-02-20 01:57:15 +0000358 APValue Result;
359 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
360 return APValue();
361 return Result;
362}
363
Eli Friedman9a156e52008-11-12 09:44:48 +0000364//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000365// Pointer Evaluation
366//===----------------------------------------------------------------------===//
367
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000368namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000369class PointerExprEvaluator
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000370 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattnercdf34e72008-07-11 22:52:41 +0000371 EvalInfo &Info;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000372public:
Mike Stump11289f42009-09-09 15:08:12 +0000373
Chris Lattnercdf34e72008-07-11 22:52:41 +0000374 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000375
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000376 APValue VisitStmt(Stmt *S) {
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000377 return APValue();
378 }
379
380 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
381
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000382 APValue VisitBinaryOperator(const BinaryOperator *E);
Eli Friedman847a2bc2009-12-27 05:43:15 +0000383 APValue VisitCastExpr(CastExpr* E);
Eli Friedmanc2b50172009-02-22 11:46:18 +0000384 APValue VisitUnaryExtension(const UnaryOperator *E)
385 { return Visit(E->getSubExpr()); }
386 APValue VisitUnaryAddrOf(const UnaryOperator *E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000387 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
Ken Dyck02990832010-01-15 12:37:54 +0000388 { return APValue(E); }
Eli Friedman529a99b2009-01-25 01:21:06 +0000389 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
Ken Dyck02990832010-01-15 12:37:54 +0000390 { return APValue(E); }
Eli Friedmanc69d4542009-01-25 01:54:01 +0000391 APValue VisitCallExpr(CallExpr *E);
Mike Stumpa6703322009-02-19 22:01:56 +0000392 APValue VisitBlockExpr(BlockExpr *E) {
393 if (!E->hasBlockDeclRefExprs())
Ken Dyck02990832010-01-15 12:37:54 +0000394 return APValue(E);
Mike Stumpa6703322009-02-19 22:01:56 +0000395 return APValue();
396 }
Eli Friedman3ae59112009-02-23 04:23:56 +0000397 APValue VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
Ken Dyck02990832010-01-15 12:37:54 +0000398 { return APValue((Expr*)0); }
Eli Friedman9a156e52008-11-12 09:44:48 +0000399 APValue VisitConditionalOperator(ConditionalOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +0000400 APValue VisitChooseExpr(ChooseExpr *E)
Sebastian Redl576fd422009-05-10 18:38:11 +0000401 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
402 APValue VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
Ken Dyck02990832010-01-15 12:37:54 +0000403 { return APValue((Expr*)0); }
Eli Friedman449fe542009-03-23 04:56:01 +0000404 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000405};
Chris Lattner05706e882008-07-11 18:11:29 +0000406} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000407
Chris Lattnercdf34e72008-07-11 22:52:41 +0000408static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000409 assert(E->getType()->hasPointerRepresentation());
Chris Lattnercdf34e72008-07-11 22:52:41 +0000410 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattner05706e882008-07-11 18:11:29 +0000411 return Result.isLValue();
412}
413
414APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
415 if (E->getOpcode() != BinaryOperator::Add &&
416 E->getOpcode() != BinaryOperator::Sub)
417 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000418
Chris Lattner05706e882008-07-11 18:11:29 +0000419 const Expr *PExp = E->getLHS();
420 const Expr *IExp = E->getRHS();
421 if (IExp->getType()->isPointerType())
422 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattner05706e882008-07-11 18:11:29 +0000424 APValue ResultLValue;
Chris Lattnercdf34e72008-07-11 22:52:41 +0000425 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattner05706e882008-07-11 18:11:29 +0000426 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000427
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000428 llvm::APSInt AdditionalOffset;
Chris Lattnercdf34e72008-07-11 22:52:41 +0000429 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattner05706e882008-07-11 18:11:29 +0000430 return APValue();
431
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000432 // Compute the new offset in the appropriate width.
433
434 QualType PointeeType =
435 PExp->getType()->getAs<PointerType>()->getPointeeType();
436 llvm::APSInt SizeOfPointee(AdditionalOffset);
Mike Stump11289f42009-09-09 15:08:12 +0000437
Anders Carlssonef56fba2009-02-19 04:55:58 +0000438 // Explicitly handle GNU void* and function pointer arithmetic extensions.
439 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000440 SizeOfPointee = 1;
Anders Carlssonef56fba2009-02-19 04:55:58 +0000441 else
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000442 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType).getQuantity();
Eli Friedman9a156e52008-11-12 09:44:48 +0000443
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000444 llvm::APSInt Offset(AdditionalOffset);
445 Offset = ResultLValue.getLValueOffset().getQuantity();
Chris Lattner05706e882008-07-11 18:11:29 +0000446 if (E->getOpcode() == BinaryOperator::Add)
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000447 Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000448 else
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000449 Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000450
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000451 // Sign extend prior to converting back to a char unit.
452 if (Offset.getBitWidth() < 64)
453 Offset.extend(64);
454 return APValue(ResultLValue.getLValueBase(),
455 CharUnits::fromQuantity(Offset.getLimitedValue()));
Chris Lattner05706e882008-07-11 18:11:29 +0000456}
Eli Friedman9a156e52008-11-12 09:44:48 +0000457
Eli Friedmanc2b50172009-02-22 11:46:18 +0000458APValue PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
459 APValue result;
460 if (EvaluateLValue(E->getSubExpr(), result, Info))
461 return result;
Eli Friedman9a156e52008-11-12 09:44:48 +0000462 return APValue();
463}
Mike Stump11289f42009-09-09 15:08:12 +0000464
Chris Lattner05706e882008-07-11 18:11:29 +0000465
Eli Friedman847a2bc2009-12-27 05:43:15 +0000466APValue PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
467 Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000468
Eli Friedman847a2bc2009-12-27 05:43:15 +0000469 switch (E->getCastKind()) {
470 default:
471 break;
472
473 case CastExpr::CK_Unknown: {
474 // FIXME: The handling for CK_Unknown is ugly/shouldn't be necessary!
475
476 // Check for pointer->pointer cast
477 if (SubExpr->getType()->isPointerType() ||
478 SubExpr->getType()->isObjCObjectPointerType() ||
479 SubExpr->getType()->isNullPtrType() ||
480 SubExpr->getType()->isBlockPointerType())
481 return Visit(SubExpr);
482
483 if (SubExpr->getType()->isIntegralType()) {
484 APValue Result;
485 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
486 break;
487
488 if (Result.isInt()) {
489 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Ken Dyck02990832010-01-15 12:37:54 +0000490 return APValue(0,
491 CharUnits::fromQuantity(Result.getInt().getZExtValue()));
Eli Friedman847a2bc2009-12-27 05:43:15 +0000492 }
493
494 // Cast is of an lvalue, no need to change value.
Chris Lattner05706e882008-07-11 18:11:29 +0000495 return Result;
Eli Friedman847a2bc2009-12-27 05:43:15 +0000496 }
497 break;
Chris Lattner05706e882008-07-11 18:11:29 +0000498 }
Mike Stump11289f42009-09-09 15:08:12 +0000499
Eli Friedman847a2bc2009-12-27 05:43:15 +0000500 case CastExpr::CK_NoOp:
501 case CastExpr::CK_BitCast:
502 case CastExpr::CK_AnyPointerToObjCPointerCast:
503 case CastExpr::CK_AnyPointerToBlockPointerCast:
504 return Visit(SubExpr);
505
506 case CastExpr::CK_IntegralToPointer: {
Daniel Dunbarce399542009-02-20 18:22:23 +0000507 APValue Result;
508 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000509 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000510
511 if (Result.isInt()) {
512 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Ken Dyck02990832010-01-15 12:37:54 +0000513 return APValue(0,
514 CharUnits::fromQuantity(Result.getInt().getZExtValue()));
Chris Lattner05706e882008-07-11 18:11:29 +0000515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Daniel Dunbarce399542009-02-20 18:22:23 +0000517 // Cast is of an lvalue, no need to change value.
518 return Result;
Chris Lattner05706e882008-07-11 18:11:29 +0000519 }
Eli Friedman847a2bc2009-12-27 05:43:15 +0000520 case CastExpr::CK_ArrayToPointerDecay:
521 case CastExpr::CK_FunctionToPointerDecay: {
Eli Friedman9a156e52008-11-12 09:44:48 +0000522 APValue Result;
523 if (EvaluateLValue(SubExpr, Result, Info))
524 return Result;
Eli Friedman847a2bc2009-12-27 05:43:15 +0000525 break;
526 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000527 }
528
Chris Lattner05706e882008-07-11 18:11:29 +0000529 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000530}
Chris Lattner05706e882008-07-11 18:11:29 +0000531
Eli Friedmanc69d4542009-01-25 01:54:01 +0000532APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000533 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000534 Builtin::BI__builtin___CFStringMakeConstantString ||
535 E->isBuiltinCall(Info.Ctx) ==
536 Builtin::BI__builtin___NSStringMakeConstantString)
Ken Dyck02990832010-01-15 12:37:54 +0000537 return APValue(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000538 return APValue();
539}
540
Eli Friedman9a156e52008-11-12 09:44:48 +0000541APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
542 bool BoolResult;
543 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
544 return APValue();
545
546 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
547
548 APValue Result;
549 if (EvaluatePointer(EvalExpr, Result, Info))
550 return Result;
551 return APValue();
552}
Chris Lattner05706e882008-07-11 18:11:29 +0000553
554//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000555// Vector Evaluation
556//===----------------------------------------------------------------------===//
557
558namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000559 class VectorExprEvaluator
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000560 : public StmtVisitor<VectorExprEvaluator, APValue> {
561 EvalInfo &Info;
Eli Friedman3ae59112009-02-23 04:23:56 +0000562 APValue GetZeroVector(QualType VecType);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000563 public:
Mike Stump11289f42009-09-09 15:08:12 +0000564
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000565 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump11289f42009-09-09 15:08:12 +0000566
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000567 APValue VisitStmt(Stmt *S) {
568 return APValue();
569 }
Mike Stump11289f42009-09-09 15:08:12 +0000570
Eli Friedman3ae59112009-02-23 04:23:56 +0000571 APValue VisitParenExpr(ParenExpr *E)
572 { return Visit(E->getSubExpr()); }
573 APValue VisitUnaryExtension(const UnaryOperator *E)
574 { return Visit(E->getSubExpr()); }
575 APValue VisitUnaryPlus(const UnaryOperator *E)
576 { return Visit(E->getSubExpr()); }
577 APValue VisitUnaryReal(const UnaryOperator *E)
578 { return Visit(E->getSubExpr()); }
579 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
580 { return GetZeroVector(E->getType()); }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000581 APValue VisitCastExpr(const CastExpr* E);
582 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
583 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000584 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +0000585 APValue VisitChooseExpr(const ChooseExpr *E)
586 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman3ae59112009-02-23 04:23:56 +0000587 APValue VisitUnaryImag(const UnaryOperator *E);
588 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000589 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000590 // shufflevector, ExtVectorElementExpr
591 // (Note that these require implementing conversions
592 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000593 };
594} // end anonymous namespace
595
596static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
597 if (!E->getType()->isVectorType())
598 return false;
599 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
600 return !Result.isUninit();
601}
602
603APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall9dd450b2009-09-21 23:43:11 +0000604 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000605 QualType EltTy = VTy->getElementType();
606 unsigned NElts = VTy->getNumElements();
607 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000608
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000609 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000610 QualType SETy = SE->getType();
611 APValue Result = APValue();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000612
Nate Begeman2ffd3842009-06-26 18:22:18 +0000613 // Check for vector->vector bitcast and scalar->vector splat.
614 if (SETy->isVectorType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000615 return this->Visit(const_cast<Expr*>(SE));
Nate Begeman2ffd3842009-06-26 18:22:18 +0000616 } else if (SETy->isIntegerType()) {
617 APSInt IntResult;
Daniel Dunbardf4a58e2009-07-01 20:37:45 +0000618 if (!EvaluateInteger(SE, IntResult, Info))
619 return APValue();
620 Result = APValue(IntResult);
Nate Begeman2ffd3842009-06-26 18:22:18 +0000621 } else if (SETy->isRealFloatingType()) {
622 APFloat F(0.0);
Daniel Dunbardf4a58e2009-07-01 20:37:45 +0000623 if (!EvaluateFloat(SE, F, Info))
624 return APValue();
625 Result = APValue(F);
626 } else
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000627 return APValue();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000628
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000629 // For casts of a scalar to ExtVector, convert the scalar to the element type
630 // and splat it to all elements.
631 if (E->getType()->isExtVectorType()) {
632 if (EltTy->isIntegerType() && Result.isInt())
633 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
634 Info.Ctx));
635 else if (EltTy->isIntegerType())
636 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
637 Info.Ctx));
638 else if (EltTy->isRealFloatingType() && Result.isInt())
639 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
640 Info.Ctx));
641 else if (EltTy->isRealFloatingType())
642 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
643 Info.Ctx));
644 else
645 return APValue();
646
647 // Splat and create vector APValue.
648 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
649 return APValue(&Elts[0], Elts.size());
Nate Begeman2ffd3842009-06-26 18:22:18 +0000650 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000651
652 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
653 // to the vector. To construct the APValue vector initializer, bitcast the
654 // initializing value to an APInt, and shift out the bits pertaining to each
655 // element.
656 APSInt Init;
657 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump11289f42009-09-09 15:08:12 +0000658
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000659 llvm::SmallVector<APValue, 4> Elts;
660 for (unsigned i = 0; i != NElts; ++i) {
661 APSInt Tmp = Init;
662 Tmp.extOrTrunc(EltWidth);
Mike Stump11289f42009-09-09 15:08:12 +0000663
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000664 if (EltTy->isIntegerType())
665 Elts.push_back(APValue(Tmp));
666 else if (EltTy->isRealFloatingType())
667 Elts.push_back(APValue(APFloat(Tmp)));
668 else
669 return APValue();
670
671 Init >>= EltWidth;
672 }
673 return APValue(&Elts[0], Elts.size());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000674}
675
Mike Stump11289f42009-09-09 15:08:12 +0000676APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000677VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
678 return this->Visit(const_cast<Expr*>(E->getInitializer()));
679}
680
Mike Stump11289f42009-09-09 15:08:12 +0000681APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000682VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall9dd450b2009-09-21 23:43:11 +0000683 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000684 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000685 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000686
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000687 QualType EltTy = VT->getElementType();
688 llvm::SmallVector<APValue, 4> Elements;
689
Eli Friedman3ae59112009-02-23 04:23:56 +0000690 for (unsigned i = 0; i < NumElements; i++) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000691 if (EltTy->isIntegerType()) {
692 llvm::APSInt sInt(32);
Eli Friedman3ae59112009-02-23 04:23:56 +0000693 if (i < NumInits) {
694 if (!EvaluateInteger(E->getInit(i), sInt, Info))
695 return APValue();
696 } else {
697 sInt = Info.Ctx.MakeIntValue(0, EltTy);
698 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000699 Elements.push_back(APValue(sInt));
700 } else {
701 llvm::APFloat f(0.0);
Eli Friedman3ae59112009-02-23 04:23:56 +0000702 if (i < NumInits) {
703 if (!EvaluateFloat(E->getInit(i), f, Info))
704 return APValue();
705 } else {
706 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
707 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000708 Elements.push_back(APValue(f));
709 }
710 }
711 return APValue(&Elements[0], Elements.size());
712}
713
Mike Stump11289f42009-09-09 15:08:12 +0000714APValue
Eli Friedman3ae59112009-02-23 04:23:56 +0000715VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +0000716 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +0000717 QualType EltTy = VT->getElementType();
718 APValue ZeroElement;
719 if (EltTy->isIntegerType())
720 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
721 else
722 ZeroElement =
723 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
724
725 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
726 return APValue(&Elements[0], Elements.size());
727}
728
729APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
730 bool BoolResult;
731 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
732 return APValue();
733
734 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
735
736 APValue Result;
737 if (EvaluateVector(EvalExpr, Result, Info))
738 return Result;
739 return APValue();
740}
741
Eli Friedman3ae59112009-02-23 04:23:56 +0000742APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
743 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
744 Info.EvalResult.HasSideEffects = true;
745 return GetZeroVector(E->getType());
746}
747
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000748//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000749// Integer Evaluation
750//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000751
752namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000753class IntExprEvaluator
Chris Lattnere13042c2008-07-11 19:10:17 +0000754 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattnercdf34e72008-07-11 22:52:41 +0000755 EvalInfo &Info;
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000756 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000757public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000758 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattnercdf34e72008-07-11 22:52:41 +0000759 : Info(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000760
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000761 bool Success(const llvm::APSInt &SI, const Expr *E) {
Daniel Dunbar79e042a2009-02-21 18:14:20 +0000762 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000763 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000764 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000765 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000766 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000767 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000768 return true;
769 }
770
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000771 bool Success(const llvm::APInt &I, const Expr *E) {
Daniel Dunbar79e042a2009-02-21 18:14:20 +0000772 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000773 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000774 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000775 Result = APValue(APSInt(I));
776 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000777 return true;
778 }
779
780 bool Success(uint64_t Value, const Expr *E) {
Daniel Dunbar79e042a2009-02-21 18:14:20 +0000781 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000782 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000783 return true;
784 }
785
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000786 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000787 // Take the first error.
Anders Carlssonbd1df8e2008-11-30 16:38:33 +0000788 if (Info.EvalResult.Diag == 0) {
789 Info.EvalResult.DiagLoc = L;
790 Info.EvalResult.Diag = D;
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000791 Info.EvalResult.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000792 }
Chris Lattner99415702008-07-12 00:14:42 +0000793 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +0000794 }
Mike Stump11289f42009-09-09 15:08:12 +0000795
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000796 //===--------------------------------------------------------------------===//
797 // Visitor Methods
798 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000799
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000800 bool VisitStmt(Stmt *) {
801 assert(0 && "This should be called on integers, stmts are not integers");
802 return false;
803 }
Mike Stump11289f42009-09-09 15:08:12 +0000804
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000805 bool VisitExpr(Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +0000806 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000807 }
Mike Stump11289f42009-09-09 15:08:12 +0000808
Chris Lattnere13042c2008-07-11 19:10:17 +0000809 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000810
Chris Lattner7174bf32008-07-12 00:38:25 +0000811 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000812 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +0000813 }
814 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000815 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +0000816 }
817 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbard7be95d2008-10-24 08:07:57 +0000818 // Per gcc docs "this built-in function ignores top level
819 // qualifiers". We need to use the canonical version to properly
820 // be able to strip CRV qualifiers from the type.
821 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
822 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Mike Stump11289f42009-09-09 15:08:12 +0000823 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000824 T1.getUnqualifiedType()),
825 E);
Chris Lattner7174bf32008-07-12 00:38:25 +0000826 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +0000827
828 bool CheckReferencedDecl(const Expr *E, const Decl *D);
829 bool VisitDeclRefExpr(const DeclRefExpr *E) {
830 return CheckReferencedDecl(E, E->getDecl());
831 }
832 bool VisitMemberExpr(const MemberExpr *E) {
833 if (CheckReferencedDecl(E, E->getMemberDecl())) {
834 // Conservatively assume a MemberExpr will have side-effects
835 Info.EvalResult.HasSideEffects = true;
836 return true;
837 }
838 return false;
839 }
840
Eli Friedmand5c93992010-02-13 00:10:10 +0000841 bool VisitCallExpr(CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +0000842 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +0000843 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +0000844 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopes42042612008-11-16 19:28:31 +0000845 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +0000846
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000847 bool VisitCastExpr(CastExpr* E);
Sebastian Redl6f282892008-11-11 17:56:53 +0000848 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
849
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000850 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000851 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Anders Carlsson39def3a2008-12-21 22:39:40 +0000854 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000855 return Success(0, E);
Anders Carlsson39def3a2008-12-21 22:39:40 +0000856 }
Mike Stump11289f42009-09-09 15:08:12 +0000857
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000858 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000859 return Success(0, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000860 }
861
Eli Friedman4e7a2412009-02-27 04:45:43 +0000862 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
863 return Success(0, E);
864 }
865
Sebastian Redlbaad4e72009-01-05 20:52:13 +0000866 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Douglas Gregor79f83ed2009-07-23 23:49:00 +0000867 return Success(E->EvaluateTrait(Info.Ctx), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +0000868 }
869
Eli Friedman449fe542009-03-23 04:56:01 +0000870 bool VisitChooseExpr(const ChooseExpr *E) {
871 return Visit(E->getChosenSubExpr(Info.Ctx));
872 }
873
Eli Friedmana1c7b6c2009-02-28 03:59:05 +0000874 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +0000875 bool VisitUnaryImag(const UnaryOperator *E);
876
Chris Lattnerf8d7f722008-07-11 21:24:13 +0000877private:
Ken Dyck160146e2010-01-27 17:10:57 +0000878 CharUnits GetAlignOfExpr(const Expr *E);
879 CharUnits GetAlignOfType(QualType T);
Eli Friedman4e7a2412009-02-27 04:45:43 +0000880 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +0000881};
Chris Lattner05706e882008-07-11 18:11:29 +0000882} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000883
Daniel Dunbarce399542009-02-20 18:22:23 +0000884static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000885 assert(E->getType()->isIntegralType());
Daniel Dunbarce399542009-02-20 18:22:23 +0000886 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
887}
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000888
Daniel Dunbarce399542009-02-20 18:22:23 +0000889static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000890 assert(E->getType()->isIntegralType());
891
Daniel Dunbarce399542009-02-20 18:22:23 +0000892 APValue Val;
893 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
894 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000895 Result = Val.getInt();
896 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000897}
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000898
Eli Friedmanfb8a93f2009-11-24 05:28:59 +0000899bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +0000900 // Enums are integer constant exprs.
Eli Friedmanee275c82009-12-10 22:29:29 +0000901 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
902 return Success(ECD->getInitVal(), E);
Sebastian Redlc9ab3d42009-02-08 15:51:17 +0000903
904 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +0000905 // In C, they can also be folded, although they are not ICEs.
Douglas Gregor0840cc02009-11-01 20:32:48 +0000906 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
907 == Qualifiers::Const) {
Anders Carlssonb0695ef2010-02-03 21:58:41 +0000908
909 if (isa<ParmVarDecl>(D))
910 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
911
Eli Friedmanfb8a93f2009-11-24 05:28:59 +0000912 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000913 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedman1d6fb162009-12-03 20:31:57 +0000914 if (APValue *V = VD->getEvaluatedValue()) {
915 if (V->isInt())
916 return Success(V->getInt(), E);
917 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
918 }
919
920 if (VD->isEvaluatingValue())
921 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
922
923 VD->setEvaluatingValue();
924
Douglas Gregor31cf12c2009-05-26 18:54:04 +0000925 if (Visit(const_cast<Expr*>(Init))) {
926 // Cache the evaluated value in the variable declaration.
Eli Friedman1d6fb162009-12-03 20:31:57 +0000927 VD->setEvaluatedValue(Result);
Douglas Gregor31cf12c2009-05-26 18:54:04 +0000928 return true;
929 }
930
Eli Friedman1d6fb162009-12-03 20:31:57 +0000931 VD->setEvaluatedValue(APValue());
Douglas Gregor31cf12c2009-05-26 18:54:04 +0000932 return false;
933 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +0000934 }
935 }
936
Chris Lattner7174bf32008-07-12 00:38:25 +0000937 // Otherwise, random variable references are not constants.
Anders Carlssonb33d6c82008-11-30 18:37:00 +0000938 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner7174bf32008-07-12 00:38:25 +0000939}
940
Chris Lattner86ee2862008-10-06 06:40:35 +0000941/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
942/// as GCC.
943static int EvaluateBuiltinClassifyType(const CallExpr *E) {
944 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000945 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +0000946 enum gcc_type_class {
947 no_type_class = -1,
948 void_type_class, integer_type_class, char_type_class,
949 enumeral_type_class, boolean_type_class,
950 pointer_type_class, reference_type_class, offset_type_class,
951 real_type_class, complex_type_class,
952 function_type_class, method_type_class,
953 record_type_class, union_type_class,
954 array_type_class, string_type_class,
955 lang_type_class
956 };
Mike Stump11289f42009-09-09 15:08:12 +0000957
958 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +0000959 // ideal, however it is what gcc does.
960 if (E->getNumArgs() == 0)
961 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +0000962
Chris Lattner86ee2862008-10-06 06:40:35 +0000963 QualType ArgTy = E->getArg(0)->getType();
964 if (ArgTy->isVoidType())
965 return void_type_class;
966 else if (ArgTy->isEnumeralType())
967 return enumeral_type_class;
968 else if (ArgTy->isBooleanType())
969 return boolean_type_class;
970 else if (ArgTy->isCharType())
971 return string_type_class; // gcc doesn't appear to use char_type_class
972 else if (ArgTy->isIntegerType())
973 return integer_type_class;
974 else if (ArgTy->isPointerType())
975 return pointer_type_class;
976 else if (ArgTy->isReferenceType())
977 return reference_type_class;
978 else if (ArgTy->isRealType())
979 return real_type_class;
980 else if (ArgTy->isComplexType())
981 return complex_type_class;
982 else if (ArgTy->isFunctionType())
983 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +0000984 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +0000985 return record_type_class;
986 else if (ArgTy->isUnionType())
987 return union_type_class;
988 else if (ArgTy->isArrayType())
989 return array_type_class;
990 else if (ArgTy->isUnionType())
991 return union_type_class;
992 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
993 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
994 return -1;
995}
996
Eli Friedmand5c93992010-02-13 00:10:10 +0000997bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +0000998 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +0000999 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001000 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001001
1002 case Builtin::BI__builtin_object_size: {
Mike Stump722cedf2009-10-26 18:35:08 +00001003 const Expr *Arg = E->getArg(0)->IgnoreParens();
1004 Expr::EvalResult Base;
Eric Christopher99469702010-01-19 22:58:35 +00001005
1006 // TODO: Perhaps we should let LLVM lower this?
Mike Stump5183a142009-10-26 23:05:19 +00001007 if (Arg->EvaluateAsAny(Base, Info.Ctx)
Mike Stump722cedf2009-10-26 18:35:08 +00001008 && Base.Val.getKind() == APValue::LValue
1009 && !Base.HasSideEffects)
1010 if (const Expr *LVBase = Base.Val.getLValueBase())
1011 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVBase)) {
1012 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Mike Stump5179f302009-10-28 21:22:24 +00001013 if (!VD->getType()->isIncompleteType()
1014 && VD->getType()->isObjectType()
1015 && !VD->getType()->isVariablyModifiedType()
1016 && !VD->getType()->isDependentType()) {
Ken Dyck40775002010-01-11 17:06:35 +00001017 CharUnits Size = Info.Ctx.getTypeSizeInChars(VD->getType());
Ken Dyck02990832010-01-15 12:37:54 +00001018 CharUnits Offset = Base.Val.getLValueOffset();
Ken Dyck40775002010-01-11 17:06:35 +00001019 if (!Offset.isNegative() && Offset <= Size)
1020 Size -= Offset;
Mike Stump5179f302009-10-28 21:22:24 +00001021 else
Ken Dyck40775002010-01-11 17:06:35 +00001022 Size = CharUnits::Zero();
1023 return Success(Size.getQuantity(), E);
Mike Stump5179f302009-10-28 21:22:24 +00001024 }
Mike Stump722cedf2009-10-26 18:35:08 +00001025 }
1026 }
1027
Eric Christopher99469702010-01-19 22:58:35 +00001028 // If evaluating the argument has side-effects we can't determine
1029 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001030 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer0128f662010-01-03 18:18:37 +00001031 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001032 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001033 return Success(0, E);
1034 }
Mike Stump876387b2009-10-27 22:09:17 +00001035
Mike Stump722cedf2009-10-26 18:35:08 +00001036 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1037 }
1038
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001039 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001040 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001041
Anders Carlsson4c76e932008-11-24 04:21:33 +00001042 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001043 // __builtin_constant_p always has one operand: it returns true if that
1044 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001045 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001046
1047 case Builtin::BI__builtin_eh_return_data_regno: {
1048 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1049 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1050 return Success(Operand, E);
1051 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001052
1053 case Builtin::BI__builtin_expect:
1054 return Visit(E->getArg(0));
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001055 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001056}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001057
Chris Lattnere13042c2008-07-11 19:10:17 +00001058bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001059 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001060 if (!Visit(E->getRHS()))
1061 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001062
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001063 // If we can't evaluate the LHS, it might have side effects;
1064 // conservatively mark it.
1065 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1066 Info.EvalResult.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001067
Anders Carlsson564730a2008-12-01 02:07:06 +00001068 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001069 }
1070
1071 if (E->isLogicalOp()) {
1072 // These need to be handled specially because the operands aren't
1073 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001074 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001075
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001076 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001077 // We were able to evaluate the LHS, see if we can get away with not
1078 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001079 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001080 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001081
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001082 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001083 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001084 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001085 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001086 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001087 }
1088 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001089 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001090 // We can't evaluate the LHS; however, sometimes the result
1091 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Mike Stump11289f42009-09-09 15:08:12 +00001092 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001093 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001094 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001095 // must have had side effects.
1096 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001097
1098 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001099 }
1100 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001101 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001102
Eli Friedman5a332ea2008-11-13 06:09:17 +00001103 return false;
1104 }
1105
Anders Carlssonacc79812008-11-16 07:17:21 +00001106 QualType LHSTy = E->getLHS()->getType();
1107 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001108
1109 if (LHSTy->isAnyComplexType()) {
1110 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
1111 APValue LHS, RHS;
1112
1113 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1114 return false;
1115
1116 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1117 return false;
1118
1119 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001120 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001121 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001122 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001123 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1124
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001125 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001126 return Success((CR_r == APFloat::cmpEqual &&
1127 CR_i == APFloat::cmpEqual), E);
1128 else {
1129 assert(E->getOpcode() == BinaryOperator::NE &&
1130 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001131 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001132 CR_r == APFloat::cmpLessThan ||
1133 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001134 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001135 CR_i == APFloat::cmpLessThan ||
1136 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001137 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001138 } else {
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001139 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001140 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1141 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1142 else {
1143 assert(E->getOpcode() == BinaryOperator::NE &&
1144 "Invalid compex comparison.");
1145 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1146 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1147 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001148 }
1149 }
Mike Stump11289f42009-09-09 15:08:12 +00001150
Anders Carlssonacc79812008-11-16 07:17:21 +00001151 if (LHSTy->isRealFloatingType() &&
1152 RHSTy->isRealFloatingType()) {
1153 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001154
Anders Carlssonacc79812008-11-16 07:17:21 +00001155 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1156 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001157
Anders Carlssonacc79812008-11-16 07:17:21 +00001158 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1159 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001160
Anders Carlssonacc79812008-11-16 07:17:21 +00001161 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001162
Anders Carlssonacc79812008-11-16 07:17:21 +00001163 switch (E->getOpcode()) {
1164 default:
1165 assert(0 && "Invalid binary operator!");
1166 case BinaryOperator::LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001167 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001168 case BinaryOperator::GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001169 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001170 case BinaryOperator::LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001171 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001172 case BinaryOperator::GE:
Mike Stump11289f42009-09-09 15:08:12 +00001173 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001174 E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001175 case BinaryOperator::EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001176 return Success(CR == APFloat::cmpEqual, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001177 case BinaryOperator::NE:
Mike Stump11289f42009-09-09 15:08:12 +00001178 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001179 || CR == APFloat::cmpLessThan
1180 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001181 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001182 }
Mike Stump11289f42009-09-09 15:08:12 +00001183
Eli Friedmana38da572009-04-28 19:17:36 +00001184 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1185 if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001186 APValue LHSValue;
1187 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1188 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001189
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001190 APValue RHSValue;
1191 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1192 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001193
Eli Friedman334046a2009-06-14 02:17:33 +00001194 // Reject any bases from the normal codepath; we special-case comparisons
1195 // to null.
1196 if (LHSValue.getLValueBase()) {
1197 if (!E->isEqualityOp())
1198 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001199 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001200 return false;
1201 bool bres;
1202 if (!EvalPointerValueAsBool(LHSValue, bres))
1203 return false;
1204 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1205 } else if (RHSValue.getLValueBase()) {
1206 if (!E->isEqualityOp())
1207 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001208 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001209 return false;
1210 bool bres;
1211 if (!EvalPointerValueAsBool(RHSValue, bres))
1212 return false;
1213 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1214 }
Eli Friedman64004332009-03-23 04:38:34 +00001215
Eli Friedmana38da572009-04-28 19:17:36 +00001216 if (E->getOpcode() == BinaryOperator::Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001217 QualType Type = E->getLHS()->getType();
1218 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001219
Ken Dyck02990832010-01-15 12:37:54 +00001220 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001221 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001222 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001223
Ken Dyck02990832010-01-15 12:37:54 +00001224 CharUnits Diff = LHSValue.getLValueOffset() -
1225 RHSValue.getLValueOffset();
1226 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001227 }
1228 bool Result;
1229 if (E->getOpcode() == BinaryOperator::EQ) {
1230 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001231 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001232 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1233 }
1234 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001235 }
1236 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001237 if (!LHSTy->isIntegralType() ||
1238 !RHSTy->isIntegralType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001239 // We can't continue from here for non-integral types, and they
1240 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001241 return false;
1242 }
1243
Anders Carlsson9c181652008-07-08 14:35:21 +00001244 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001245 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001246 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001247
Eli Friedman94c25c62009-03-24 01:14:50 +00001248 APValue RHSVal;
1249 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001250 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001251
1252 // Handle cases like (unsigned long)&a + 4.
1253 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001254 CharUnits Offset = Result.getLValueOffset();
1255 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1256 RHSVal.getInt().getZExtValue());
Eli Friedman94c25c62009-03-24 01:14:50 +00001257 if (E->getOpcode() == BinaryOperator::Add)
Ken Dyck02990832010-01-15 12:37:54 +00001258 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001259 else
Ken Dyck02990832010-01-15 12:37:54 +00001260 Offset -= AdditionalOffset;
1261 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001262 return true;
1263 }
1264
1265 // Handle cases like 4 + (unsigned long)&a
1266 if (E->getOpcode() == BinaryOperator::Add &&
1267 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001268 CharUnits Offset = RHSVal.getLValueOffset();
1269 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1270 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001271 return true;
1272 }
1273
1274 // All the following cases expect both operands to be an integer
1275 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001276 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001277
Eli Friedman94c25c62009-03-24 01:14:50 +00001278 APSInt& RHS = RHSVal.getInt();
1279
Anders Carlsson9c181652008-07-08 14:35:21 +00001280 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001281 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001282 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001283 case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1284 case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1285 case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1286 case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1287 case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1288 case BinaryOperator::Or: return Success(Result.getInt() | RHS, E);
Chris Lattnerf09ad162008-07-11 22:15:16 +00001289 case BinaryOperator::Div:
Chris Lattner99415702008-07-12 00:14:42 +00001290 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001291 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001292 return Success(Result.getInt() / RHS, E);
Chris Lattnerf09ad162008-07-11 22:15:16 +00001293 case BinaryOperator::Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001294 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001295 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001296 return Success(Result.getInt() % RHS, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001297 case BinaryOperator::Shl: {
Chris Lattner99415702008-07-12 00:14:42 +00001298 // FIXME: Warn about out of range shift amounts!
Mike Stump11289f42009-09-09 15:08:12 +00001299 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001300 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1301 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001302 }
1303 case BinaryOperator::Shr: {
Mike Stump11289f42009-09-09 15:08:12 +00001304 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001305 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1306 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001307 }
Mike Stump11289f42009-09-09 15:08:12 +00001308
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001309 case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1310 case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1311 case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1312 case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1313 case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1314 case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001315 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001316}
1317
Nuno Lopes42042612008-11-16 19:28:31 +00001318bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes527b5a62008-11-16 22:06:39 +00001319 bool Cond;
1320 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopes42042612008-11-16 19:28:31 +00001321 return false;
1322
Nuno Lopes527b5a62008-11-16 22:06:39 +00001323 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopes42042612008-11-16 19:28:31 +00001324}
1325
Ken Dyck160146e2010-01-27 17:10:57 +00001326CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001327 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1328 // the result is the size of the referenced type."
1329 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1330 // result shall be the alignment of the referenced type."
1331 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1332 T = Ref->getPointeeType();
1333
Chris Lattner24aeeab2009-01-24 21:09:06 +00001334 // Get information about the alignment.
1335 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Douglas Gregoref462e62009-04-30 17:32:17 +00001336
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001337 // __alignof is defined to return the preferred alignment.
Ken Dyck160146e2010-01-27 17:10:57 +00001338 return CharUnits::fromQuantity(
1339 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001340}
1341
Ken Dyck160146e2010-01-27 17:10:57 +00001342CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001343 E = E->IgnoreParens();
1344
1345 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001346 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001347 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001348 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1349 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001350
Chris Lattner68061312009-01-24 21:53:27 +00001351 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001352 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1353 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001354
Chris Lattner24aeeab2009-01-24 21:09:06 +00001355 return GetAlignOfType(E->getType());
1356}
1357
1358
Sebastian Redl6f282892008-11-11 17:56:53 +00001359/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1360/// expression's type.
1361bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001362 // Handle alignof separately.
1363 if (!E->isSizeOf()) {
1364 if (E->isArgumentType())
Ken Dyck160146e2010-01-27 17:10:57 +00001365 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001366 else
Ken Dyck160146e2010-01-27 17:10:57 +00001367 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001368 }
Eli Friedman64004332009-03-23 04:38:34 +00001369
Sebastian Redl6f282892008-11-11 17:56:53 +00001370 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001371 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1372 // the result is the size of the referenced type."
1373 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1374 // result shall be the alignment of the referenced type."
1375 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1376 SrcTy = Ref->getPointeeType();
Sebastian Redl6f282892008-11-11 17:56:53 +00001377
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001378 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1379 // extension.
1380 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1381 return Success(1, E);
Eli Friedman64004332009-03-23 04:38:34 +00001382
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001383 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattner24aeeab2009-01-24 21:09:06 +00001384 if (!SrcTy->isConstantSizeType())
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001385 return false;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001386
Chris Lattner24aeeab2009-01-24 21:09:06 +00001387 // Get information about the size.
Ken Dyck40775002010-01-11 17:06:35 +00001388 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001389}
1390
Douglas Gregor882211c2010-04-28 22:16:22 +00001391bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1392 CharUnits Result;
1393 unsigned n = E->getNumComponents();
1394 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1395 if (n == 0)
1396 return false;
1397 QualType CurrentType = E->getTypeSourceInfo()->getType();
1398 for (unsigned i = 0; i != n; ++i) {
1399 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1400 switch (ON.getKind()) {
1401 case OffsetOfExpr::OffsetOfNode::Array: {
1402 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1403 APSInt IdxResult;
1404 if (!EvaluateInteger(Idx, IdxResult, Info))
1405 return false;
1406 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1407 if (!AT)
1408 return false;
1409 CurrentType = AT->getElementType();
1410 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1411 Result += IdxResult.getSExtValue() * ElementSize;
1412 break;
1413 }
1414
1415 case OffsetOfExpr::OffsetOfNode::Field: {
1416 FieldDecl *MemberDecl = ON.getField();
1417 const RecordType *RT = CurrentType->getAs<RecordType>();
1418 if (!RT)
1419 return false;
1420 RecordDecl *RD = RT->getDecl();
1421 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1422 unsigned i = 0;
1423 // FIXME: It would be nice if we didn't have to loop here!
1424 for (RecordDecl::field_iterator Field = RD->field_begin(),
1425 FieldEnd = RD->field_end();
1426 Field != FieldEnd; (void)++Field, ++i) {
1427 if (*Field == MemberDecl)
1428 break;
1429 }
Douglas Gregord1702062010-04-29 00:18:15 +00001430 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1431 Result += CharUnits::fromQuantity(
1432 RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
Douglas Gregor882211c2010-04-28 22:16:22 +00001433 CurrentType = MemberDecl->getType().getNonReferenceType();
1434 break;
1435 }
1436
1437 case OffsetOfExpr::OffsetOfNode::Identifier:
1438 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001439 return false;
1440
1441 case OffsetOfExpr::OffsetOfNode::Base: {
1442 CXXBaseSpecifier *BaseSpec = ON.getBase();
1443 if (BaseSpec->isVirtual())
1444 return false;
1445
1446 // Find the layout of the class whose base we are looking into.
1447 const RecordType *RT = CurrentType->getAs<RecordType>();
1448 if (!RT)
1449 return false;
1450 RecordDecl *RD = RT->getDecl();
1451 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1452
1453 // Find the base class itself.
1454 CurrentType = BaseSpec->getType();
1455 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1456 if (!BaseRT)
1457 return false;
1458
1459 // Add the offset to the base.
1460 Result += CharUnits::fromQuantity(
1461 RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()))
1462 / Info.Ctx.getCharWidth());
1463 break;
1464 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001465 }
1466 }
1467 return Success(Result.getQuantity(), E);
1468}
1469
Chris Lattnere13042c2008-07-11 19:10:17 +00001470bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001471 // Special case unary operators that do not need their subexpression
1472 // evaluated. offsetof/sizeof/alignof are all special.
Eli Friedman988a16b2009-02-27 06:44:11 +00001473 if (E->isOffsetOfOp()) {
1474 // The AST for offsetof is defined in such a way that we can just
1475 // directly Evaluate it as an l-value.
1476 APValue LV;
1477 if (!EvaluateLValue(E->getSubExpr(), LV, Info))
Douglas Gregor882211c2010-04-28 22:16:22 +00001478 return false;
Eli Friedman988a16b2009-02-27 06:44:11 +00001479 if (LV.getLValueBase())
Douglas Gregor882211c2010-04-28 22:16:22 +00001480 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001481 return Success(LV.getLValueOffset().getQuantity(), E);
Eli Friedman988a16b2009-02-27 06:44:11 +00001482 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001483
Eli Friedman5a332ea2008-11-13 06:09:17 +00001484 if (E->getOpcode() == UnaryOperator::LNot) {
1485 // LNot's operand isn't necessarily an integer, so we handle it specially.
1486 bool bres;
1487 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1488 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001489 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001490 }
1491
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001492 // Only handle integral operations...
1493 if (!E->getSubExpr()->getType()->isIntegralType())
1494 return false;
1495
Chris Lattnercdf34e72008-07-11 22:52:41 +00001496 // Get the operand value into 'Result'.
1497 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001498 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001499
Chris Lattnerf09ad162008-07-11 22:15:16 +00001500 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001501 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001502 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1503 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001504 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerf09ad162008-07-11 22:15:16 +00001505 case UnaryOperator::Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001506 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1507 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001508 return true;
Chris Lattnerf09ad162008-07-11 22:15:16 +00001509 case UnaryOperator::Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001510 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001511 return true;
Chris Lattnerf09ad162008-07-11 22:15:16 +00001512 case UnaryOperator::Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001513 if (!Result.isInt()) return false;
1514 return Success(-Result.getInt(), E);
Chris Lattnerf09ad162008-07-11 22:15:16 +00001515 case UnaryOperator::Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001516 if (!Result.isInt()) return false;
1517 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001518 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001519}
Mike Stump11289f42009-09-09 15:08:12 +00001520
Chris Lattner477c4be2008-07-12 01:15:53 +00001521/// HandleCast - This is used to evaluate implicit or explicit casts where the
1522/// result type is integer.
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001523bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001524 Expr *SubExpr = E->getSubExpr();
1525 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001526 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001527
Eli Friedman9a156e52008-11-12 09:44:48 +00001528 if (DestType->isBooleanType()) {
1529 bool BoolResult;
1530 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1531 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001532 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001533 }
1534
Anders Carlsson9c181652008-07-08 14:35:21 +00001535 // Handle simple integer->integer casts.
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001536 if (SrcType->isIntegralType()) {
Chris Lattner477c4be2008-07-12 01:15:53 +00001537 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001538 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001539
Eli Friedman742421e2009-02-20 01:15:07 +00001540 if (!Result.isInt()) {
1541 // Only allow casts of lvalues if they are lossless.
1542 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1543 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001544
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001545 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001546 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001547 }
Mike Stump11289f42009-09-09 15:08:12 +00001548
Chris Lattner477c4be2008-07-12 01:15:53 +00001549 // FIXME: Clean this up!
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001550 if (SrcType->isPointerType()) {
Anders Carlsson9c181652008-07-08 14:35:21 +00001551 APValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001552 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001553 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001554
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001555 if (LV.getLValueBase()) {
1556 // Only allow based lvalue casts if they are lossless.
1557 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1558 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001559
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001560 Result = LV;
1561 return true;
1562 }
1563
Ken Dyck02990832010-01-15 12:37:54 +00001564 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1565 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001566 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001567 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001568
Eli Friedman742421e2009-02-20 01:15:07 +00001569 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1570 // This handles double-conversion cases, where there's both
1571 // an l-value promotion and an implicit conversion to int.
1572 APValue LV;
1573 if (!EvaluateLValue(SubExpr, LV, Info))
1574 return false;
1575
1576 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1577 return false;
1578
1579 Result = LV;
1580 return true;
1581 }
1582
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001583 if (SrcType->isAnyComplexType()) {
1584 APValue C;
1585 if (!EvaluateComplex(SubExpr, C, Info))
1586 return false;
1587 if (C.isComplexFloat())
1588 return Success(HandleFloatToIntCast(DestType, SrcType,
1589 C.getComplexFloatReal(), Info.Ctx),
1590 E);
1591 else
1592 return Success(HandleIntToIntCast(DestType, SrcType,
1593 C.getComplexIntReal(), Info.Ctx), E);
1594 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001595 // FIXME: Handle vectors
1596
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001597 if (!SrcType->isRealFloatingType())
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001598 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001599
Eli Friedman24c01542008-08-22 00:06:13 +00001600 APFloat F(0.0);
1601 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001602 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump11289f42009-09-09 15:08:12 +00001603
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001604 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001605}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001606
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001607bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1608 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1609 APValue LV;
1610 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1611 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1612 return Success(LV.getComplexIntReal(), E);
1613 }
1614
1615 return Visit(E->getSubExpr());
1616}
1617
Eli Friedman4e7a2412009-02-27 04:45:43 +00001618bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001619 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
1620 APValue LV;
1621 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1622 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1623 return Success(LV.getComplexIntImag(), E);
1624 }
1625
Eli Friedman4e7a2412009-02-27 04:45:43 +00001626 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1627 Info.EvalResult.HasSideEffects = true;
1628 return Success(0, E);
1629}
1630
Chris Lattner05706e882008-07-11 18:11:29 +00001631//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00001632// Float Evaluation
1633//===----------------------------------------------------------------------===//
1634
1635namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001636class FloatExprEvaluator
Eli Friedman24c01542008-08-22 00:06:13 +00001637 : public StmtVisitor<FloatExprEvaluator, bool> {
1638 EvalInfo &Info;
1639 APFloat &Result;
1640public:
1641 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1642 : Info(info), Result(result) {}
1643
1644 bool VisitStmt(Stmt *S) {
1645 return false;
1646 }
1647
1648 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001649 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001650
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001651 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001652 bool VisitBinaryOperator(const BinaryOperator *E);
1653 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001654 bool VisitCastExpr(CastExpr *E);
1655 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmanf3da3342009-12-04 02:12:53 +00001656 bool VisitConditionalOperator(ConditionalOperator *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00001657
Eli Friedman449fe542009-03-23 04:56:01 +00001658 bool VisitChooseExpr(const ChooseExpr *E)
1659 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1660 bool VisitUnaryExtension(const UnaryOperator *E)
1661 { return Visit(E->getSubExpr()); }
1662
1663 // FIXME: Missing: __real__/__imag__, array subscript of vector,
Eli Friedmanf3da3342009-12-04 02:12:53 +00001664 // member of vector, ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00001665};
1666} // end anonymous namespace
1667
1668static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00001669 assert(E->getType()->isRealFloatingType());
Eli Friedman24c01542008-08-22 00:06:13 +00001670 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1671}
1672
John McCall16291492010-02-28 13:00:19 +00001673static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1674 QualType ResultTy,
1675 const Expr *Arg,
1676 bool SNaN,
1677 llvm::APFloat &Result) {
1678 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1679 if (!S) return false;
1680
1681 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1682
1683 llvm::APInt fill;
1684
1685 // Treat empty strings as if they were zero.
1686 if (S->getString().empty())
1687 fill = llvm::APInt(32, 0);
1688 else if (S->getString().getAsInteger(0, fill))
1689 return false;
1690
1691 if (SNaN)
1692 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1693 else
1694 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1695 return true;
1696}
1697
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001698bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001699 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner37346e02008-10-06 05:53:16 +00001700 default: return false;
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001701 case Builtin::BI__builtin_huge_val:
1702 case Builtin::BI__builtin_huge_valf:
1703 case Builtin::BI__builtin_huge_vall:
1704 case Builtin::BI__builtin_inf:
1705 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00001706 case Builtin::BI__builtin_infl: {
1707 const llvm::fltSemantics &Sem =
1708 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00001709 Result = llvm::APFloat::getInf(Sem);
1710 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00001711 }
Mike Stump11289f42009-09-09 15:08:12 +00001712
John McCall16291492010-02-28 13:00:19 +00001713 case Builtin::BI__builtin_nans:
1714 case Builtin::BI__builtin_nansf:
1715 case Builtin::BI__builtin_nansl:
1716 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1717 true, Result);
1718
Chris Lattner0b7282e2008-10-06 06:31:58 +00001719 case Builtin::BI__builtin_nan:
1720 case Builtin::BI__builtin_nanf:
1721 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00001722 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00001723 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00001724 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1725 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001726
1727 case Builtin::BI__builtin_fabs:
1728 case Builtin::BI__builtin_fabsf:
1729 case Builtin::BI__builtin_fabsl:
1730 if (!EvaluateFloat(E->getArg(0), Result, Info))
1731 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001732
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001733 if (Result.isNegative())
1734 Result.changeSign();
1735 return true;
1736
Mike Stump11289f42009-09-09 15:08:12 +00001737 case Builtin::BI__builtin_copysign:
1738 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001739 case Builtin::BI__builtin_copysignl: {
1740 APFloat RHS(0.);
1741 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1742 !EvaluateFloat(E->getArg(1), RHS, Info))
1743 return false;
1744 Result.copySign(RHS);
1745 return true;
1746 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001747 }
1748}
1749
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001750bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes0e33c682008-11-19 17:44:31 +00001751 if (E->getOpcode() == UnaryOperator::Deref)
1752 return false;
1753
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001754 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1755 return false;
1756
1757 switch (E->getOpcode()) {
1758 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00001759 case UnaryOperator::Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001760 return true;
1761 case UnaryOperator::Minus:
1762 Result.changeSign();
1763 return true;
1764 }
1765}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001766
Eli Friedman24c01542008-08-22 00:06:13 +00001767bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman141fbf32009-11-16 04:25:37 +00001768 if (E->getOpcode() == BinaryOperator::Comma) {
1769 if (!EvaluateFloat(E->getRHS(), Result, Info))
1770 return false;
1771
1772 // If we can't evaluate the LHS, it might have side effects;
1773 // conservatively mark it.
1774 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1775 Info.EvalResult.HasSideEffects = true;
1776
1777 return true;
1778 }
1779
Eli Friedman24c01542008-08-22 00:06:13 +00001780 // FIXME: Diagnostics? I really don't understand how the warnings
1781 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001782 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00001783 if (!EvaluateFloat(E->getLHS(), Result, Info))
1784 return false;
1785 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1786 return false;
1787
1788 switch (E->getOpcode()) {
1789 default: return false;
1790 case BinaryOperator::Mul:
1791 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1792 return true;
1793 case BinaryOperator::Add:
1794 Result.add(RHS, APFloat::rmNearestTiesToEven);
1795 return true;
1796 case BinaryOperator::Sub:
1797 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1798 return true;
1799 case BinaryOperator::Div:
1800 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1801 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00001802 }
1803}
1804
1805bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1806 Result = E->getValue();
1807 return true;
1808}
1809
Eli Friedman9a156e52008-11-12 09:44:48 +00001810bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1811 Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001812
Eli Friedman9a156e52008-11-12 09:44:48 +00001813 if (SubExpr->getType()->isIntegralType()) {
1814 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001815 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00001816 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001817 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001818 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00001819 return true;
1820 }
1821 if (SubExpr->getType()->isRealFloatingType()) {
1822 if (!Visit(SubExpr))
1823 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001824 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1825 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00001826 return true;
1827 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001828 // FIXME: Handle complex types
Eli Friedman9a156e52008-11-12 09:44:48 +00001829
1830 return false;
1831}
1832
1833bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1834 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1835 return true;
1836}
1837
Eli Friedmanf3da3342009-12-04 02:12:53 +00001838bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
1839 bool Cond;
1840 if (!HandleConversionToBool(E->getCond(), Cond, Info))
1841 return false;
1842
1843 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1844}
1845
Eli Friedman24c01542008-08-22 00:06:13 +00001846//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001847// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00001848//===----------------------------------------------------------------------===//
1849
1850namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001851class ComplexExprEvaluator
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001852 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlsson537969c2008-11-16 20:27:53 +00001853 EvalInfo &Info;
Mike Stump11289f42009-09-09 15:08:12 +00001854
Anders Carlsson537969c2008-11-16 20:27:53 +00001855public:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001856 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump11289f42009-09-09 15:08:12 +00001857
Anders Carlsson537969c2008-11-16 20:27:53 +00001858 //===--------------------------------------------------------------------===//
1859 // Visitor Methods
1860 //===--------------------------------------------------------------------===//
1861
1862 APValue VisitStmt(Stmt *S) {
Anders Carlsson537969c2008-11-16 20:27:53 +00001863 return APValue();
1864 }
Mike Stump11289f42009-09-09 15:08:12 +00001865
Anders Carlsson537969c2008-11-16 20:27:53 +00001866 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1867
1868 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001869 Expr* SubExpr = E->getSubExpr();
1870
1871 if (SubExpr->getType()->isRealFloatingType()) {
1872 APFloat Result(0.0);
1873
1874 if (!EvaluateFloat(SubExpr, Result, Info))
1875 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +00001876
1877 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001878 Result);
1879 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001880 assert(SubExpr->getType()->isIntegerType() &&
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001881 "Unexpected imaginary literal.");
1882
1883 llvm::APSInt Result;
1884 if (!EvaluateInteger(SubExpr, Result, Info))
1885 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +00001886
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001887 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1888 Zero = 0;
1889 return APValue(Zero, Result);
1890 }
Anders Carlsson537969c2008-11-16 20:27:53 +00001891 }
1892
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001893 APValue VisitCastExpr(CastExpr *E) {
1894 Expr* SubExpr = E->getSubExpr();
John McCall9dd450b2009-09-21 23:43:11 +00001895 QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001896 QualType SubType = SubExpr->getType();
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001897
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001898 if (SubType->isRealFloatingType()) {
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001899 APFloat Result(0.0);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001900
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001901 if (!EvaluateFloat(SubExpr, Result, Info))
1902 return APValue();
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001903
1904 if (EltType->isRealFloatingType()) {
1905 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001906 return APValue(Result,
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001907 APFloat(Result.getSemantics(), APFloat::fcZero, false));
1908 } else {
1909 llvm::APSInt IResult;
1910 IResult = HandleFloatToIntCast(EltType, SubType, Result, Info.Ctx);
1911 llvm::APSInt Zero(IResult.getBitWidth(), !IResult.isSigned());
1912 Zero = 0;
1913 return APValue(IResult, Zero);
1914 }
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001915 } else if (SubType->isIntegerType()) {
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001916 APSInt Result;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001917
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001918 if (!EvaluateInteger(SubExpr, Result, Info))
1919 return APValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001920
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001921 if (EltType->isRealFloatingType()) {
1922 APFloat FResult =
1923 HandleIntToFloatCast(EltType, SubType, Result, Info.Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001924 return APValue(FResult,
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001925 APFloat(FResult.getSemantics(), APFloat::fcZero, false));
1926 } else {
1927 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
1928 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1929 Zero = 0;
1930 return APValue(Result, Zero);
1931 }
John McCall9dd450b2009-09-21 23:43:11 +00001932 } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001933 APValue Src;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001934
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001935 if (!EvaluateComplex(SubExpr, Src, Info))
1936 return APValue();
1937
1938 QualType SrcType = CT->getElementType();
1939
1940 if (Src.isComplexFloat()) {
1941 if (EltType->isRealFloatingType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001942 return APValue(HandleFloatToFloatCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001943 Src.getComplexFloatReal(),
1944 Info.Ctx),
Mike Stump11289f42009-09-09 15:08:12 +00001945 HandleFloatToFloatCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001946 Src.getComplexFloatImag(),
1947 Info.Ctx));
1948 } else {
1949 return APValue(HandleFloatToIntCast(EltType, SrcType,
1950 Src.getComplexFloatReal(),
1951 Info.Ctx),
Mike Stump11289f42009-09-09 15:08:12 +00001952 HandleFloatToIntCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001953 Src.getComplexFloatImag(),
Mike Stump11289f42009-09-09 15:08:12 +00001954 Info.Ctx));
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001955 }
1956 } else {
1957 assert(Src.isComplexInt() && "Invalid evaluate result.");
1958 if (EltType->isRealFloatingType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001959 return APValue(HandleIntToFloatCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001960 Src.getComplexIntReal(),
1961 Info.Ctx),
Mike Stump11289f42009-09-09 15:08:12 +00001962 HandleIntToFloatCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001963 Src.getComplexIntImag(),
1964 Info.Ctx));
1965 } else {
1966 return APValue(HandleIntToIntCast(EltType, SrcType,
1967 Src.getComplexIntReal(),
1968 Info.Ctx),
Mike Stump11289f42009-09-09 15:08:12 +00001969 HandleIntToIntCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001970 Src.getComplexIntImag(),
Mike Stump11289f42009-09-09 15:08:12 +00001971 Info.Ctx));
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001972 }
1973 }
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001974 }
1975
1976 // FIXME: Handle more casts.
1977 return APValue();
1978 }
Mike Stump11289f42009-09-09 15:08:12 +00001979
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001980 APValue VisitBinaryOperator(const BinaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00001981 APValue VisitChooseExpr(const ChooseExpr *E)
1982 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1983 APValue VisitUnaryExtension(const UnaryOperator *E)
1984 { return Visit(E->getSubExpr()); }
1985 // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001986 // conditional ?:, comma
Anders Carlsson537969c2008-11-16 20:27:53 +00001987};
1988} // end anonymous namespace
1989
Mike Stump11289f42009-09-09 15:08:12 +00001990static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00001991 assert(E->getType()->isAnyComplexType());
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001992 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1993 assert((!Result.isComplexFloat() ||
Mike Stump11289f42009-09-09 15:08:12 +00001994 (&Result.getComplexFloatReal().getSemantics() ==
1995 &Result.getComplexFloatImag().getSemantics())) &&
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001996 "Invalid complex evaluation.");
1997 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlsson537969c2008-11-16 20:27:53 +00001998}
1999
Mike Stump11289f42009-09-09 15:08:12 +00002000APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002001 APValue Result, RHS;
Mike Stump11289f42009-09-09 15:08:12 +00002002
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002003 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002004 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +00002005
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002006 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002007 return APValue();
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002008
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002009 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2010 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002011 switch (E->getOpcode()) {
2012 default: return APValue();
2013 case BinaryOperator::Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002014 if (Result.isComplexFloat()) {
2015 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2016 APFloat::rmNearestTiesToEven);
2017 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2018 APFloat::rmNearestTiesToEven);
2019 } else {
2020 Result.getComplexIntReal() += RHS.getComplexIntReal();
2021 Result.getComplexIntImag() += RHS.getComplexIntImag();
2022 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002023 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002024 case BinaryOperator::Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002025 if (Result.isComplexFloat()) {
2026 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2027 APFloat::rmNearestTiesToEven);
2028 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2029 APFloat::rmNearestTiesToEven);
2030 } else {
2031 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2032 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2033 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002034 break;
2035 case BinaryOperator::Mul:
2036 if (Result.isComplexFloat()) {
2037 APValue LHS = Result;
2038 APFloat &LHS_r = LHS.getComplexFloatReal();
2039 APFloat &LHS_i = LHS.getComplexFloatImag();
2040 APFloat &RHS_r = RHS.getComplexFloatReal();
2041 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002042
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002043 APFloat Tmp = LHS_r;
2044 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2045 Result.getComplexFloatReal() = Tmp;
2046 Tmp = LHS_i;
2047 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2048 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2049
2050 Tmp = LHS_r;
2051 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2052 Result.getComplexFloatImag() = Tmp;
2053 Tmp = LHS_i;
2054 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2055 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2056 } else {
2057 APValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002058 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002059 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2060 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002061 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002062 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2063 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2064 }
2065 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002066 }
2067
2068 return Result;
2069}
2070
Anders Carlsson537969c2008-11-16 20:27:53 +00002071//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002072// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002073//===----------------------------------------------------------------------===//
2074
Chris Lattner67d7b922008-11-16 21:24:15 +00002075/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002076/// any crazy technique (that has nothing to do with language standards) that
2077/// we want to. If this function returns true, it returns the folded constant
2078/// in Result.
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002079bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2080 EvalInfo Info(Ctx, Result);
Anders Carlssonbd1df8e2008-11-30 16:38:33 +00002081
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002082 if (getType()->isVectorType()) {
2083 if (!EvaluateVector(this, Result.Val, Info))
2084 return false;
2085 } else if (getType()->isIntegerType()) {
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002086 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002087 return false;
Daniel Dunbar76ba41c2009-02-26 20:52:22 +00002088 } else if (getType()->hasPointerRepresentation()) {
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002089 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002090 return false;
Eli Friedman24c01542008-08-22 00:06:13 +00002091 } else if (getType()->isRealFloatingType()) {
2092 llvm::APFloat f(0.0);
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002093 if (!EvaluateFloat(this, f, Info))
2094 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002095
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002096 Result.Val = APValue(f);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002097 } else if (getType()->isAnyComplexType()) {
2098 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002099 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002100 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002101 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002102
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002103 return true;
2104}
2105
Mike Stump5183a142009-10-26 23:05:19 +00002106bool Expr::EvaluateAsAny(EvalResult &Result, ASTContext &Ctx) const {
2107 EvalInfo Info(Ctx, Result, true);
2108
2109 if (getType()->isVectorType()) {
2110 if (!EvaluateVector(this, Result.Val, Info))
2111 return false;
2112 } else if (getType()->isIntegerType()) {
2113 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
2114 return false;
2115 } else if (getType()->hasPointerRepresentation()) {
2116 if (!EvaluatePointer(this, Result.Val, Info))
2117 return false;
2118 } else if (getType()->isRealFloatingType()) {
2119 llvm::APFloat f(0.0);
2120 if (!EvaluateFloat(this, f, Info))
2121 return false;
2122
2123 Result.Val = APValue(f);
2124 } else if (getType()->isAnyComplexType()) {
2125 if (!EvaluateComplex(this, Result.Val, Info))
2126 return false;
2127 } else
2128 return false;
2129
2130 return true;
2131}
2132
John McCall1be1c632010-01-05 23:42:56 +00002133bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2134 EvalResult Scratch;
2135 EvalInfo Info(Ctx, Scratch);
2136
2137 return HandleConversionToBool(this, Result, Info);
2138}
2139
Anders Carlsson43168122009-04-10 04:54:13 +00002140bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2141 EvalInfo Info(Ctx, Result);
2142
2143 return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
2144}
2145
Eli Friedman7d45c482009-09-13 10:17:44 +00002146bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2147 EvalInfo Info(Ctx, Result, true);
2148
2149 return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
2150}
2151
Chris Lattner67d7b922008-11-16 21:24:15 +00002152/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002153/// folded, but discard the result.
2154bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002155 EvalResult Result;
2156 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002157}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002158
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002159bool Expr::HasSideEffects(ASTContext &Ctx) const {
2160 Expr::EvalResult Result;
2161 EvalInfo Info(Ctx, Result);
2162 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2163}
2164
Anders Carlsson59689ed2008-11-22 21:04:56 +00002165APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002166 EvalResult EvalResult;
2167 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbar435bbe02009-01-15 18:32:35 +00002168 Result = Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002169 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002170 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002171
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002172 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002173}
John McCall864e3962010-05-07 05:32:02 +00002174
2175/// isIntegerConstantExpr - this recursive routine will test if an expression is
2176/// an integer constant expression.
2177
2178/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2179/// comma, etc
2180///
2181/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2182/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2183/// cast+dereference.
2184
2185// CheckICE - This function does the fundamental ICE checking: the returned
2186// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2187// Note that to reduce code duplication, this helper does no evaluation
2188// itself; the caller checks whether the expression is evaluatable, and
2189// in the rare cases where CheckICE actually cares about the evaluated
2190// value, it calls into Evalute.
2191//
2192// Meanings of Val:
2193// 0: This expression is an ICE if it can be evaluated by Evaluate.
2194// 1: This expression is not an ICE, but if it isn't evaluated, it's
2195// a legal subexpression for an ICE. This return value is used to handle
2196// the comma operator in C99 mode.
2197// 2: This expression is not an ICE, and is not a legal subexpression for one.
2198
2199struct ICEDiag {
2200 unsigned Val;
2201 SourceLocation Loc;
2202
2203 public:
2204 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2205 ICEDiag() : Val(0) {}
2206};
2207
2208ICEDiag NoDiag() { return ICEDiag(); }
2209
2210static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2211 Expr::EvalResult EVResult;
2212 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2213 !EVResult.Val.isInt()) {
2214 return ICEDiag(2, E->getLocStart());
2215 }
2216 return NoDiag();
2217}
2218
2219static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2220 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
2221 if (!E->getType()->isIntegralType()) {
2222 return ICEDiag(2, E->getLocStart());
2223 }
2224
2225 switch (E->getStmtClass()) {
2226#define STMT(Node, Base) case Expr::Node##Class:
2227#define EXPR(Node, Base)
2228#include "clang/AST/StmtNodes.inc"
2229 case Expr::PredefinedExprClass:
2230 case Expr::FloatingLiteralClass:
2231 case Expr::ImaginaryLiteralClass:
2232 case Expr::StringLiteralClass:
2233 case Expr::ArraySubscriptExprClass:
2234 case Expr::MemberExprClass:
2235 case Expr::CompoundAssignOperatorClass:
2236 case Expr::CompoundLiteralExprClass:
2237 case Expr::ExtVectorElementExprClass:
2238 case Expr::InitListExprClass:
2239 case Expr::DesignatedInitExprClass:
2240 case Expr::ImplicitValueInitExprClass:
2241 case Expr::ParenListExprClass:
2242 case Expr::VAArgExprClass:
2243 case Expr::AddrLabelExprClass:
2244 case Expr::StmtExprClass:
2245 case Expr::CXXMemberCallExprClass:
2246 case Expr::CXXDynamicCastExprClass:
2247 case Expr::CXXTypeidExprClass:
2248 case Expr::CXXNullPtrLiteralExprClass:
2249 case Expr::CXXThisExprClass:
2250 case Expr::CXXThrowExprClass:
2251 case Expr::CXXNewExprClass:
2252 case Expr::CXXDeleteExprClass:
2253 case Expr::CXXPseudoDestructorExprClass:
2254 case Expr::UnresolvedLookupExprClass:
2255 case Expr::DependentScopeDeclRefExprClass:
2256 case Expr::CXXConstructExprClass:
2257 case Expr::CXXBindTemporaryExprClass:
2258 case Expr::CXXBindReferenceExprClass:
2259 case Expr::CXXExprWithTemporariesClass:
2260 case Expr::CXXTemporaryObjectExprClass:
2261 case Expr::CXXUnresolvedConstructExprClass:
2262 case Expr::CXXDependentScopeMemberExprClass:
2263 case Expr::UnresolvedMemberExprClass:
2264 case Expr::ObjCStringLiteralClass:
2265 case Expr::ObjCEncodeExprClass:
2266 case Expr::ObjCMessageExprClass:
2267 case Expr::ObjCSelectorExprClass:
2268 case Expr::ObjCProtocolExprClass:
2269 case Expr::ObjCIvarRefExprClass:
2270 case Expr::ObjCPropertyRefExprClass:
2271 case Expr::ObjCImplicitSetterGetterRefExprClass:
2272 case Expr::ObjCSuperExprClass:
2273 case Expr::ObjCIsaExprClass:
2274 case Expr::ShuffleVectorExprClass:
2275 case Expr::BlockExprClass:
2276 case Expr::BlockDeclRefExprClass:
2277 case Expr::NoStmtClass:
2278 return ICEDiag(2, E->getLocStart());
2279
2280 case Expr::GNUNullExprClass:
2281 // GCC considers the GNU __null value to be an integral constant expression.
2282 return NoDiag();
2283
2284 case Expr::ParenExprClass:
2285 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2286 case Expr::IntegerLiteralClass:
2287 case Expr::CharacterLiteralClass:
2288 case Expr::CXXBoolLiteralExprClass:
2289 case Expr::CXXZeroInitValueExprClass:
2290 case Expr::TypesCompatibleExprClass:
2291 case Expr::UnaryTypeTraitExprClass:
2292 return NoDiag();
2293 case Expr::CallExprClass:
2294 case Expr::CXXOperatorCallExprClass: {
2295 const CallExpr *CE = cast<CallExpr>(E);
2296 if (CE->isBuiltinCall(Ctx))
2297 return CheckEvalInICE(E, Ctx);
2298 return ICEDiag(2, E->getLocStart());
2299 }
2300 case Expr::DeclRefExprClass:
2301 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2302 return NoDiag();
2303 if (Ctx.getLangOptions().CPlusPlus &&
2304 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2305 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2306
2307 // Parameter variables are never constants. Without this check,
2308 // getAnyInitializer() can find a default argument, which leads
2309 // to chaos.
2310 if (isa<ParmVarDecl>(D))
2311 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2312
2313 // C++ 7.1.5.1p2
2314 // A variable of non-volatile const-qualified integral or enumeration
2315 // type initialized by an ICE can be used in ICEs.
2316 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2317 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2318 if (Quals.hasVolatile() || !Quals.hasConst())
2319 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2320
2321 // Look for a declaration of this variable that has an initializer.
2322 const VarDecl *ID = 0;
2323 const Expr *Init = Dcl->getAnyInitializer(ID);
2324 if (Init) {
2325 if (ID->isInitKnownICE()) {
2326 // We have already checked whether this subexpression is an
2327 // integral constant expression.
2328 if (ID->isInitICE())
2329 return NoDiag();
2330 else
2331 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2332 }
2333
2334 // It's an ICE whether or not the definition we found is
2335 // out-of-line. See DR 721 and the discussion in Clang PR
2336 // 6206 for details.
2337
2338 if (Dcl->isCheckingICE()) {
2339 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2340 }
2341
2342 Dcl->setCheckingICE();
2343 ICEDiag Result = CheckICE(Init, Ctx);
2344 // Cache the result of the ICE test.
2345 Dcl->setInitKnownICE(Result.Val == 0);
2346 return Result;
2347 }
2348 }
2349 }
2350 return ICEDiag(2, E->getLocStart());
2351 case Expr::UnaryOperatorClass: {
2352 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2353 switch (Exp->getOpcode()) {
2354 case UnaryOperator::PostInc:
2355 case UnaryOperator::PostDec:
2356 case UnaryOperator::PreInc:
2357 case UnaryOperator::PreDec:
2358 case UnaryOperator::AddrOf:
2359 case UnaryOperator::Deref:
2360 return ICEDiag(2, E->getLocStart());
2361 case UnaryOperator::Extension:
2362 case UnaryOperator::LNot:
2363 case UnaryOperator::Plus:
2364 case UnaryOperator::Minus:
2365 case UnaryOperator::Not:
2366 case UnaryOperator::Real:
2367 case UnaryOperator::Imag:
2368 return CheckICE(Exp->getSubExpr(), Ctx);
2369 case UnaryOperator::OffsetOf:
2370 break;
2371 }
2372
2373 // OffsetOf falls through here.
2374 }
2375 case Expr::OffsetOfExprClass: {
2376 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2377 // Evaluate matches the proposed gcc behavior for cases like
2378 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2379 // compliance: we should warn earlier for offsetof expressions with
2380 // array subscripts that aren't ICEs, and if the array subscripts
2381 // are ICEs, the value of the offsetof must be an integer constant.
2382 return CheckEvalInICE(E, Ctx);
2383 }
2384 case Expr::SizeOfAlignOfExprClass: {
2385 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2386 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2387 return ICEDiag(2, E->getLocStart());
2388 return NoDiag();
2389 }
2390 case Expr::BinaryOperatorClass: {
2391 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2392 switch (Exp->getOpcode()) {
2393 case BinaryOperator::PtrMemD:
2394 case BinaryOperator::PtrMemI:
2395 case BinaryOperator::Assign:
2396 case BinaryOperator::MulAssign:
2397 case BinaryOperator::DivAssign:
2398 case BinaryOperator::RemAssign:
2399 case BinaryOperator::AddAssign:
2400 case BinaryOperator::SubAssign:
2401 case BinaryOperator::ShlAssign:
2402 case BinaryOperator::ShrAssign:
2403 case BinaryOperator::AndAssign:
2404 case BinaryOperator::XorAssign:
2405 case BinaryOperator::OrAssign:
2406 return ICEDiag(2, E->getLocStart());
2407
2408 case BinaryOperator::Mul:
2409 case BinaryOperator::Div:
2410 case BinaryOperator::Rem:
2411 case BinaryOperator::Add:
2412 case BinaryOperator::Sub:
2413 case BinaryOperator::Shl:
2414 case BinaryOperator::Shr:
2415 case BinaryOperator::LT:
2416 case BinaryOperator::GT:
2417 case BinaryOperator::LE:
2418 case BinaryOperator::GE:
2419 case BinaryOperator::EQ:
2420 case BinaryOperator::NE:
2421 case BinaryOperator::And:
2422 case BinaryOperator::Xor:
2423 case BinaryOperator::Or:
2424 case BinaryOperator::Comma: {
2425 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2426 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2427 if (Exp->getOpcode() == BinaryOperator::Div ||
2428 Exp->getOpcode() == BinaryOperator::Rem) {
2429 // Evaluate gives an error for undefined Div/Rem, so make sure
2430 // we don't evaluate one.
2431 if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2432 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2433 if (REval == 0)
2434 return ICEDiag(1, E->getLocStart());
2435 if (REval.isSigned() && REval.isAllOnesValue()) {
2436 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2437 if (LEval.isMinSignedValue())
2438 return ICEDiag(1, E->getLocStart());
2439 }
2440 }
2441 }
2442 if (Exp->getOpcode() == BinaryOperator::Comma) {
2443 if (Ctx.getLangOptions().C99) {
2444 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2445 // if it isn't evaluated.
2446 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2447 return ICEDiag(1, E->getLocStart());
2448 } else {
2449 // In both C89 and C++, commas in ICEs are illegal.
2450 return ICEDiag(2, E->getLocStart());
2451 }
2452 }
2453 if (LHSResult.Val >= RHSResult.Val)
2454 return LHSResult;
2455 return RHSResult;
2456 }
2457 case BinaryOperator::LAnd:
2458 case BinaryOperator::LOr: {
2459 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2460 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2461 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2462 // Rare case where the RHS has a comma "side-effect"; we need
2463 // to actually check the condition to see whether the side
2464 // with the comma is evaluated.
2465 if ((Exp->getOpcode() == BinaryOperator::LAnd) !=
2466 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2467 return RHSResult;
2468 return NoDiag();
2469 }
2470
2471 if (LHSResult.Val >= RHSResult.Val)
2472 return LHSResult;
2473 return RHSResult;
2474 }
2475 }
2476 }
2477 case Expr::ImplicitCastExprClass:
2478 case Expr::CStyleCastExprClass:
2479 case Expr::CXXFunctionalCastExprClass:
2480 case Expr::CXXStaticCastExprClass:
2481 case Expr::CXXReinterpretCastExprClass:
2482 case Expr::CXXConstCastExprClass: {
2483 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
2484 if (SubExpr->getType()->isIntegralType())
2485 return CheckICE(SubExpr, Ctx);
2486 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2487 return NoDiag();
2488 return ICEDiag(2, E->getLocStart());
2489 }
2490 case Expr::ConditionalOperatorClass: {
2491 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2492 // If the condition (ignoring parens) is a __builtin_constant_p call,
2493 // then only the true side is actually considered in an integer constant
2494 // expression, and it is fully evaluated. This is an important GNU
2495 // extension. See GCC PR38377 for discussion.
2496 if (const CallExpr *CallCE
2497 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2498 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2499 Expr::EvalResult EVResult;
2500 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2501 !EVResult.Val.isInt()) {
2502 return ICEDiag(2, E->getLocStart());
2503 }
2504 return NoDiag();
2505 }
2506 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2507 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2508 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2509 if (CondResult.Val == 2)
2510 return CondResult;
2511 if (TrueResult.Val == 2)
2512 return TrueResult;
2513 if (FalseResult.Val == 2)
2514 return FalseResult;
2515 if (CondResult.Val == 1)
2516 return CondResult;
2517 if (TrueResult.Val == 0 && FalseResult.Val == 0)
2518 return NoDiag();
2519 // Rare case where the diagnostics depend on which side is evaluated
2520 // Note that if we get here, CondResult is 0, and at least one of
2521 // TrueResult and FalseResult is non-zero.
2522 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2523 return FalseResult;
2524 }
2525 return TrueResult;
2526 }
2527 case Expr::CXXDefaultArgExprClass:
2528 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2529 case Expr::ChooseExprClass: {
2530 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2531 }
2532 }
2533
2534 // Silence a GCC warning
2535 return ICEDiag(2, E->getLocStart());
2536}
2537
2538bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2539 SourceLocation *Loc, bool isEvaluated) const {
2540 ICEDiag d = CheckICE(this, Ctx);
2541 if (d.Val != 0) {
2542 if (Loc) *Loc = d.Loc;
2543 return false;
2544 }
2545 EvalResult EvalResult;
2546 if (!Evaluate(EvalResult, Ctx))
2547 llvm_unreachable("ICE cannot be evaluated!");
2548 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2549 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2550 Result = EvalResult.Val.getInt();
2551 return true;
2552}