blob: 727678662db4b8af6c7e9cf32374941f50c920b7 [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()); }
124 APValue VisitDeclRefExpr(DeclRefExpr *E) { return APValue(E, 0); }
125 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
138APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
139 if (E->isFileScope())
140 return APValue(E, 0);
141 return APValue();
142}
143
144APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
145 APValue result;
146 QualType Ty;
147 if (E->isArrow()) {
148 if (!EvaluatePointer(E->getBase(), result, Info))
149 return APValue();
150 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
151 } else {
152 result = Visit(E->getBase());
153 if (result.isUninit())
154 return APValue();
155 Ty = E->getBase()->getType();
156 }
157
158 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
159 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
160 FieldDecl *FD = E->getMemberDecl();
161
162 // FIXME: This is linear time.
163 unsigned i = 0, e = 0;
164 for (i = 0, e = RD->getNumMembers(); i != e; i++) {
165 if (RD->getMember(i) == FD)
166 break;
167 }
168
169 result.setLValue(result.getLValueBase(),
170 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
171
172 return result;
173}
174
Anders Carlsson3068d112008-11-16 19:01:22 +0000175APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
176{
177 APValue Result;
178
179 if (!EvaluatePointer(E->getBase(), Result, Info))
180 return APValue();
181
182 APSInt Index;
183 if (!EvaluateInteger(E->getIdx(), Index, Info))
184 return APValue();
185
186 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
187
188 uint64_t Offset = Index.getSExtValue() * ElementSize;
189 Result.setLValue(Result.getLValueBase(),
190 Result.getLValueOffset() + Offset);
191 return Result;
192}
Eli Friedman4efaa272008-11-12 09:44:48 +0000193
194//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000195// Pointer Evaluation
196//===----------------------------------------------------------------------===//
197
Anders Carlssonc754aa62008-07-08 05:13:58 +0000198namespace {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000199class VISIBILITY_HIDDEN PointerExprEvaluator
200 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000201 EvalInfo &Info;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000202public:
Anders Carlsson2bad1682008-07-08 14:30:00 +0000203
Chris Lattner87eae5e2008-07-11 22:52:41 +0000204 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000205
Anders Carlsson2bad1682008-07-08 14:30:00 +0000206 APValue VisitStmt(Stmt *S) {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000207 return APValue();
208 }
209
210 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
211
Anders Carlsson650c92f2008-07-08 15:34:11 +0000212 APValue VisitBinaryOperator(const BinaryOperator *E);
213 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000214 APValue VisitUnaryOperator(const UnaryOperator *E);
215 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
216 { return APValue(E, 0); }
217 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlsson650c92f2008-07-08 15:34:11 +0000218};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000219} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000220
Chris Lattner87eae5e2008-07-11 22:52:41 +0000221static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000222 if (!E->getType()->isPointerType())
223 return false;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000224 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000225 return Result.isLValue();
226}
227
228APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
229 if (E->getOpcode() != BinaryOperator::Add &&
230 E->getOpcode() != BinaryOperator::Sub)
231 return APValue();
232
233 const Expr *PExp = E->getLHS();
234 const Expr *IExp = E->getRHS();
235 if (IExp->getType()->isPointerType())
236 std::swap(PExp, IExp);
237
238 APValue ResultLValue;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000239 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000240 return APValue();
241
242 llvm::APSInt AdditionalOffset(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000243 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000244 return APValue();
245
Eli Friedman4efaa272008-11-12 09:44:48 +0000246 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
247 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
248
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000249 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman4efaa272008-11-12 09:44:48 +0000250
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000251 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman4efaa272008-11-12 09:44:48 +0000252 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000253 else
Eli Friedman4efaa272008-11-12 09:44:48 +0000254 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
255
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000256 return APValue(ResultLValue.getLValueBase(), Offset);
257}
Eli Friedman4efaa272008-11-12 09:44:48 +0000258
259APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
260 if (E->getOpcode() == UnaryOperator::Extension) {
261 // FIXME: Deal with warnings?
262 return Visit(E->getSubExpr());
263 }
264
265 if (E->getOpcode() == UnaryOperator::AddrOf) {
266 APValue result;
267 if (EvaluateLValue(E->getSubExpr(), result, Info))
268 return result;
269 }
270
271 return APValue();
272}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000273
274
Chris Lattnerb542afe2008-07-11 19:10:17 +0000275APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000276 const Expr* SubExpr = E->getSubExpr();
277
278 // Check for pointer->pointer cast
279 if (SubExpr->getType()->isPointerType()) {
280 APValue Result;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000281 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000282 return Result;
283 return APValue();
284 }
285
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000286 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000287 llvm::APSInt Result(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000288 if (EvaluateInteger(SubExpr, Result, Info)) {
289 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000290 return APValue(0, Result.getZExtValue());
291 }
292 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000293
294 if (SubExpr->getType()->isFunctionType() ||
295 SubExpr->getType()->isArrayType()) {
296 APValue Result;
297 if (EvaluateLValue(SubExpr, Result, Info))
298 return Result;
299 return APValue();
300 }
301
302 //assert(0 && "Unhandled cast");
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000303 return APValue();
304}
305
Eli Friedman4efaa272008-11-12 09:44:48 +0000306APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
307 bool BoolResult;
308 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
309 return APValue();
310
311 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
312
313 APValue Result;
314 if (EvaluatePointer(EvalExpr, Result, Info))
315 return Result;
316 return APValue();
317}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000318
319//===----------------------------------------------------------------------===//
320// Integer Evaluation
321//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000322
323namespace {
Anders Carlssonc754aa62008-07-08 05:13:58 +0000324class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000325 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000326 EvalInfo &Info;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000327 APSInt &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000328public:
Chris Lattner87eae5e2008-07-11 22:52:41 +0000329 IntExprEvaluator(EvalInfo &info, APSInt &result)
330 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000331
Chris Lattner7a767782008-07-11 19:24:49 +0000332 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner54176fd2008-07-12 00:14:42 +0000333 return (unsigned)Info.Ctx.getIntWidth(T);
334 }
335
336 bool Extension(SourceLocation L, diag::kind D) {
337 Info.DiagLoc = L;
338 Info.ICEDiag = D;
339 return true; // still a constant.
340 }
341
Chris Lattner32fea9d2008-11-12 07:43:42 +0000342 bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000343 // If this is in an unevaluated portion of the subexpression, ignore the
344 // error.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000345 if (!Info.isEvaluated) {
346 // If error is ignored because the value isn't evaluated, get the real
347 // type at least to prevent errors downstream.
348 Result.zextOrTrunc(getIntTypeSizeInBits(ExprTy));
349 Result.setIsUnsigned(ExprTy->isUnsignedIntegerType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000350 return true;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000351 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000352
Chris Lattner32fea9d2008-11-12 07:43:42 +0000353 // Take the first error.
354 if (Info.ICEDiag == 0) {
355 Info.DiagLoc = L;
356 Info.ICEDiag = D;
357 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000358 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000359 }
360
Anders Carlssonc754aa62008-07-08 05:13:58 +0000361 //===--------------------------------------------------------------------===//
362 // Visitor Methods
363 //===--------------------------------------------------------------------===//
Chris Lattner32fea9d2008-11-12 07:43:42 +0000364
365 bool VisitStmt(Stmt *) {
366 assert(0 && "This should be called on integers, stmts are not integers");
367 return false;
368 }
Chris Lattner7a767782008-07-11 19:24:49 +0000369
Chris Lattner32fea9d2008-11-12 07:43:42 +0000370 bool VisitExpr(Expr *E) {
371 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Anders Carlssonc754aa62008-07-08 05:13:58 +0000372 }
373
Chris Lattnerb542afe2008-07-11 19:10:17 +0000374 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000375
Chris Lattner4c4867e2008-07-12 00:38:25 +0000376 bool VisitIntegerLiteral(const IntegerLiteral *E) {
377 Result = E->getValue();
378 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
379 return true;
380 }
381 bool VisitCharacterLiteral(const CharacterLiteral *E) {
382 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
383 Result = E->getValue();
384 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
385 return true;
386 }
387 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
388 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarac620de2008-10-24 08:07:57 +0000389 // Per gcc docs "this built-in function ignores top level
390 // qualifiers". We need to use the canonical version to properly
391 // be able to strip CRV qualifiers from the type.
392 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
393 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
394 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
395 T1.getUnqualifiedType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000396 return true;
397 }
398 bool VisitDeclRefExpr(const DeclRefExpr *E);
399 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000400 bool VisitBinaryOperator(const BinaryOperator *E);
401 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000402 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000403
Chris Lattner732b2232008-07-12 01:15:53 +0000404 bool VisitCastExpr(CastExpr* E) {
Chris Lattner732b2232008-07-12 01:15:53 +0000405 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlsson650c92f2008-07-08 15:34:11 +0000406 }
Sebastian Redl05189992008-11-11 17:56:53 +0000407 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
408
Anders Carlsson3068d112008-11-16 19:01:22 +0000409 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
410 Result = E->getValue();
411 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
412 return true;
413 }
414
415 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
416 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
417 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
418 return true;
419 }
420
Chris Lattnerfcee0012008-07-11 21:24:13 +0000421private:
Chris Lattner732b2232008-07-12 01:15:53 +0000422 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000423};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000424} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000425
Chris Lattner87eae5e2008-07-11 22:52:41 +0000426static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
427 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson650c92f2008-07-08 15:34:11 +0000428}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000429
Chris Lattner4c4867e2008-07-12 00:38:25 +0000430bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
431 // Enums are integer constant exprs.
432 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
433 Result = D->getInitVal();
434 return true;
435 }
436
437 // Otherwise, random variable references are not constants.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000438 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000439}
440
Chris Lattnera4d55d82008-10-06 06:40:35 +0000441/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
442/// as GCC.
443static int EvaluateBuiltinClassifyType(const CallExpr *E) {
444 // The following enum mimics the values returned by GCC.
445 enum gcc_type_class {
446 no_type_class = -1,
447 void_type_class, integer_type_class, char_type_class,
448 enumeral_type_class, boolean_type_class,
449 pointer_type_class, reference_type_class, offset_type_class,
450 real_type_class, complex_type_class,
451 function_type_class, method_type_class,
452 record_type_class, union_type_class,
453 array_type_class, string_type_class,
454 lang_type_class
455 };
456
457 // If no argument was supplied, default to "no_type_class". This isn't
458 // ideal, however it is what gcc does.
459 if (E->getNumArgs() == 0)
460 return no_type_class;
461
462 QualType ArgTy = E->getArg(0)->getType();
463 if (ArgTy->isVoidType())
464 return void_type_class;
465 else if (ArgTy->isEnumeralType())
466 return enumeral_type_class;
467 else if (ArgTy->isBooleanType())
468 return boolean_type_class;
469 else if (ArgTy->isCharType())
470 return string_type_class; // gcc doesn't appear to use char_type_class
471 else if (ArgTy->isIntegerType())
472 return integer_type_class;
473 else if (ArgTy->isPointerType())
474 return pointer_type_class;
475 else if (ArgTy->isReferenceType())
476 return reference_type_class;
477 else if (ArgTy->isRealType())
478 return real_type_class;
479 else if (ArgTy->isComplexType())
480 return complex_type_class;
481 else if (ArgTy->isFunctionType())
482 return function_type_class;
483 else if (ArgTy->isStructureType())
484 return record_type_class;
485 else if (ArgTy->isUnionType())
486 return union_type_class;
487 else if (ArgTy->isArrayType())
488 return array_type_class;
489 else if (ArgTy->isUnionType())
490 return union_type_class;
491 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
492 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
493 return -1;
494}
495
Chris Lattner4c4867e2008-07-12 00:38:25 +0000496bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
497 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner4c4867e2008-07-12 00:38:25 +0000498
Chris Lattner019f4e82008-10-06 05:28:25 +0000499 switch (E->isBuiltinCall()) {
500 default:
Chris Lattner32fea9d2008-11-12 07:43:42 +0000501 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner019f4e82008-10-06 05:28:25 +0000502 case Builtin::BI__builtin_classify_type:
Chris Lattnera4d55d82008-10-06 06:40:35 +0000503 Result.setIsSigned(true);
504 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000505 return true;
506
507 case Builtin::BI__builtin_constant_p: {
508 // __builtin_constant_p always has one operand: it returns true if that
509 // operand can be folded, false otherwise.
510 APValue Res;
Chris Lattner6ee7aa12008-11-16 21:24:15 +0000511 Result = E->getArg(0)->Evaluate(Res, Info.Ctx);
Chris Lattner019f4e82008-10-06 05:28:25 +0000512 return true;
513 }
514 }
Chris Lattner4c4867e2008-07-12 00:38:25 +0000515}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000516
Chris Lattnerb542afe2008-07-11 19:10:17 +0000517bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000518 if (E->getOpcode() == BinaryOperator::Comma) {
519 // Evaluate the side that actually matters; this needs to be
520 // handled specially because calling Visit() on the LHS can
521 // have strange results when it doesn't have an integral type.
Nuno Lopesf9ef0c62008-11-16 20:09:07 +0000522 if (Visit(E->getRHS()))
523 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +0000524
525 // Check for isEvaluated; the idea is that this might eventually
526 // be useful for isICE and other similar uses that care about
527 // whether a comma is evaluated. This isn't really used yet, though,
528 // and I'm not sure it really works as intended.
529 if (!Info.isEvaluated)
Nuno Lopesf9ef0c62008-11-16 20:09:07 +0000530 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
Eli Friedmana6afa762008-11-13 06:09:17 +0000531
Nuno Lopesf9ef0c62008-11-16 20:09:07 +0000532 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000533 }
534
535 if (E->isLogicalOp()) {
536 // These need to be handled specially because the operands aren't
537 // necessarily integral
538 bool bres;
539 if (!HandleConversionToBool(E->getLHS(), bres, Info)) {
540 // We can't evaluate the LHS; however, sometimes the result
541 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
542 if (HandleConversionToBool(E->getRHS(), bres, Info) &&
543 bres == (E->getOpcode() == BinaryOperator::LOr)) {
544 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
545 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
546 Result = bres;
547 return true;
548 }
549
550 // Really can't evaluate
551 return false;
552 }
553
554 bool bres2;
555 if (HandleConversionToBool(E->getRHS(), bres2, Info)) {
556 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
557 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
558 if (E->getOpcode() == BinaryOperator::LOr)
559 Result = bres || bres2;
560 else
561 Result = bres && bres2;
562 return true;
563 }
564 return false;
565 }
566
Anders Carlsson286f85e2008-11-16 07:17:21 +0000567 QualType LHSTy = E->getLHS()->getType();
568 QualType RHSTy = E->getRHS()->getType();
569
570 if (LHSTy->isRealFloatingType() &&
571 RHSTy->isRealFloatingType()) {
572 APFloat RHS(0.0), LHS(0.0);
573
574 if (!EvaluateFloat(E->getRHS(), RHS, Info))
575 return false;
576
577 if (!EvaluateFloat(E->getLHS(), LHS, Info))
578 return false;
579
580 APFloat::cmpResult CR = LHS.compare(RHS);
581
582 switch (E->getOpcode()) {
583 default:
584 assert(0 && "Invalid binary operator!");
585 case BinaryOperator::LT:
586 Result = CR == APFloat::cmpLessThan;
587 break;
588 case BinaryOperator::GT:
589 Result = CR == APFloat::cmpGreaterThan;
590 break;
591 case BinaryOperator::LE:
592 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
593 break;
594 case BinaryOperator::GE:
595 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
596 break;
597 case BinaryOperator::EQ:
598 Result = CR == APFloat::cmpEqual;
599 break;
600 case BinaryOperator::NE:
601 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
602 break;
603 }
604
605 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
606 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
607 return true;
608 }
609
Anders Carlsson3068d112008-11-16 19:01:22 +0000610 if (E->getOpcode() == BinaryOperator::Sub) {
611 if (LHSTy->isPointerType()) {
612 if (RHSTy->isIntegralType()) {
613 // pointer - int.
614 // FIXME: Implement.
615 }
616
617 assert(RHSTy->isPointerType() && "RHS not pointer!");
618
619 APValue LHSValue;
620 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
621 return false;
622
623 APValue RHSValue;
624 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
625 return false;
626
627 // FIXME: Is this correct? What if only one of the operands has a base?
628 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
629 return false;
630
631 const QualType Type = E->getLHS()->getType();
632 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
633
634 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
635 D /= Info.Ctx.getTypeSize(ElementType) / 8;
636
637 Result = D;
638 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
639 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
640
641 return true;
642 }
643 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000644 if (!LHSTy->isIntegralType() ||
645 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000646 // We can't continue from here for non-integral types, and they
647 // could potentially confuse the following operations.
648 // FIXME: Deal with EQ and friends.
649 return false;
650 }
651
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000652 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000653 llvm::APSInt RHS(32);
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000654 if (!Visit(E->getLHS())) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000655 return false; // error in subexpression.
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000656 }
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000657
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000658
659 // FIXME Maybe we want to succeed even where we can't evaluate the
660 // right side of LAnd/LOr?
661 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner54176fd2008-07-12 00:14:42 +0000662 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000663 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000664
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000665 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000666 default:
667 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000668 case BinaryOperator::Mul: Result *= RHS; return true;
669 case BinaryOperator::Add: Result += RHS; return true;
670 case BinaryOperator::Sub: Result -= RHS; return true;
671 case BinaryOperator::And: Result &= RHS; return true;
672 case BinaryOperator::Xor: Result ^= RHS; return true;
673 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner75a48812008-07-11 22:15:16 +0000674 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +0000675 if (RHS == 0)
Chris Lattner32fea9d2008-11-12 07:43:42 +0000676 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
677 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000678 Result /= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000679 break;
Chris Lattner75a48812008-07-11 22:15:16 +0000680 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +0000681 if (RHS == 0)
Chris Lattner32fea9d2008-11-12 07:43:42 +0000682 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
683 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000684 Result %= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000685 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000686 case BinaryOperator::Shl:
Chris Lattner54176fd2008-07-12 00:14:42 +0000687 // FIXME: Warn about out of range shift amounts!
Chris Lattnerb542afe2008-07-11 19:10:17 +0000688 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000689 break;
690 case BinaryOperator::Shr:
Chris Lattnerb542afe2008-07-11 19:10:17 +0000691 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000692 break;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000693
Chris Lattnerac7cb602008-07-11 19:29:32 +0000694 case BinaryOperator::LT:
695 Result = Result < RHS;
696 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
697 break;
698 case BinaryOperator::GT:
699 Result = Result > RHS;
700 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
701 break;
702 case BinaryOperator::LE:
703 Result = Result <= RHS;
704 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
705 break;
706 case BinaryOperator::GE:
707 Result = Result >= RHS;
708 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
709 break;
710 case BinaryOperator::EQ:
711 Result = Result == RHS;
712 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
713 break;
714 case BinaryOperator::NE:
715 Result = Result != RHS;
716 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
717 break;
Chris Lattner54176fd2008-07-12 00:14:42 +0000718 case BinaryOperator::LAnd:
719 Result = Result != 0 && RHS != 0;
720 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
721 break;
722 case BinaryOperator::LOr:
723 Result = Result != 0 || RHS != 0;
724 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
725 break;
Eli Friedmanb11e7782008-11-13 02:13:11 +0000726 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000727
728 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000729 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000730}
731
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000732bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
733 llvm::APSInt Cond(32);
734 if (!EvaluateInteger(E->getCond(), Cond, Info))
735 return false;
736
737 return Visit(Cond != 0 ? E->getTrueExpr() : E->getFalseExpr());
738}
739
Sebastian Redl05189992008-11-11 17:56:53 +0000740/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
741/// expression's type.
742bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
743 QualType DstTy = E->getType();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000744 // Return the result in the right width.
745 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
746 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
747
Sebastian Redl05189992008-11-11 17:56:53 +0000748 QualType SrcTy = E->getTypeOfArgument();
749
Chris Lattnerfcee0012008-07-11 21:24:13 +0000750 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman4efaa272008-11-12 09:44:48 +0000751 if (SrcTy->isVoidType()) {
Chris Lattnerfcee0012008-07-11 21:24:13 +0000752 Result = 1;
Eli Friedman4efaa272008-11-12 09:44:48 +0000753 return true;
754 }
Chris Lattnerfcee0012008-07-11 21:24:13 +0000755
756 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman4efaa272008-11-12 09:44:48 +0000757 // FIXME: But alignof(vla) is!
Chris Lattnerfcee0012008-07-11 21:24:13 +0000758 if (!SrcTy->isConstantSizeType()) {
759 // FIXME: Should we attempt to evaluate this?
760 return false;
761 }
Sebastian Redl05189992008-11-11 17:56:53 +0000762
763 bool isSizeOf = E->isSizeOf();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000764
765 // GCC extension: sizeof(function) = 1.
766 if (SrcTy->isFunctionType()) {
767 // FIXME: AlignOf shouldn't be unconditionally 4!
768 Result = isSizeOf ? 1 : 4;
769 return true;
770 }
771
772 // Get information about the size or align.
Chris Lattner87eae5e2008-07-11 22:52:41 +0000773 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000774 if (isSizeOf)
Eli Friedman4efaa272008-11-12 09:44:48 +0000775 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000776 else
Chris Lattner87eae5e2008-07-11 22:52:41 +0000777 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000778 return true;
779}
780
Chris Lattnerb542afe2008-07-11 19:10:17 +0000781bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000782 // Special case unary operators that do not need their subexpression
783 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner75a48812008-07-11 22:15:16 +0000784 if (E->isOffsetOfOp()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000785 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner87eae5e2008-07-11 22:52:41 +0000786 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner75a48812008-07-11 22:15:16 +0000787 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
788 return true;
789 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000790
791 if (E->getOpcode() == UnaryOperator::LNot) {
792 // LNot's operand isn't necessarily an integer, so we handle it specially.
793 bool bres;
794 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
795 return false;
796 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
797 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
798 Result = !bres;
799 return true;
800 }
801
Chris Lattner87eae5e2008-07-11 22:52:41 +0000802 // Get the operand value into 'Result'.
803 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +0000804 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000805
Chris Lattner75a48812008-07-11 22:15:16 +0000806 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000807 default:
Chris Lattner75a48812008-07-11 22:15:16 +0000808 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
809 // See C99 6.6p3.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000810 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
811 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000812 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000813 // FIXME: Should extension allow i-c-e extension expressions in its scope?
814 // If so, we could clear the diagnostic ID.
Chris Lattner75a48812008-07-11 22:15:16 +0000815 case UnaryOperator::Plus:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000816 // The result is always just the subexpr.
Chris Lattner75a48812008-07-11 22:15:16 +0000817 break;
818 case UnaryOperator::Minus:
819 Result = -Result;
820 break;
821 case UnaryOperator::Not:
822 Result = ~Result;
823 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000824 }
825
826 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000827 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000828}
829
Chris Lattner732b2232008-07-12 01:15:53 +0000830/// HandleCast - This is used to evaluate implicit or explicit casts where the
831/// result type is integer.
832bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
833 Expr *SubExpr, QualType DestType) {
Chris Lattner7a767782008-07-11 19:24:49 +0000834 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000835
Eli Friedman4efaa272008-11-12 09:44:48 +0000836 if (DestType->isBooleanType()) {
837 bool BoolResult;
838 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
839 return false;
840 Result.zextOrTrunc(DestWidth);
841 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
842 Result = BoolResult;
843 return true;
844 }
845
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000846 // Handle simple integer->integer casts.
Eli Friedmana6afa762008-11-13 06:09:17 +0000847 if (SubExpr->getType()->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +0000848 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000849 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000850
851 // Figure out if this is a truncate, extend or noop cast.
852 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman4efaa272008-11-12 09:44:48 +0000853 Result.extOrTrunc(DestWidth);
Chris Lattner732b2232008-07-12 01:15:53 +0000854 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
855 return true;
856 }
857
858 // FIXME: Clean this up!
859 if (SubExpr->getType()->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000860 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000861 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000862 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000863
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000864 if (LV.getLValueBase())
Chris Lattnerb542afe2008-07-11 19:10:17 +0000865 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000866
Anders Carlsson559e56b2008-07-08 16:49:00 +0000867 Result.extOrTrunc(DestWidth);
868 Result = LV.getLValueOffset();
Chris Lattner732b2232008-07-12 01:15:53 +0000869 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
870 return true;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000871 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000872
Chris Lattner732b2232008-07-12 01:15:53 +0000873 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner32fea9d2008-11-12 07:43:42 +0000874 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattner732b2232008-07-12 01:15:53 +0000875
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000876 APFloat F(0.0);
877 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner32fea9d2008-11-12 07:43:42 +0000878 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattner732b2232008-07-12 01:15:53 +0000879
880 // Determine whether we are converting to unsigned or signed.
881 bool DestSigned = DestType->isSignedIntegerType();
882
883 // FIXME: Warning for overflow.
Dale Johannesenee5a7002008-10-09 23:02:32 +0000884 uint64_t Space[4];
885 bool ignored;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000886 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesenee5a7002008-10-09 23:02:32 +0000887 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattner732b2232008-07-12 01:15:53 +0000888 Result = llvm::APInt(DestWidth, 4, Space);
889 Result.setIsUnsigned(!DestSigned);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000890 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000891}
Anders Carlsson2bad1682008-07-08 14:30:00 +0000892
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000893//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000894// Float Evaluation
895//===----------------------------------------------------------------------===//
896
897namespace {
898class VISIBILITY_HIDDEN FloatExprEvaluator
899 : public StmtVisitor<FloatExprEvaluator, bool> {
900 EvalInfo &Info;
901 APFloat &Result;
902public:
903 FloatExprEvaluator(EvalInfo &info, APFloat &result)
904 : Info(info), Result(result) {}
905
906 bool VisitStmt(Stmt *S) {
907 return false;
908 }
909
910 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +0000911 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000912
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000913 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000914 bool VisitBinaryOperator(const BinaryOperator *E);
915 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000916 bool VisitCastExpr(CastExpr *E);
917 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000918};
919} // end anonymous namespace
920
921static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
922 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
923}
924
Chris Lattner019f4e82008-10-06 05:28:25 +0000925bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner019f4e82008-10-06 05:28:25 +0000926 switch (E->isBuiltinCall()) {
Chris Lattner34a74ab2008-10-06 05:53:16 +0000927 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +0000928 case Builtin::BI__builtin_huge_val:
929 case Builtin::BI__builtin_huge_valf:
930 case Builtin::BI__builtin_huge_vall:
931 case Builtin::BI__builtin_inf:
932 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000933 case Builtin::BI__builtin_infl: {
934 const llvm::fltSemantics &Sem =
935 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +0000936 Result = llvm::APFloat::getInf(Sem);
937 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000938 }
Chris Lattner9e621712008-10-06 06:31:58 +0000939
940 case Builtin::BI__builtin_nan:
941 case Builtin::BI__builtin_nanf:
942 case Builtin::BI__builtin_nanl:
943 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
944 // can't constant fold it.
945 if (const StringLiteral *S =
946 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
947 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000948 const llvm::fltSemantics &Sem =
949 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner9e621712008-10-06 06:31:58 +0000950 Result = llvm::APFloat::getNaN(Sem);
951 return true;
952 }
953 }
954 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000955
956 case Builtin::BI__builtin_fabs:
957 case Builtin::BI__builtin_fabsf:
958 case Builtin::BI__builtin_fabsl:
959 if (!EvaluateFloat(E->getArg(0), Result, Info))
960 return false;
961
962 if (Result.isNegative())
963 Result.changeSign();
964 return true;
965
966 case Builtin::BI__builtin_copysign:
967 case Builtin::BI__builtin_copysignf:
968 case Builtin::BI__builtin_copysignl: {
969 APFloat RHS(0.);
970 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
971 !EvaluateFloat(E->getArg(1), RHS, Info))
972 return false;
973 Result.copySign(RHS);
974 return true;
975 }
Chris Lattner019f4e82008-10-06 05:28:25 +0000976 }
977}
978
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000979bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
980 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
981 return false;
982
983 switch (E->getOpcode()) {
984 default: return false;
985 case UnaryOperator::Plus:
986 return true;
987 case UnaryOperator::Minus:
988 Result.changeSign();
989 return true;
990 }
991}
Chris Lattner019f4e82008-10-06 05:28:25 +0000992
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000993bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
994 // FIXME: Diagnostics? I really don't understand how the warnings
995 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000996 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000997 if (!EvaluateFloat(E->getLHS(), Result, Info))
998 return false;
999 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1000 return false;
1001
1002 switch (E->getOpcode()) {
1003 default: return false;
1004 case BinaryOperator::Mul:
1005 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1006 return true;
1007 case BinaryOperator::Add:
1008 Result.add(RHS, APFloat::rmNearestTiesToEven);
1009 return true;
1010 case BinaryOperator::Sub:
1011 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1012 return true;
1013 case BinaryOperator::Div:
1014 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1015 return true;
1016 case BinaryOperator::Rem:
1017 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1018 return true;
1019 }
1020}
1021
1022bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1023 Result = E->getValue();
1024 return true;
1025}
1026
Eli Friedman4efaa272008-11-12 09:44:48 +00001027bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1028 Expr* SubExpr = E->getSubExpr();
1029 const llvm::fltSemantics& destSemantics =
1030 Info.Ctx.getFloatTypeSemantics(E->getType());
1031 if (SubExpr->getType()->isIntegralType()) {
1032 APSInt IntResult;
1033 if (!EvaluateInteger(E, IntResult, Info))
1034 return false;
1035 Result = APFloat(destSemantics, 1);
1036 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1037 APFloat::rmNearestTiesToEven);
1038 return true;
1039 }
1040 if (SubExpr->getType()->isRealFloatingType()) {
1041 if (!Visit(SubExpr))
1042 return false;
1043 bool ignored;
1044 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1045 return true;
1046 }
1047
1048 return false;
1049}
1050
1051bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1052 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1053 return true;
1054}
1055
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001056//===----------------------------------------------------------------------===//
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001057// Complex Float Evaluation
1058//===----------------------------------------------------------------------===//
1059
1060namespace {
1061class VISIBILITY_HIDDEN ComplexFloatExprEvaluator
1062 : public StmtVisitor<ComplexFloatExprEvaluator, APValue> {
1063 EvalInfo &Info;
1064
1065public:
1066 ComplexFloatExprEvaluator(EvalInfo &info) : Info(info) {}
1067
1068 //===--------------------------------------------------------------------===//
1069 // Visitor Methods
1070 //===--------------------------------------------------------------------===//
1071
1072 APValue VisitStmt(Stmt *S) {
1073 assert(0 && "This should be called on complex floats");
1074 return APValue();
1075 }
1076
1077 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1078
1079 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1080 APFloat Result(0.0);
1081 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1082 return APValue();
1083
1084 return APValue(APFloat(0.0), Result);
1085 }
1086
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001087 APValue VisitCastExpr(CastExpr *E) {
1088 Expr* SubExpr = E->getSubExpr();
1089
1090 if (SubExpr->getType()->isRealFloatingType()) {
1091 APFloat Result(0.0);
1092
1093 if (!EvaluateFloat(SubExpr, Result, Info))
1094 return APValue();
1095
1096 return APValue(Result, APFloat(0.0));
1097 }
1098
1099 // FIXME: Handle more casts.
1100 return APValue();
1101 }
1102
1103 APValue VisitBinaryOperator(const BinaryOperator *E);
1104
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001105};
1106} // end anonymous namespace
1107
1108static bool EvaluateComplexFloat(const Expr *E, APValue &Result, EvalInfo &Info)
1109{
1110 Result = ComplexFloatExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1111 return Result.isComplexFloat();
1112}
1113
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001114APValue ComplexFloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
1115{
1116 APValue Result, RHS;
1117
1118 if (!EvaluateComplexFloat(E->getLHS(), Result, Info))
1119 return APValue();
1120
1121 if (!EvaluateComplexFloat(E->getRHS(), RHS, Info))
1122 return APValue();
1123
1124 switch (E->getOpcode()) {
1125 default: return APValue();
1126 case BinaryOperator::Add:
1127 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1128 APFloat::rmNearestTiesToEven);
1129 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1130 APFloat::rmNearestTiesToEven);
1131 case BinaryOperator::Sub:
1132 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1133 APFloat::rmNearestTiesToEven);
1134 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1135 APFloat::rmNearestTiesToEven);
1136 }
1137
1138 return Result;
1139}
1140
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001141//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001142// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001143//===----------------------------------------------------------------------===//
1144
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001145/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner019f4e82008-10-06 05:28:25 +00001146/// any crazy technique (that has nothing to do with language standards) that
1147/// we want to. If this function returns true, it returns the folded constant
1148/// in Result.
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001149bool Expr::Evaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner87eae5e2008-07-11 22:52:41 +00001150 EvalInfo Info(Ctx);
Anders Carlsson06a36752008-07-08 05:49:43 +00001151 if (getType()->isIntegerType()) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001152 llvm::APSInt sInt(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +00001153 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlsson06a36752008-07-08 05:49:43 +00001154 Result = APValue(sInt);
1155 return true;
1156 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001157 } else if (getType()->isPointerType()) {
1158 if (EvaluatePointer(this, Result, Info)) {
1159 return true;
1160 }
1161 } else if (getType()->isRealFloatingType()) {
1162 llvm::APFloat f(0.0);
1163 if (EvaluateFloat(this, f, Info)) {
1164 Result = APValue(f);
1165 return true;
1166 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001167 } else if (getType()->isComplexType()) {
1168 if (EvaluateComplexFloat(this, Result, Info))
1169 return true;
1170 }
Anders Carlsson165a70f2008-08-10 17:03:01 +00001171
Anders Carlssonc44eec62008-07-03 04:20:39 +00001172 return false;
1173}
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001174
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001175/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001176/// folded, but discard the result.
1177bool Expr::isEvaluatable(ASTContext &Ctx) const {
1178 APValue V;
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001179 return Evaluate(V, Ctx);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001180}