blob: 6cdbc80afa7ab67f784d0b149e384985e5ed3682 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Eli Friedman4efaa272008-11-12 09:44:48 +000016#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner54176fd2008-07-12 00:14:42 +000018#include "clang/Basic/Diagnostic.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssonc754aa62008-07-08 05:13:58 +000020#include "llvm/Support/Compiler.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000021using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000022using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000023using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000024
Chris Lattner87eae5e2008-07-11 22:52:41 +000025/// EvalInfo - This is a private struct used by the evaluator to capture
26/// information about a subexpression as it is folded. It retains information
27/// about the AST context, but also maintains information about the folded
28/// expression.
29///
30/// If an expression could be evaluated, it is still possible it is not a C
31/// "integer constant expression" or constant expression. If not, this struct
32/// captures information about how and why not.
33///
34/// One bit of information passed *into* the request for constant folding
35/// indicates whether the subexpression is "evaluated" or not according to C
36/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
37/// evaluate the expression regardless of what the RHS is, but C only allows
38/// certain things in certain situations.
39struct EvalInfo {
40 ASTContext &Ctx;
41
42 /// isEvaluated - True if the subexpression is required to be evaluated, false
43 /// if it is short-circuited (according to C rules).
44 bool isEvaluated;
45
Chris Lattner54176fd2008-07-12 00:14:42 +000046 /// ICEDiag - If the expression is unfoldable, then ICEDiag contains the
47 /// error diagnostic indicating why it is not foldable and DiagLoc indicates a
48 /// caret position for the error. If it is foldable, but the expression is
49 /// not an integer constant expression, ICEDiag contains the extension
50 /// diagnostic to emit which describes why it isn't an integer constant
51 /// expression. If this expression *is* an integer-constant-expr, then
52 /// ICEDiag is zero.
Chris Lattner87eae5e2008-07-11 22:52:41 +000053 ///
Chris Lattner54176fd2008-07-12 00:14:42 +000054 /// The caller can choose to emit this diagnostic or not, depending on whether
55 /// they require an i-c-e or a constant or not. DiagLoc indicates the caret
56 /// position for the report.
57 ///
58 /// If ICEDiag is zero, then this expression is an i-c-e.
Chris Lattner87eae5e2008-07-11 22:52:41 +000059 unsigned ICEDiag;
60 SourceLocation DiagLoc;
61
62 EvalInfo(ASTContext &ctx) : Ctx(ctx), isEvaluated(true), ICEDiag(0) {}
63};
64
65
Eli Friedman4efaa272008-11-12 09:44:48 +000066static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +000067static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
68static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000069static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +000070static bool EvaluateComplexFloat(const Expr *E, APValue &Result,
71 EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +000072
73//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +000074// Misc utilities
75//===----------------------------------------------------------------------===//
76
77static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
78 if (E->getType()->isIntegralType()) {
79 APSInt IntResult;
80 if (!EvaluateInteger(E, IntResult, Info))
81 return false;
82 Result = IntResult != 0;
83 return true;
84 } else if (E->getType()->isRealFloatingType()) {
85 APFloat FloatResult(0.0);
86 if (!EvaluateFloat(E, FloatResult, Info))
87 return false;
88 Result = !FloatResult.isZero();
89 return true;
90 } else if (E->getType()->isPointerType()) {
91 APValue PointerResult;
92 if (!EvaluatePointer(E, PointerResult, Info))
93 return false;
94 // FIXME: Is this accurate for all kinds of bases? If not, what would
95 // the check look like?
96 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
97 return true;
98 }
99
100 return false;
101}
102
103//===----------------------------------------------------------------------===//
104// LValue Evaluation
105//===----------------------------------------------------------------------===//
106namespace {
107class VISIBILITY_HIDDEN LValueExprEvaluator
108 : public StmtVisitor<LValueExprEvaluator, APValue> {
109 EvalInfo &Info;
110public:
111
112 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
113
114 APValue VisitStmt(Stmt *S) {
Daniel Dunbar8a7b7c62008-11-12 21:52:46 +0000115#if 0
Eli Friedman4efaa272008-11-12 09:44:48 +0000116 // FIXME: Remove this when we support more expressions.
117 printf("Unhandled pointer statement\n");
118 S->dump();
Daniel Dunbar8a7b7c62008-11-12 21:52:46 +0000119#endif
Eli Friedman4efaa272008-11-12 09:44:48 +0000120 return APValue();
121 }
122
123 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson35873c42008-11-24 04:41:22 +0000124 APValue VisitDeclRefExpr(DeclRefExpr *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000125 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
126 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
127 APValue VisitMemberExpr(MemberExpr *E);
128 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
Anders Carlsson3068d112008-11-16 19:01:22 +0000129 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000130};
131} // end anonymous namespace
132
133static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
134 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
135 return Result.isLValue();
136}
137
Anders Carlsson35873c42008-11-24 04:41:22 +0000138APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
139{
140 if (!E->hasGlobalStorage())
141 return APValue();
142
143 return APValue(E, 0);
144}
145
Eli Friedman4efaa272008-11-12 09:44:48 +0000146APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
147 if (E->isFileScope())
148 return APValue(E, 0);
149 return APValue();
150}
151
152APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
153 APValue result;
154 QualType Ty;
155 if (E->isArrow()) {
156 if (!EvaluatePointer(E->getBase(), result, Info))
157 return APValue();
158 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
159 } else {
160 result = Visit(E->getBase());
161 if (result.isUninit())
162 return APValue();
163 Ty = E->getBase()->getType();
164 }
165
166 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
167 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
168 FieldDecl *FD = E->getMemberDecl();
169
170 // FIXME: This is linear time.
171 unsigned i = 0, e = 0;
172 for (i = 0, e = RD->getNumMembers(); i != e; i++) {
173 if (RD->getMember(i) == FD)
174 break;
175 }
176
177 result.setLValue(result.getLValueBase(),
178 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
179
180 return result;
181}
182
Anders Carlsson3068d112008-11-16 19:01:22 +0000183APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
184{
185 APValue Result;
186
187 if (!EvaluatePointer(E->getBase(), Result, Info))
188 return APValue();
189
190 APSInt Index;
191 if (!EvaluateInteger(E->getIdx(), Index, Info))
192 return APValue();
193
194 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
195
196 uint64_t Offset = Index.getSExtValue() * ElementSize;
197 Result.setLValue(Result.getLValueBase(),
198 Result.getLValueOffset() + Offset);
199 return Result;
200}
Eli Friedman4efaa272008-11-12 09:44:48 +0000201
202//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000203// Pointer Evaluation
204//===----------------------------------------------------------------------===//
205
Anders Carlssonc754aa62008-07-08 05:13:58 +0000206namespace {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000207class VISIBILITY_HIDDEN PointerExprEvaluator
208 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000209 EvalInfo &Info;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000210public:
Anders Carlsson2bad1682008-07-08 14:30:00 +0000211
Chris Lattner87eae5e2008-07-11 22:52:41 +0000212 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000213
Anders Carlsson2bad1682008-07-08 14:30:00 +0000214 APValue VisitStmt(Stmt *S) {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000215 return APValue();
216 }
217
218 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
219
Anders Carlsson650c92f2008-07-08 15:34:11 +0000220 APValue VisitBinaryOperator(const BinaryOperator *E);
221 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000222 APValue VisitUnaryOperator(const UnaryOperator *E);
223 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
224 { return APValue(E, 0); }
225 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlsson650c92f2008-07-08 15:34:11 +0000226};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000227} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000228
Chris Lattner87eae5e2008-07-11 22:52:41 +0000229static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000230 if (!E->getType()->isPointerType())
231 return false;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000232 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000233 return Result.isLValue();
234}
235
236APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
237 if (E->getOpcode() != BinaryOperator::Add &&
238 E->getOpcode() != BinaryOperator::Sub)
239 return APValue();
240
241 const Expr *PExp = E->getLHS();
242 const Expr *IExp = E->getRHS();
243 if (IExp->getType()->isPointerType())
244 std::swap(PExp, IExp);
245
246 APValue ResultLValue;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000247 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000248 return APValue();
249
250 llvm::APSInt AdditionalOffset(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000251 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000252 return APValue();
253
Eli Friedman4efaa272008-11-12 09:44:48 +0000254 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
255 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
256
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000257 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman4efaa272008-11-12 09:44:48 +0000258
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000259 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman4efaa272008-11-12 09:44:48 +0000260 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000261 else
Eli Friedman4efaa272008-11-12 09:44:48 +0000262 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
263
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000264 return APValue(ResultLValue.getLValueBase(), Offset);
265}
Eli Friedman4efaa272008-11-12 09:44:48 +0000266
267APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
268 if (E->getOpcode() == UnaryOperator::Extension) {
269 // FIXME: Deal with warnings?
270 return Visit(E->getSubExpr());
271 }
272
273 if (E->getOpcode() == UnaryOperator::AddrOf) {
274 APValue result;
275 if (EvaluateLValue(E->getSubExpr(), result, Info))
276 return result;
277 }
278
279 return APValue();
280}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000281
282
Chris Lattnerb542afe2008-07-11 19:10:17 +0000283APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000284 const Expr* SubExpr = E->getSubExpr();
285
286 // Check for pointer->pointer cast
287 if (SubExpr->getType()->isPointerType()) {
288 APValue Result;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000289 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000290 return Result;
291 return APValue();
292 }
293
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000294 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000295 llvm::APSInt Result(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000296 if (EvaluateInteger(SubExpr, Result, Info)) {
297 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000298 return APValue(0, Result.getZExtValue());
299 }
300 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000301
302 if (SubExpr->getType()->isFunctionType() ||
303 SubExpr->getType()->isArrayType()) {
304 APValue Result;
305 if (EvaluateLValue(SubExpr, Result, Info))
306 return Result;
307 return APValue();
308 }
309
310 //assert(0 && "Unhandled cast");
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000311 return APValue();
312}
313
Eli Friedman4efaa272008-11-12 09:44:48 +0000314APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
315 bool BoolResult;
316 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
317 return APValue();
318
319 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
320
321 APValue Result;
322 if (EvaluatePointer(EvalExpr, Result, Info))
323 return Result;
324 return APValue();
325}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000326
327//===----------------------------------------------------------------------===//
328// Integer Evaluation
329//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000330
331namespace {
Anders Carlssonc754aa62008-07-08 05:13:58 +0000332class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000333 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000334 EvalInfo &Info;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000335 APSInt &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000336public:
Chris Lattner87eae5e2008-07-11 22:52:41 +0000337 IntExprEvaluator(EvalInfo &info, APSInt &result)
338 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000339
Chris Lattner7a767782008-07-11 19:24:49 +0000340 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner54176fd2008-07-12 00:14:42 +0000341 return (unsigned)Info.Ctx.getIntWidth(T);
342 }
343
344 bool Extension(SourceLocation L, diag::kind D) {
345 Info.DiagLoc = L;
346 Info.ICEDiag = D;
347 return true; // still a constant.
348 }
349
Chris Lattner32fea9d2008-11-12 07:43:42 +0000350 bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000351 // If this is in an unevaluated portion of the subexpression, ignore the
352 // error.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000353 if (!Info.isEvaluated) {
354 // If error is ignored because the value isn't evaluated, get the real
355 // type at least to prevent errors downstream.
356 Result.zextOrTrunc(getIntTypeSizeInBits(ExprTy));
357 Result.setIsUnsigned(ExprTy->isUnsignedIntegerType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000358 return true;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000359 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000360
Chris Lattner32fea9d2008-11-12 07:43:42 +0000361 // Take the first error.
362 if (Info.ICEDiag == 0) {
363 Info.DiagLoc = L;
364 Info.ICEDiag = D;
365 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000366 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000367 }
368
Anders Carlssonc754aa62008-07-08 05:13:58 +0000369 //===--------------------------------------------------------------------===//
370 // Visitor Methods
371 //===--------------------------------------------------------------------===//
Chris Lattner32fea9d2008-11-12 07:43:42 +0000372
373 bool VisitStmt(Stmt *) {
374 assert(0 && "This should be called on integers, stmts are not integers");
375 return false;
376 }
Chris Lattner7a767782008-07-11 19:24:49 +0000377
Chris Lattner32fea9d2008-11-12 07:43:42 +0000378 bool VisitExpr(Expr *E) {
379 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Anders Carlssonc754aa62008-07-08 05:13:58 +0000380 }
381
Chris Lattnerb542afe2008-07-11 19:10:17 +0000382 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000383
Chris Lattner4c4867e2008-07-12 00:38:25 +0000384 bool VisitIntegerLiteral(const IntegerLiteral *E) {
385 Result = E->getValue();
386 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
387 return true;
388 }
389 bool VisitCharacterLiteral(const CharacterLiteral *E) {
390 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
391 Result = E->getValue();
392 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
393 return true;
394 }
395 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
396 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarac620de2008-10-24 08:07:57 +0000397 // Per gcc docs "this built-in function ignores top level
398 // qualifiers". We need to use the canonical version to properly
399 // be able to strip CRV qualifiers from the type.
400 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
401 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
402 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
403 T1.getUnqualifiedType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000404 return true;
405 }
406 bool VisitDeclRefExpr(const DeclRefExpr *E);
407 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000408 bool VisitBinaryOperator(const BinaryOperator *E);
409 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000410 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000411
Chris Lattner732b2232008-07-12 01:15:53 +0000412 bool VisitCastExpr(CastExpr* E) {
Chris Lattner732b2232008-07-12 01:15:53 +0000413 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlsson650c92f2008-07-08 15:34:11 +0000414 }
Sebastian Redl05189992008-11-11 17:56:53 +0000415 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
416
Anders Carlsson3068d112008-11-16 19:01:22 +0000417 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Anders Carlsson529569e2008-11-16 22:46:56 +0000418 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson3068d112008-11-16 19:01:22 +0000419 Result = E->getValue();
420 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
421 return true;
422 }
423
424 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
425 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
426 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
427 return true;
428 }
429
Chris Lattnerfcee0012008-07-11 21:24:13 +0000430private:
Chris Lattner732b2232008-07-12 01:15:53 +0000431 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000432};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000433} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000434
Chris Lattner87eae5e2008-07-11 22:52:41 +0000435static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
436 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson650c92f2008-07-08 15:34:11 +0000437}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000438
Chris Lattner4c4867e2008-07-12 00:38:25 +0000439bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
440 // Enums are integer constant exprs.
441 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
442 Result = D->getInitVal();
443 return true;
444 }
445
446 // Otherwise, random variable references are not constants.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000447 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000448}
449
Chris Lattnera4d55d82008-10-06 06:40:35 +0000450/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
451/// as GCC.
452static int EvaluateBuiltinClassifyType(const CallExpr *E) {
453 // The following enum mimics the values returned by GCC.
454 enum gcc_type_class {
455 no_type_class = -1,
456 void_type_class, integer_type_class, char_type_class,
457 enumeral_type_class, boolean_type_class,
458 pointer_type_class, reference_type_class, offset_type_class,
459 real_type_class, complex_type_class,
460 function_type_class, method_type_class,
461 record_type_class, union_type_class,
462 array_type_class, string_type_class,
463 lang_type_class
464 };
465
466 // If no argument was supplied, default to "no_type_class". This isn't
467 // ideal, however it is what gcc does.
468 if (E->getNumArgs() == 0)
469 return no_type_class;
470
471 QualType ArgTy = E->getArg(0)->getType();
472 if (ArgTy->isVoidType())
473 return void_type_class;
474 else if (ArgTy->isEnumeralType())
475 return enumeral_type_class;
476 else if (ArgTy->isBooleanType())
477 return boolean_type_class;
478 else if (ArgTy->isCharType())
479 return string_type_class; // gcc doesn't appear to use char_type_class
480 else if (ArgTy->isIntegerType())
481 return integer_type_class;
482 else if (ArgTy->isPointerType())
483 return pointer_type_class;
484 else if (ArgTy->isReferenceType())
485 return reference_type_class;
486 else if (ArgTy->isRealType())
487 return real_type_class;
488 else if (ArgTy->isComplexType())
489 return complex_type_class;
490 else if (ArgTy->isFunctionType())
491 return function_type_class;
492 else if (ArgTy->isStructureType())
493 return record_type_class;
494 else if (ArgTy->isUnionType())
495 return union_type_class;
496 else if (ArgTy->isArrayType())
497 return array_type_class;
498 else if (ArgTy->isUnionType())
499 return union_type_class;
500 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
501 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
502 return -1;
503}
504
Chris Lattner4c4867e2008-07-12 00:38:25 +0000505bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
506 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner4c4867e2008-07-12 00:38:25 +0000507
Chris Lattner019f4e82008-10-06 05:28:25 +0000508 switch (E->isBuiltinCall()) {
509 default:
Chris Lattner32fea9d2008-11-12 07:43:42 +0000510 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner019f4e82008-10-06 05:28:25 +0000511 case Builtin::BI__builtin_classify_type:
Chris Lattnera4d55d82008-10-06 06:40:35 +0000512 Result.setIsSigned(true);
513 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000514 return true;
515
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000516 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +0000517 // __builtin_constant_p always has one operand: it returns true if that
518 // operand can be folded, false otherwise.
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000519 Result = E->getArg(0)->isEvaluatable(Info.Ctx);
Chris Lattner019f4e82008-10-06 05:28:25 +0000520 return true;
521 }
Chris Lattner4c4867e2008-07-12 00:38:25 +0000522}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000523
Chris Lattnerb542afe2008-07-11 19:10:17 +0000524bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000525 if (E->getOpcode() == BinaryOperator::Comma) {
526 // Evaluate the side that actually matters; this needs to be
527 // handled specially because calling Visit() on the LHS can
528 // have strange results when it doesn't have an integral type.
Nuno Lopesf9ef0c62008-11-16 20:09:07 +0000529 if (Visit(E->getRHS()))
530 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +0000531
532 // Check for isEvaluated; the idea is that this might eventually
533 // be useful for isICE and other similar uses that care about
534 // whether a comma is evaluated. This isn't really used yet, though,
535 // and I'm not sure it really works as intended.
536 if (!Info.isEvaluated)
Nuno Lopesf9ef0c62008-11-16 20:09:07 +0000537 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
Eli Friedmana6afa762008-11-13 06:09:17 +0000538
Nuno Lopesf9ef0c62008-11-16 20:09:07 +0000539 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000540 }
541
542 if (E->isLogicalOp()) {
543 // These need to be handled specially because the operands aren't
544 // necessarily integral
545 bool bres;
Anders Carlsson51fe9962008-11-22 21:04:56 +0000546
547 if (HandleConversionToBool(E->getLHS(), bres, Info)) {
548 // We were able to evaluate the LHS, see if we can get away with not
549 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000550 if (bres == (E->getOpcode() == BinaryOperator::LOr) ||
551 !bres == (E->getOpcode() == BinaryOperator::LAnd)) {
552 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
553 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
554 Result = bres;
555
556 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +0000557 }
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000558
559 bool bres2;
560 if (HandleConversionToBool(E->getRHS(), bres2, Info)) {
561 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
562 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
563 if (E->getOpcode() == BinaryOperator::LOr)
564 Result = bres || bres2;
565 else
566 Result = bres && bres2;
567 return true;
568 }
569 } else {
570 if (HandleConversionToBool(E->getRHS(), bres, Info)) {
571 // We can't evaluate the LHS; however, sometimes the result
572 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
573 if (bres == (E->getOpcode() == BinaryOperator::LOr) ||
574 !bres == (E->getOpcode() == BinaryOperator::LAnd)) {
575 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
576 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
577 Result = bres;
578 Info.isEvaluated = false;
579
580 return true;
581 }
582 }
Anders Carlsson51fe9962008-11-22 21:04:56 +0000583 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000584
Eli Friedmana6afa762008-11-13 06:09:17 +0000585 return false;
586 }
587
Anders Carlsson286f85e2008-11-16 07:17:21 +0000588 QualType LHSTy = E->getLHS()->getType();
589 QualType RHSTy = E->getRHS()->getType();
590
591 if (LHSTy->isRealFloatingType() &&
592 RHSTy->isRealFloatingType()) {
593 APFloat RHS(0.0), LHS(0.0);
594
595 if (!EvaluateFloat(E->getRHS(), RHS, Info))
596 return false;
597
598 if (!EvaluateFloat(E->getLHS(), LHS, Info))
599 return false;
600
601 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +0000602
603 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
604
Anders Carlsson286f85e2008-11-16 07:17:21 +0000605 switch (E->getOpcode()) {
606 default:
607 assert(0 && "Invalid binary operator!");
608 case BinaryOperator::LT:
609 Result = CR == APFloat::cmpLessThan;
610 break;
611 case BinaryOperator::GT:
612 Result = CR == APFloat::cmpGreaterThan;
613 break;
614 case BinaryOperator::LE:
615 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
616 break;
617 case BinaryOperator::GE:
618 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
619 break;
620 case BinaryOperator::EQ:
621 Result = CR == APFloat::cmpEqual;
622 break;
623 case BinaryOperator::NE:
624 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
625 break;
626 }
627
Anders Carlsson286f85e2008-11-16 07:17:21 +0000628 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
629 return true;
630 }
631
Anders Carlsson3068d112008-11-16 19:01:22 +0000632 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson529569e2008-11-16 22:46:56 +0000633 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000634 APValue LHSValue;
635 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
636 return false;
637
638 APValue RHSValue;
639 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
640 return false;
641
642 // FIXME: Is this correct? What if only one of the operands has a base?
643 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
644 return false;
645
646 const QualType Type = E->getLHS()->getType();
647 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
648
649 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
650 D /= Info.Ctx.getTypeSize(ElementType) / 8;
651
Anders Carlsson3068d112008-11-16 19:01:22 +0000652 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson529569e2008-11-16 22:46:56 +0000653 Result = D;
Anders Carlsson3068d112008-11-16 19:01:22 +0000654 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
655
656 return true;
657 }
658 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000659 if (!LHSTy->isIntegralType() ||
660 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000661 // We can't continue from here for non-integral types, and they
662 // could potentially confuse the following operations.
663 // FIXME: Deal with EQ and friends.
664 return false;
665 }
666
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000667 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000668 llvm::APSInt RHS(32);
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000669 if (!Visit(E->getLHS())) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000670 return false; // error in subexpression.
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000671 }
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000672
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000673
674 // FIXME Maybe we want to succeed even where we can't evaluate the
675 // right side of LAnd/LOr?
676 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner54176fd2008-07-12 00:14:42 +0000677 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000678 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000679
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000680 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000681 default:
682 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000683 case BinaryOperator::Mul: Result *= RHS; return true;
684 case BinaryOperator::Add: Result += RHS; return true;
685 case BinaryOperator::Sub: Result -= RHS; return true;
686 case BinaryOperator::And: Result &= RHS; return true;
687 case BinaryOperator::Xor: Result ^= RHS; return true;
688 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner75a48812008-07-11 22:15:16 +0000689 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +0000690 if (RHS == 0)
Chris Lattner32fea9d2008-11-12 07:43:42 +0000691 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
692 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000693 Result /= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000694 break;
Chris Lattner75a48812008-07-11 22:15:16 +0000695 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +0000696 if (RHS == 0)
Chris Lattner32fea9d2008-11-12 07:43:42 +0000697 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
698 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000699 Result %= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000700 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000701 case BinaryOperator::Shl:
Chris Lattner54176fd2008-07-12 00:14:42 +0000702 // FIXME: Warn about out of range shift amounts!
Chris Lattnerb542afe2008-07-11 19:10:17 +0000703 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000704 break;
705 case BinaryOperator::Shr:
Chris Lattnerb542afe2008-07-11 19:10:17 +0000706 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000707 break;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000708
Chris Lattnerac7cb602008-07-11 19:29:32 +0000709 case BinaryOperator::LT:
710 Result = Result < RHS;
711 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
712 break;
713 case BinaryOperator::GT:
714 Result = Result > RHS;
715 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
716 break;
717 case BinaryOperator::LE:
718 Result = Result <= RHS;
719 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
720 break;
721 case BinaryOperator::GE:
722 Result = Result >= RHS;
723 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
724 break;
725 case BinaryOperator::EQ:
726 Result = Result == RHS;
727 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
728 break;
729 case BinaryOperator::NE:
730 Result = Result != RHS;
731 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
732 break;
Chris Lattner54176fd2008-07-12 00:14:42 +0000733 case BinaryOperator::LAnd:
734 Result = Result != 0 && RHS != 0;
735 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
736 break;
737 case BinaryOperator::LOr:
738 Result = Result != 0 || RHS != 0;
739 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
740 break;
Eli Friedmanb11e7782008-11-13 02:13:11 +0000741 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000742
743 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000744 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000745}
746
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000747bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +0000748 bool Cond;
749 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000750 return false;
751
Nuno Lopesa25bd552008-11-16 22:06:39 +0000752 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000753}
754
Sebastian Redl05189992008-11-11 17:56:53 +0000755/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
756/// expression's type.
757bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
758 QualType DstTy = E->getType();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000759 // Return the result in the right width.
760 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
761 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
762
Sebastian Redl05189992008-11-11 17:56:53 +0000763 QualType SrcTy = E->getTypeOfArgument();
764
Chris Lattnerfcee0012008-07-11 21:24:13 +0000765 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman4efaa272008-11-12 09:44:48 +0000766 if (SrcTy->isVoidType()) {
Chris Lattnerfcee0012008-07-11 21:24:13 +0000767 Result = 1;
Eli Friedman4efaa272008-11-12 09:44:48 +0000768 return true;
769 }
Chris Lattnerfcee0012008-07-11 21:24:13 +0000770
771 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman4efaa272008-11-12 09:44:48 +0000772 // FIXME: But alignof(vla) is!
Chris Lattnerfcee0012008-07-11 21:24:13 +0000773 if (!SrcTy->isConstantSizeType()) {
774 // FIXME: Should we attempt to evaluate this?
775 return false;
776 }
Sebastian Redl05189992008-11-11 17:56:53 +0000777
778 bool isSizeOf = E->isSizeOf();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000779
780 // GCC extension: sizeof(function) = 1.
781 if (SrcTy->isFunctionType()) {
782 // FIXME: AlignOf shouldn't be unconditionally 4!
783 Result = isSizeOf ? 1 : 4;
784 return true;
785 }
786
787 // Get information about the size or align.
Chris Lattner87eae5e2008-07-11 22:52:41 +0000788 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000789 if (isSizeOf)
Eli Friedman4efaa272008-11-12 09:44:48 +0000790 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000791 else
Chris Lattner87eae5e2008-07-11 22:52:41 +0000792 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000793 return true;
794}
795
Chris Lattnerb542afe2008-07-11 19:10:17 +0000796bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000797 // Special case unary operators that do not need their subexpression
798 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner75a48812008-07-11 22:15:16 +0000799 if (E->isOffsetOfOp()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000800 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner87eae5e2008-07-11 22:52:41 +0000801 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner75a48812008-07-11 22:15:16 +0000802 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
803 return true;
804 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000805
806 if (E->getOpcode() == UnaryOperator::LNot) {
807 // LNot's operand isn't necessarily an integer, so we handle it specially.
808 bool bres;
809 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
810 return false;
811 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
812 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
813 Result = !bres;
814 return true;
815 }
816
Chris Lattner87eae5e2008-07-11 22:52:41 +0000817 // Get the operand value into 'Result'.
818 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +0000819 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000820
Chris Lattner75a48812008-07-11 22:15:16 +0000821 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000822 default:
Chris Lattner75a48812008-07-11 22:15:16 +0000823 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
824 // See C99 6.6p3.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000825 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
826 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000827 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000828 // FIXME: Should extension allow i-c-e extension expressions in its scope?
829 // If so, we could clear the diagnostic ID.
Chris Lattner75a48812008-07-11 22:15:16 +0000830 case UnaryOperator::Plus:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000831 // The result is always just the subexpr.
Chris Lattner75a48812008-07-11 22:15:16 +0000832 break;
833 case UnaryOperator::Minus:
834 Result = -Result;
835 break;
836 case UnaryOperator::Not:
837 Result = ~Result;
838 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000839 }
840
841 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000842 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000843}
844
Chris Lattner732b2232008-07-12 01:15:53 +0000845/// HandleCast - This is used to evaluate implicit or explicit casts where the
846/// result type is integer.
847bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
848 Expr *SubExpr, QualType DestType) {
Chris Lattner7a767782008-07-11 19:24:49 +0000849 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000850
Eli Friedman4efaa272008-11-12 09:44:48 +0000851 if (DestType->isBooleanType()) {
852 bool BoolResult;
853 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
854 return false;
855 Result.zextOrTrunc(DestWidth);
856 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
857 Result = BoolResult;
858 return true;
859 }
860
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000861 // Handle simple integer->integer casts.
Eli Friedmana6afa762008-11-13 06:09:17 +0000862 if (SubExpr->getType()->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +0000863 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000864 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000865
866 // Figure out if this is a truncate, extend or noop cast.
867 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman4efaa272008-11-12 09:44:48 +0000868 Result.extOrTrunc(DestWidth);
Chris Lattner732b2232008-07-12 01:15:53 +0000869 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
870 return true;
871 }
872
873 // FIXME: Clean this up!
874 if (SubExpr->getType()->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000875 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000876 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000877 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000878
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000879 if (LV.getLValueBase())
Chris Lattnerb542afe2008-07-11 19:10:17 +0000880 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000881
Anders Carlsson559e56b2008-07-08 16:49:00 +0000882 Result.extOrTrunc(DestWidth);
883 Result = LV.getLValueOffset();
Chris Lattner732b2232008-07-12 01:15:53 +0000884 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
885 return true;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000886 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000887
Chris Lattner732b2232008-07-12 01:15:53 +0000888 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner32fea9d2008-11-12 07:43:42 +0000889 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattner732b2232008-07-12 01:15:53 +0000890
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000891 APFloat F(0.0);
892 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner32fea9d2008-11-12 07:43:42 +0000893 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattner732b2232008-07-12 01:15:53 +0000894
895 // Determine whether we are converting to unsigned or signed.
896 bool DestSigned = DestType->isSignedIntegerType();
897
898 // FIXME: Warning for overflow.
Dale Johannesenee5a7002008-10-09 23:02:32 +0000899 uint64_t Space[4];
900 bool ignored;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000901 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesenee5a7002008-10-09 23:02:32 +0000902 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattner732b2232008-07-12 01:15:53 +0000903 Result = llvm::APInt(DestWidth, 4, Space);
904 Result.setIsUnsigned(!DestSigned);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000905 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000906}
Anders Carlsson2bad1682008-07-08 14:30:00 +0000907
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000908//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000909// Float Evaluation
910//===----------------------------------------------------------------------===//
911
912namespace {
913class VISIBILITY_HIDDEN FloatExprEvaluator
914 : public StmtVisitor<FloatExprEvaluator, bool> {
915 EvalInfo &Info;
916 APFloat &Result;
917public:
918 FloatExprEvaluator(EvalInfo &info, APFloat &result)
919 : Info(info), Result(result) {}
920
921 bool VisitStmt(Stmt *S) {
922 return false;
923 }
924
925 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +0000926 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000927
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000928 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000929 bool VisitBinaryOperator(const BinaryOperator *E);
930 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000931 bool VisitCastExpr(CastExpr *E);
932 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000933};
934} // end anonymous namespace
935
936static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
937 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
938}
939
Chris Lattner019f4e82008-10-06 05:28:25 +0000940bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner019f4e82008-10-06 05:28:25 +0000941 switch (E->isBuiltinCall()) {
Chris Lattner34a74ab2008-10-06 05:53:16 +0000942 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +0000943 case Builtin::BI__builtin_huge_val:
944 case Builtin::BI__builtin_huge_valf:
945 case Builtin::BI__builtin_huge_vall:
946 case Builtin::BI__builtin_inf:
947 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000948 case Builtin::BI__builtin_infl: {
949 const llvm::fltSemantics &Sem =
950 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +0000951 Result = llvm::APFloat::getInf(Sem);
952 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000953 }
Chris Lattner9e621712008-10-06 06:31:58 +0000954
955 case Builtin::BI__builtin_nan:
956 case Builtin::BI__builtin_nanf:
957 case Builtin::BI__builtin_nanl:
958 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
959 // can't constant fold it.
960 if (const StringLiteral *S =
961 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
962 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000963 const llvm::fltSemantics &Sem =
964 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner9e621712008-10-06 06:31:58 +0000965 Result = llvm::APFloat::getNaN(Sem);
966 return true;
967 }
968 }
969 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000970
971 case Builtin::BI__builtin_fabs:
972 case Builtin::BI__builtin_fabsf:
973 case Builtin::BI__builtin_fabsl:
974 if (!EvaluateFloat(E->getArg(0), Result, Info))
975 return false;
976
977 if (Result.isNegative())
978 Result.changeSign();
979 return true;
980
981 case Builtin::BI__builtin_copysign:
982 case Builtin::BI__builtin_copysignf:
983 case Builtin::BI__builtin_copysignl: {
984 APFloat RHS(0.);
985 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
986 !EvaluateFloat(E->getArg(1), RHS, Info))
987 return false;
988 Result.copySign(RHS);
989 return true;
990 }
Chris Lattner019f4e82008-10-06 05:28:25 +0000991 }
992}
993
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000994bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopesa468d342008-11-19 17:44:31 +0000995 if (E->getOpcode() == UnaryOperator::Deref)
996 return false;
997
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000998 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
999 return false;
1000
1001 switch (E->getOpcode()) {
1002 default: return false;
1003 case UnaryOperator::Plus:
1004 return true;
1005 case UnaryOperator::Minus:
1006 Result.changeSign();
1007 return true;
1008 }
1009}
Chris Lattner019f4e82008-10-06 05:28:25 +00001010
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001011bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1012 // FIXME: Diagnostics? I really don't understand how the warnings
1013 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001014 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001015 if (!EvaluateFloat(E->getLHS(), Result, Info))
1016 return false;
1017 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1018 return false;
1019
1020 switch (E->getOpcode()) {
1021 default: return false;
1022 case BinaryOperator::Mul:
1023 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1024 return true;
1025 case BinaryOperator::Add:
1026 Result.add(RHS, APFloat::rmNearestTiesToEven);
1027 return true;
1028 case BinaryOperator::Sub:
1029 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1030 return true;
1031 case BinaryOperator::Div:
1032 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1033 return true;
1034 case BinaryOperator::Rem:
1035 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1036 return true;
1037 }
1038}
1039
1040bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1041 Result = E->getValue();
1042 return true;
1043}
1044
Eli Friedman4efaa272008-11-12 09:44:48 +00001045bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1046 Expr* SubExpr = E->getSubExpr();
1047 const llvm::fltSemantics& destSemantics =
1048 Info.Ctx.getFloatTypeSemantics(E->getType());
1049 if (SubExpr->getType()->isIntegralType()) {
1050 APSInt IntResult;
1051 if (!EvaluateInteger(E, IntResult, Info))
1052 return false;
1053 Result = APFloat(destSemantics, 1);
1054 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1055 APFloat::rmNearestTiesToEven);
1056 return true;
1057 }
1058 if (SubExpr->getType()->isRealFloatingType()) {
1059 if (!Visit(SubExpr))
1060 return false;
1061 bool ignored;
1062 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1063 return true;
1064 }
1065
1066 return false;
1067}
1068
1069bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1070 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1071 return true;
1072}
1073
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001074//===----------------------------------------------------------------------===//
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001075// Complex Float Evaluation
1076//===----------------------------------------------------------------------===//
1077
1078namespace {
1079class VISIBILITY_HIDDEN ComplexFloatExprEvaluator
1080 : public StmtVisitor<ComplexFloatExprEvaluator, APValue> {
1081 EvalInfo &Info;
1082
1083public:
1084 ComplexFloatExprEvaluator(EvalInfo &info) : Info(info) {}
1085
1086 //===--------------------------------------------------------------------===//
1087 // Visitor Methods
1088 //===--------------------------------------------------------------------===//
1089
1090 APValue VisitStmt(Stmt *S) {
1091 assert(0 && "This should be called on complex floats");
1092 return APValue();
1093 }
1094
1095 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1096
1097 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1098 APFloat Result(0.0);
1099 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1100 return APValue();
1101
1102 return APValue(APFloat(0.0), Result);
1103 }
1104
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001105 APValue VisitCastExpr(CastExpr *E) {
1106 Expr* SubExpr = E->getSubExpr();
1107
1108 if (SubExpr->getType()->isRealFloatingType()) {
1109 APFloat Result(0.0);
1110
1111 if (!EvaluateFloat(SubExpr, Result, Info))
1112 return APValue();
1113
1114 return APValue(Result, APFloat(0.0));
1115 }
1116
1117 // FIXME: Handle more casts.
1118 return APValue();
1119 }
1120
1121 APValue VisitBinaryOperator(const BinaryOperator *E);
1122
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001123};
1124} // end anonymous namespace
1125
1126static bool EvaluateComplexFloat(const Expr *E, APValue &Result, EvalInfo &Info)
1127{
1128 Result = ComplexFloatExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1129 return Result.isComplexFloat();
1130}
1131
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001132APValue ComplexFloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
1133{
1134 APValue Result, RHS;
1135
1136 if (!EvaluateComplexFloat(E->getLHS(), Result, Info))
1137 return APValue();
1138
1139 if (!EvaluateComplexFloat(E->getRHS(), RHS, Info))
1140 return APValue();
1141
1142 switch (E->getOpcode()) {
1143 default: return APValue();
1144 case BinaryOperator::Add:
1145 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1146 APFloat::rmNearestTiesToEven);
1147 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1148 APFloat::rmNearestTiesToEven);
1149 case BinaryOperator::Sub:
1150 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1151 APFloat::rmNearestTiesToEven);
1152 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1153 APFloat::rmNearestTiesToEven);
1154 }
1155
1156 return Result;
1157}
1158
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001159//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001160// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001161//===----------------------------------------------------------------------===//
1162
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001163/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner019f4e82008-10-06 05:28:25 +00001164/// any crazy technique (that has nothing to do with language standards) that
1165/// we want to. If this function returns true, it returns the folded constant
1166/// in Result.
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001167bool Expr::Evaluate(APValue &Result, ASTContext &Ctx, bool *isEvaluated) const {
Chris Lattner87eae5e2008-07-11 22:52:41 +00001168 EvalInfo Info(Ctx);
Anders Carlsson06a36752008-07-08 05:49:43 +00001169 if (getType()->isIntegerType()) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001170 llvm::APSInt sInt(32);
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001171 if (!EvaluateInteger(this, sInt, Info))
1172 return false;
1173
1174 Result = APValue(sInt);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001175 } else if (getType()->isPointerType()) {
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001176 if (!EvaluatePointer(this, Result, Info))
1177 return false;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001178 } else if (getType()->isRealFloatingType()) {
1179 llvm::APFloat f(0.0);
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001180 if (!EvaluateFloat(this, f, Info))
1181 return false;
1182
1183 Result = APValue(f);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001184 } else if (getType()->isComplexType()) {
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001185 if (!EvaluateComplexFloat(this, Result, Info))
1186 return false;
Anders Carlsson9d4c1572008-11-22 22:56:32 +00001187 } else
1188 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001189
1190 if (isEvaluated)
1191 *isEvaluated = Info.isEvaluated;
1192 return true;
Anders Carlssonc44eec62008-07-03 04:20:39 +00001193}
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001194
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001195/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001196/// folded, but discard the result.
1197bool Expr::isEvaluatable(ASTContext &Ctx) const {
1198 APValue V;
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001199 return Evaluate(V, Ctx);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001200}
Anders Carlsson51fe9962008-11-22 21:04:56 +00001201
1202APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
1203 APValue V;
1204 bool Result = Evaluate(V, Ctx);
1205 assert(Result && "Could not evaluate expression");
1206 assert(V.isInt() && "Expression did not evaluate to integer");
1207
1208 return V.getInt();
1209}