blob: 4a679567498be1a30b096b8140df12d67e22c580 [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);
Chris Lattnerf5eeb052008-07-11 18:11:29 +000070
71//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +000072// Misc utilities
73//===----------------------------------------------------------------------===//
74
75static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
76 if (E->getType()->isIntegralType()) {
77 APSInt IntResult;
78 if (!EvaluateInteger(E, IntResult, Info))
79 return false;
80 Result = IntResult != 0;
81 return true;
82 } else if (E->getType()->isRealFloatingType()) {
83 APFloat FloatResult(0.0);
84 if (!EvaluateFloat(E, FloatResult, Info))
85 return false;
86 Result = !FloatResult.isZero();
87 return true;
88 } else if (E->getType()->isPointerType()) {
89 APValue PointerResult;
90 if (!EvaluatePointer(E, PointerResult, Info))
91 return false;
92 // FIXME: Is this accurate for all kinds of bases? If not, what would
93 // the check look like?
94 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
95 return true;
96 }
97
98 return false;
99}
100
101//===----------------------------------------------------------------------===//
102// LValue Evaluation
103//===----------------------------------------------------------------------===//
104namespace {
105class VISIBILITY_HIDDEN LValueExprEvaluator
106 : public StmtVisitor<LValueExprEvaluator, APValue> {
107 EvalInfo &Info;
108public:
109
110 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
111
112 APValue VisitStmt(Stmt *S) {
Daniel Dunbar8a7b7c62008-11-12 21:52:46 +0000113#if 0
Eli Friedman4efaa272008-11-12 09:44:48 +0000114 // FIXME: Remove this when we support more expressions.
115 printf("Unhandled pointer statement\n");
116 S->dump();
Daniel Dunbar8a7b7c62008-11-12 21:52:46 +0000117#endif
Eli Friedman4efaa272008-11-12 09:44:48 +0000118 return APValue();
119 }
120
121 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
122 APValue VisitDeclRefExpr(DeclRefExpr *E) { return APValue(E, 0); }
123 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
124 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
125 APValue VisitMemberExpr(MemberExpr *E);
126 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
Anders Carlsson3068d112008-11-16 19:01:22 +0000127 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000128};
129} // end anonymous namespace
130
131static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
132 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
133 return Result.isLValue();
134}
135
136APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
137 if (E->isFileScope())
138 return APValue(E, 0);
139 return APValue();
140}
141
142APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
143 APValue result;
144 QualType Ty;
145 if (E->isArrow()) {
146 if (!EvaluatePointer(E->getBase(), result, Info))
147 return APValue();
148 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
149 } else {
150 result = Visit(E->getBase());
151 if (result.isUninit())
152 return APValue();
153 Ty = E->getBase()->getType();
154 }
155
156 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
157 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
158 FieldDecl *FD = E->getMemberDecl();
159
160 // FIXME: This is linear time.
161 unsigned i = 0, e = 0;
162 for (i = 0, e = RD->getNumMembers(); i != e; i++) {
163 if (RD->getMember(i) == FD)
164 break;
165 }
166
167 result.setLValue(result.getLValueBase(),
168 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
169
170 return result;
171}
172
Anders Carlsson3068d112008-11-16 19:01:22 +0000173APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
174{
175 APValue Result;
176
177 if (!EvaluatePointer(E->getBase(), Result, Info))
178 return APValue();
179
180 APSInt Index;
181 if (!EvaluateInteger(E->getIdx(), Index, Info))
182 return APValue();
183
184 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
185
186 uint64_t Offset = Index.getSExtValue() * ElementSize;
187 Result.setLValue(Result.getLValueBase(),
188 Result.getLValueOffset() + Offset);
189 return Result;
190}
Eli Friedman4efaa272008-11-12 09:44:48 +0000191
192//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000193// Pointer Evaluation
194//===----------------------------------------------------------------------===//
195
Anders Carlssonc754aa62008-07-08 05:13:58 +0000196namespace {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000197class VISIBILITY_HIDDEN PointerExprEvaluator
198 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000199 EvalInfo &Info;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000200public:
Anders Carlsson2bad1682008-07-08 14:30:00 +0000201
Chris Lattner87eae5e2008-07-11 22:52:41 +0000202 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000203
Anders Carlsson2bad1682008-07-08 14:30:00 +0000204 APValue VisitStmt(Stmt *S) {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000205 return APValue();
206 }
207
208 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
209
Anders Carlsson650c92f2008-07-08 15:34:11 +0000210 APValue VisitBinaryOperator(const BinaryOperator *E);
211 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000212 APValue VisitUnaryOperator(const UnaryOperator *E);
213 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
214 { return APValue(E, 0); }
215 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlsson650c92f2008-07-08 15:34:11 +0000216};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000217} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000218
Chris Lattner87eae5e2008-07-11 22:52:41 +0000219static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000220 if (!E->getType()->isPointerType())
221 return false;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000222 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000223 return Result.isLValue();
224}
225
226APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
227 if (E->getOpcode() != BinaryOperator::Add &&
228 E->getOpcode() != BinaryOperator::Sub)
229 return APValue();
230
231 const Expr *PExp = E->getLHS();
232 const Expr *IExp = E->getRHS();
233 if (IExp->getType()->isPointerType())
234 std::swap(PExp, IExp);
235
236 APValue ResultLValue;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000237 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000238 return APValue();
239
240 llvm::APSInt AdditionalOffset(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000241 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000242 return APValue();
243
Eli Friedman4efaa272008-11-12 09:44:48 +0000244 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
245 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
246
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000247 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman4efaa272008-11-12 09:44:48 +0000248
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000249 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman4efaa272008-11-12 09:44:48 +0000250 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000251 else
Eli Friedman4efaa272008-11-12 09:44:48 +0000252 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
253
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000254 return APValue(ResultLValue.getLValueBase(), Offset);
255}
Eli Friedman4efaa272008-11-12 09:44:48 +0000256
257APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
258 if (E->getOpcode() == UnaryOperator::Extension) {
259 // FIXME: Deal with warnings?
260 return Visit(E->getSubExpr());
261 }
262
263 if (E->getOpcode() == UnaryOperator::AddrOf) {
264 APValue result;
265 if (EvaluateLValue(E->getSubExpr(), result, Info))
266 return result;
267 }
268
269 return APValue();
270}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000271
272
Chris Lattnerb542afe2008-07-11 19:10:17 +0000273APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000274 const Expr* SubExpr = E->getSubExpr();
275
276 // Check for pointer->pointer cast
277 if (SubExpr->getType()->isPointerType()) {
278 APValue Result;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000279 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000280 return Result;
281 return APValue();
282 }
283
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000284 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000285 llvm::APSInt Result(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000286 if (EvaluateInteger(SubExpr, Result, Info)) {
287 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000288 return APValue(0, Result.getZExtValue());
289 }
290 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000291
292 if (SubExpr->getType()->isFunctionType() ||
293 SubExpr->getType()->isArrayType()) {
294 APValue Result;
295 if (EvaluateLValue(SubExpr, Result, Info))
296 return Result;
297 return APValue();
298 }
299
300 //assert(0 && "Unhandled cast");
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000301 return APValue();
302}
303
Eli Friedman4efaa272008-11-12 09:44:48 +0000304APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
305 bool BoolResult;
306 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
307 return APValue();
308
309 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
310
311 APValue Result;
312 if (EvaluatePointer(EvalExpr, Result, Info))
313 return Result;
314 return APValue();
315}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000316
317//===----------------------------------------------------------------------===//
318// Integer Evaluation
319//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000320
321namespace {
Anders Carlssonc754aa62008-07-08 05:13:58 +0000322class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000323 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000324 EvalInfo &Info;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000325 APSInt &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000326public:
Chris Lattner87eae5e2008-07-11 22:52:41 +0000327 IntExprEvaluator(EvalInfo &info, APSInt &result)
328 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000329
Chris Lattner7a767782008-07-11 19:24:49 +0000330 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner54176fd2008-07-12 00:14:42 +0000331 return (unsigned)Info.Ctx.getIntWidth(T);
332 }
333
334 bool Extension(SourceLocation L, diag::kind D) {
335 Info.DiagLoc = L;
336 Info.ICEDiag = D;
337 return true; // still a constant.
338 }
339
Chris Lattner32fea9d2008-11-12 07:43:42 +0000340 bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000341 // If this is in an unevaluated portion of the subexpression, ignore the
342 // error.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000343 if (!Info.isEvaluated) {
344 // If error is ignored because the value isn't evaluated, get the real
345 // type at least to prevent errors downstream.
346 Result.zextOrTrunc(getIntTypeSizeInBits(ExprTy));
347 Result.setIsUnsigned(ExprTy->isUnsignedIntegerType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000348 return true;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000349 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000350
Chris Lattner32fea9d2008-11-12 07:43:42 +0000351 // Take the first error.
352 if (Info.ICEDiag == 0) {
353 Info.DiagLoc = L;
354 Info.ICEDiag = D;
355 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000356 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000357 }
358
Anders Carlssonc754aa62008-07-08 05:13:58 +0000359 //===--------------------------------------------------------------------===//
360 // Visitor Methods
361 //===--------------------------------------------------------------------===//
Chris Lattner32fea9d2008-11-12 07:43:42 +0000362
363 bool VisitStmt(Stmt *) {
364 assert(0 && "This should be called on integers, stmts are not integers");
365 return false;
366 }
Chris Lattner7a767782008-07-11 19:24:49 +0000367
Chris Lattner32fea9d2008-11-12 07:43:42 +0000368 bool VisitExpr(Expr *E) {
369 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Anders Carlssonc754aa62008-07-08 05:13:58 +0000370 }
371
Chris Lattnerb542afe2008-07-11 19:10:17 +0000372 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000373
Chris Lattner4c4867e2008-07-12 00:38:25 +0000374 bool VisitIntegerLiteral(const IntegerLiteral *E) {
375 Result = E->getValue();
376 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
377 return true;
378 }
379 bool VisitCharacterLiteral(const CharacterLiteral *E) {
380 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
381 Result = E->getValue();
382 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
383 return true;
384 }
385 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
386 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarac620de2008-10-24 08:07:57 +0000387 // Per gcc docs "this built-in function ignores top level
388 // qualifiers". We need to use the canonical version to properly
389 // be able to strip CRV qualifiers from the type.
390 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
391 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
392 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
393 T1.getUnqualifiedType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000394 return true;
395 }
396 bool VisitDeclRefExpr(const DeclRefExpr *E);
397 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000398 bool VisitBinaryOperator(const BinaryOperator *E);
399 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000400
Chris Lattner732b2232008-07-12 01:15:53 +0000401 bool VisitCastExpr(CastExpr* E) {
Chris Lattner732b2232008-07-12 01:15:53 +0000402 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlsson650c92f2008-07-08 15:34:11 +0000403 }
Sebastian Redl05189992008-11-11 17:56:53 +0000404 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
405
Anders Carlsson3068d112008-11-16 19:01:22 +0000406 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
407 Result = E->getValue();
408 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
409 return true;
410 }
411
412 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
413 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
414 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
415 return true;
416 }
417
Chris Lattnerfcee0012008-07-11 21:24:13 +0000418private:
Chris Lattner732b2232008-07-12 01:15:53 +0000419 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000420};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000421} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000422
Chris Lattner87eae5e2008-07-11 22:52:41 +0000423static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
424 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson650c92f2008-07-08 15:34:11 +0000425}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000426
Chris Lattner4c4867e2008-07-12 00:38:25 +0000427bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
428 // Enums are integer constant exprs.
429 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
430 Result = D->getInitVal();
431 return true;
432 }
433
434 // Otherwise, random variable references are not constants.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000435 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000436}
437
Chris Lattnera4d55d82008-10-06 06:40:35 +0000438/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
439/// as GCC.
440static int EvaluateBuiltinClassifyType(const CallExpr *E) {
441 // The following enum mimics the values returned by GCC.
442 enum gcc_type_class {
443 no_type_class = -1,
444 void_type_class, integer_type_class, char_type_class,
445 enumeral_type_class, boolean_type_class,
446 pointer_type_class, reference_type_class, offset_type_class,
447 real_type_class, complex_type_class,
448 function_type_class, method_type_class,
449 record_type_class, union_type_class,
450 array_type_class, string_type_class,
451 lang_type_class
452 };
453
454 // If no argument was supplied, default to "no_type_class". This isn't
455 // ideal, however it is what gcc does.
456 if (E->getNumArgs() == 0)
457 return no_type_class;
458
459 QualType ArgTy = E->getArg(0)->getType();
460 if (ArgTy->isVoidType())
461 return void_type_class;
462 else if (ArgTy->isEnumeralType())
463 return enumeral_type_class;
464 else if (ArgTy->isBooleanType())
465 return boolean_type_class;
466 else if (ArgTy->isCharType())
467 return string_type_class; // gcc doesn't appear to use char_type_class
468 else if (ArgTy->isIntegerType())
469 return integer_type_class;
470 else if (ArgTy->isPointerType())
471 return pointer_type_class;
472 else if (ArgTy->isReferenceType())
473 return reference_type_class;
474 else if (ArgTy->isRealType())
475 return real_type_class;
476 else if (ArgTy->isComplexType())
477 return complex_type_class;
478 else if (ArgTy->isFunctionType())
479 return function_type_class;
480 else if (ArgTy->isStructureType())
481 return record_type_class;
482 else if (ArgTy->isUnionType())
483 return union_type_class;
484 else if (ArgTy->isArrayType())
485 return array_type_class;
486 else if (ArgTy->isUnionType())
487 return union_type_class;
488 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
489 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
490 return -1;
491}
492
Chris Lattner4c4867e2008-07-12 00:38:25 +0000493bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
494 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner4c4867e2008-07-12 00:38:25 +0000495
Chris Lattner019f4e82008-10-06 05:28:25 +0000496 switch (E->isBuiltinCall()) {
497 default:
Chris Lattner32fea9d2008-11-12 07:43:42 +0000498 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner019f4e82008-10-06 05:28:25 +0000499 case Builtin::BI__builtin_classify_type:
Chris Lattnera4d55d82008-10-06 06:40:35 +0000500 Result.setIsSigned(true);
501 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000502 return true;
503
504 case Builtin::BI__builtin_constant_p: {
505 // __builtin_constant_p always has one operand: it returns true if that
506 // operand can be folded, false otherwise.
507 APValue Res;
508 Result = E->getArg(0)->tryEvaluate(Res, Info.Ctx);
509 return true;
510 }
511 }
Chris Lattner4c4867e2008-07-12 00:38:25 +0000512}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000513
Chris Lattnerb542afe2008-07-11 19:10:17 +0000514bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000515 if (E->getOpcode() == BinaryOperator::Comma) {
516 // Evaluate the side that actually matters; this needs to be
517 // handled specially because calling Visit() on the LHS can
518 // have strange results when it doesn't have an integral type.
519 Visit(E->getRHS());
520
521 // Check for isEvaluated; the idea is that this might eventually
522 // be useful for isICE and other similar uses that care about
523 // whether a comma is evaluated. This isn't really used yet, though,
524 // and I'm not sure it really works as intended.
525 if (!Info.isEvaluated)
526 return true;
527
528 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
529 }
530
531 if (E->isLogicalOp()) {
532 // These need to be handled specially because the operands aren't
533 // necessarily integral
534 bool bres;
535 if (!HandleConversionToBool(E->getLHS(), bres, Info)) {
536 // We can't evaluate the LHS; however, sometimes the result
537 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
538 if (HandleConversionToBool(E->getRHS(), bres, Info) &&
539 bres == (E->getOpcode() == BinaryOperator::LOr)) {
540 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
541 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
542 Result = bres;
543 return true;
544 }
545
546 // Really can't evaluate
547 return false;
548 }
549
550 bool bres2;
551 if (HandleConversionToBool(E->getRHS(), bres2, Info)) {
552 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
553 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
554 if (E->getOpcode() == BinaryOperator::LOr)
555 Result = bres || bres2;
556 else
557 Result = bres && bres2;
558 return true;
559 }
560 return false;
561 }
562
Anders Carlsson286f85e2008-11-16 07:17:21 +0000563 QualType LHSTy = E->getLHS()->getType();
564 QualType RHSTy = E->getRHS()->getType();
565
566 if (LHSTy->isRealFloatingType() &&
567 RHSTy->isRealFloatingType()) {
568 APFloat RHS(0.0), LHS(0.0);
569
570 if (!EvaluateFloat(E->getRHS(), RHS, Info))
571 return false;
572
573 if (!EvaluateFloat(E->getLHS(), LHS, Info))
574 return false;
575
576 APFloat::cmpResult CR = LHS.compare(RHS);
577
578 switch (E->getOpcode()) {
579 default:
580 assert(0 && "Invalid binary operator!");
581 case BinaryOperator::LT:
582 Result = CR == APFloat::cmpLessThan;
583 break;
584 case BinaryOperator::GT:
585 Result = CR == APFloat::cmpGreaterThan;
586 break;
587 case BinaryOperator::LE:
588 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
589 break;
590 case BinaryOperator::GE:
591 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
592 break;
593 case BinaryOperator::EQ:
594 Result = CR == APFloat::cmpEqual;
595 break;
596 case BinaryOperator::NE:
597 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
598 break;
599 }
600
601 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
602 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
603 return true;
604 }
605
Anders Carlsson3068d112008-11-16 19:01:22 +0000606 if (E->getOpcode() == BinaryOperator::Sub) {
607 if (LHSTy->isPointerType()) {
608 if (RHSTy->isIntegralType()) {
609 // pointer - int.
610 // FIXME: Implement.
611 }
612
613 assert(RHSTy->isPointerType() && "RHS not pointer!");
614
615 APValue LHSValue;
616 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
617 return false;
618
619 APValue RHSValue;
620 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
621 return false;
622
623 // FIXME: Is this correct? What if only one of the operands has a base?
624 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
625 return false;
626
627 const QualType Type = E->getLHS()->getType();
628 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
629
630 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
631 D /= Info.Ctx.getTypeSize(ElementType) / 8;
632
633 Result = D;
634 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
635 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
636
637 return true;
638 }
639 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000640 if (!LHSTy->isIntegralType() ||
641 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000642 // We can't continue from here for non-integral types, and they
643 // could potentially confuse the following operations.
644 // FIXME: Deal with EQ and friends.
645 return false;
646 }
647
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000648 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000649 llvm::APSInt RHS(32);
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000650 if (!Visit(E->getLHS())) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000651 return false; // error in subexpression.
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000652 }
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000653
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000654
655 // FIXME Maybe we want to succeed even where we can't evaluate the
656 // right side of LAnd/LOr?
657 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner54176fd2008-07-12 00:14:42 +0000658 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000659 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000660
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000661 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000662 default:
663 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000664 case BinaryOperator::Mul: Result *= RHS; return true;
665 case BinaryOperator::Add: Result += RHS; return true;
666 case BinaryOperator::Sub: Result -= RHS; return true;
667 case BinaryOperator::And: Result &= RHS; return true;
668 case BinaryOperator::Xor: Result ^= RHS; return true;
669 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner75a48812008-07-11 22:15:16 +0000670 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +0000671 if (RHS == 0)
Chris Lattner32fea9d2008-11-12 07:43:42 +0000672 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
673 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000674 Result /= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000675 break;
Chris Lattner75a48812008-07-11 22:15:16 +0000676 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +0000677 if (RHS == 0)
Chris Lattner32fea9d2008-11-12 07:43:42 +0000678 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
679 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000680 Result %= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000681 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000682 case BinaryOperator::Shl:
Chris Lattner54176fd2008-07-12 00:14:42 +0000683 // FIXME: Warn about out of range shift amounts!
Chris Lattnerb542afe2008-07-11 19:10:17 +0000684 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000685 break;
686 case BinaryOperator::Shr:
Chris Lattnerb542afe2008-07-11 19:10:17 +0000687 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000688 break;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000689
Chris Lattnerac7cb602008-07-11 19:29:32 +0000690 case BinaryOperator::LT:
691 Result = Result < RHS;
692 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
693 break;
694 case BinaryOperator::GT:
695 Result = Result > RHS;
696 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
697 break;
698 case BinaryOperator::LE:
699 Result = Result <= RHS;
700 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
701 break;
702 case BinaryOperator::GE:
703 Result = Result >= RHS;
704 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
705 break;
706 case BinaryOperator::EQ:
707 Result = Result == RHS;
708 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
709 break;
710 case BinaryOperator::NE:
711 Result = Result != RHS;
712 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
713 break;
Chris Lattner54176fd2008-07-12 00:14:42 +0000714 case BinaryOperator::LAnd:
715 Result = Result != 0 && RHS != 0;
716 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
717 break;
718 case BinaryOperator::LOr:
719 Result = Result != 0 || RHS != 0;
720 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
721 break;
Eli Friedmanb11e7782008-11-13 02:13:11 +0000722 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000723
724 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000725 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000726}
727
Sebastian Redl05189992008-11-11 17:56:53 +0000728/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
729/// expression's type.
730bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
731 QualType DstTy = E->getType();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000732 // Return the result in the right width.
733 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
734 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
735
Sebastian Redl05189992008-11-11 17:56:53 +0000736 QualType SrcTy = E->getTypeOfArgument();
737
Chris Lattnerfcee0012008-07-11 21:24:13 +0000738 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman4efaa272008-11-12 09:44:48 +0000739 if (SrcTy->isVoidType()) {
Chris Lattnerfcee0012008-07-11 21:24:13 +0000740 Result = 1;
Eli Friedman4efaa272008-11-12 09:44:48 +0000741 return true;
742 }
Chris Lattnerfcee0012008-07-11 21:24:13 +0000743
744 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman4efaa272008-11-12 09:44:48 +0000745 // FIXME: But alignof(vla) is!
Chris Lattnerfcee0012008-07-11 21:24:13 +0000746 if (!SrcTy->isConstantSizeType()) {
747 // FIXME: Should we attempt to evaluate this?
748 return false;
749 }
Sebastian Redl05189992008-11-11 17:56:53 +0000750
751 bool isSizeOf = E->isSizeOf();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000752
753 // GCC extension: sizeof(function) = 1.
754 if (SrcTy->isFunctionType()) {
755 // FIXME: AlignOf shouldn't be unconditionally 4!
756 Result = isSizeOf ? 1 : 4;
757 return true;
758 }
759
760 // Get information about the size or align.
Chris Lattner87eae5e2008-07-11 22:52:41 +0000761 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000762 if (isSizeOf)
Eli Friedman4efaa272008-11-12 09:44:48 +0000763 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000764 else
Chris Lattner87eae5e2008-07-11 22:52:41 +0000765 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000766 return true;
767}
768
Chris Lattnerb542afe2008-07-11 19:10:17 +0000769bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000770 // Special case unary operators that do not need their subexpression
771 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner75a48812008-07-11 22:15:16 +0000772 if (E->isOffsetOfOp()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000773 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner87eae5e2008-07-11 22:52:41 +0000774 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner75a48812008-07-11 22:15:16 +0000775 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
776 return true;
777 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000778
779 if (E->getOpcode() == UnaryOperator::LNot) {
780 // LNot's operand isn't necessarily an integer, so we handle it specially.
781 bool bres;
782 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
783 return false;
784 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
785 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
786 Result = !bres;
787 return true;
788 }
789
Chris Lattner87eae5e2008-07-11 22:52:41 +0000790 // Get the operand value into 'Result'.
791 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +0000792 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000793
Chris Lattner75a48812008-07-11 22:15:16 +0000794 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000795 default:
Chris Lattner75a48812008-07-11 22:15:16 +0000796 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
797 // See C99 6.6p3.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000798 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
799 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000800 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000801 // FIXME: Should extension allow i-c-e extension expressions in its scope?
802 // If so, we could clear the diagnostic ID.
Chris Lattner75a48812008-07-11 22:15:16 +0000803 case UnaryOperator::Plus:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000804 // The result is always just the subexpr.
Chris Lattner75a48812008-07-11 22:15:16 +0000805 break;
806 case UnaryOperator::Minus:
807 Result = -Result;
808 break;
809 case UnaryOperator::Not:
810 Result = ~Result;
811 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000812 }
813
814 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000815 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000816}
817
Chris Lattner732b2232008-07-12 01:15:53 +0000818/// HandleCast - This is used to evaluate implicit or explicit casts where the
819/// result type is integer.
820bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
821 Expr *SubExpr, QualType DestType) {
Chris Lattner7a767782008-07-11 19:24:49 +0000822 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000823
Eli Friedman4efaa272008-11-12 09:44:48 +0000824 if (DestType->isBooleanType()) {
825 bool BoolResult;
826 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
827 return false;
828 Result.zextOrTrunc(DestWidth);
829 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
830 Result = BoolResult;
831 return true;
832 }
833
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000834 // Handle simple integer->integer casts.
Eli Friedmana6afa762008-11-13 06:09:17 +0000835 if (SubExpr->getType()->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +0000836 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000837 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000838
839 // Figure out if this is a truncate, extend or noop cast.
840 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman4efaa272008-11-12 09:44:48 +0000841 Result.extOrTrunc(DestWidth);
Chris Lattner732b2232008-07-12 01:15:53 +0000842 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
843 return true;
844 }
845
846 // FIXME: Clean this up!
847 if (SubExpr->getType()->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000848 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000849 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000850 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000851
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000852 if (LV.getLValueBase())
Chris Lattnerb542afe2008-07-11 19:10:17 +0000853 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000854
Anders Carlsson559e56b2008-07-08 16:49:00 +0000855 Result.extOrTrunc(DestWidth);
856 Result = LV.getLValueOffset();
Chris Lattner732b2232008-07-12 01:15:53 +0000857 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
858 return true;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000859 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000860
Chris Lattner732b2232008-07-12 01:15:53 +0000861 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner32fea9d2008-11-12 07:43:42 +0000862 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattner732b2232008-07-12 01:15:53 +0000863
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000864 APFloat F(0.0);
865 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner32fea9d2008-11-12 07:43:42 +0000866 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattner732b2232008-07-12 01:15:53 +0000867
868 // Determine whether we are converting to unsigned or signed.
869 bool DestSigned = DestType->isSignedIntegerType();
870
871 // FIXME: Warning for overflow.
Dale Johannesenee5a7002008-10-09 23:02:32 +0000872 uint64_t Space[4];
873 bool ignored;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000874 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesenee5a7002008-10-09 23:02:32 +0000875 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattner732b2232008-07-12 01:15:53 +0000876 Result = llvm::APInt(DestWidth, 4, Space);
877 Result.setIsUnsigned(!DestSigned);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000878 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000879}
Anders Carlsson2bad1682008-07-08 14:30:00 +0000880
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000881//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000882// Float Evaluation
883//===----------------------------------------------------------------------===//
884
885namespace {
886class VISIBILITY_HIDDEN FloatExprEvaluator
887 : public StmtVisitor<FloatExprEvaluator, bool> {
888 EvalInfo &Info;
889 APFloat &Result;
890public:
891 FloatExprEvaluator(EvalInfo &info, APFloat &result)
892 : Info(info), Result(result) {}
893
894 bool VisitStmt(Stmt *S) {
895 return false;
896 }
897
898 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +0000899 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000900
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000901 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000902 bool VisitBinaryOperator(const BinaryOperator *E);
903 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000904 bool VisitCastExpr(CastExpr *E);
905 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000906};
907} // end anonymous namespace
908
909static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
910 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
911}
912
Chris Lattner019f4e82008-10-06 05:28:25 +0000913bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner019f4e82008-10-06 05:28:25 +0000914 switch (E->isBuiltinCall()) {
Chris Lattner34a74ab2008-10-06 05:53:16 +0000915 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +0000916 case Builtin::BI__builtin_huge_val:
917 case Builtin::BI__builtin_huge_valf:
918 case Builtin::BI__builtin_huge_vall:
919 case Builtin::BI__builtin_inf:
920 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000921 case Builtin::BI__builtin_infl: {
922 const llvm::fltSemantics &Sem =
923 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +0000924 Result = llvm::APFloat::getInf(Sem);
925 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000926 }
Chris Lattner9e621712008-10-06 06:31:58 +0000927
928 case Builtin::BI__builtin_nan:
929 case Builtin::BI__builtin_nanf:
930 case Builtin::BI__builtin_nanl:
931 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
932 // can't constant fold it.
933 if (const StringLiteral *S =
934 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
935 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000936 const llvm::fltSemantics &Sem =
937 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner9e621712008-10-06 06:31:58 +0000938 Result = llvm::APFloat::getNaN(Sem);
939 return true;
940 }
941 }
942 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000943
944 case Builtin::BI__builtin_fabs:
945 case Builtin::BI__builtin_fabsf:
946 case Builtin::BI__builtin_fabsl:
947 if (!EvaluateFloat(E->getArg(0), Result, Info))
948 return false;
949
950 if (Result.isNegative())
951 Result.changeSign();
952 return true;
953
954 case Builtin::BI__builtin_copysign:
955 case Builtin::BI__builtin_copysignf:
956 case Builtin::BI__builtin_copysignl: {
957 APFloat RHS(0.);
958 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
959 !EvaluateFloat(E->getArg(1), RHS, Info))
960 return false;
961 Result.copySign(RHS);
962 return true;
963 }
Chris Lattner019f4e82008-10-06 05:28:25 +0000964 }
965}
966
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000967bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
968 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
969 return false;
970
971 switch (E->getOpcode()) {
972 default: return false;
973 case UnaryOperator::Plus:
974 return true;
975 case UnaryOperator::Minus:
976 Result.changeSign();
977 return true;
978 }
979}
Chris Lattner019f4e82008-10-06 05:28:25 +0000980
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000981bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
982 // FIXME: Diagnostics? I really don't understand how the warnings
983 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000984 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000985 if (!EvaluateFloat(E->getLHS(), Result, Info))
986 return false;
987 if (!EvaluateFloat(E->getRHS(), RHS, Info))
988 return false;
989
990 switch (E->getOpcode()) {
991 default: return false;
992 case BinaryOperator::Mul:
993 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
994 return true;
995 case BinaryOperator::Add:
996 Result.add(RHS, APFloat::rmNearestTiesToEven);
997 return true;
998 case BinaryOperator::Sub:
999 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1000 return true;
1001 case BinaryOperator::Div:
1002 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1003 return true;
1004 case BinaryOperator::Rem:
1005 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1006 return true;
1007 }
1008}
1009
1010bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1011 Result = E->getValue();
1012 return true;
1013}
1014
Eli Friedman4efaa272008-11-12 09:44:48 +00001015bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1016 Expr* SubExpr = E->getSubExpr();
1017 const llvm::fltSemantics& destSemantics =
1018 Info.Ctx.getFloatTypeSemantics(E->getType());
1019 if (SubExpr->getType()->isIntegralType()) {
1020 APSInt IntResult;
1021 if (!EvaluateInteger(E, IntResult, Info))
1022 return false;
1023 Result = APFloat(destSemantics, 1);
1024 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1025 APFloat::rmNearestTiesToEven);
1026 return true;
1027 }
1028 if (SubExpr->getType()->isRealFloatingType()) {
1029 if (!Visit(SubExpr))
1030 return false;
1031 bool ignored;
1032 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1033 return true;
1034 }
1035
1036 return false;
1037}
1038
1039bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1040 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1041 return true;
1042}
1043
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001044//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001045// Top level TryEvaluate.
1046//===----------------------------------------------------------------------===//
1047
Chris Lattner019f4e82008-10-06 05:28:25 +00001048/// tryEvaluate - Return true if this is a constant which we can fold using
1049/// any crazy technique (that has nothing to do with language standards) that
1050/// we want to. If this function returns true, it returns the folded constant
1051/// in Result.
Chris Lattnerb542afe2008-07-11 19:10:17 +00001052bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner87eae5e2008-07-11 22:52:41 +00001053 EvalInfo Info(Ctx);
Anders Carlsson06a36752008-07-08 05:49:43 +00001054 if (getType()->isIntegerType()) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001055 llvm::APSInt sInt(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +00001056 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlsson06a36752008-07-08 05:49:43 +00001057 Result = APValue(sInt);
1058 return true;
1059 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001060 } else if (getType()->isPointerType()) {
1061 if (EvaluatePointer(this, Result, Info)) {
1062 return true;
1063 }
1064 } else if (getType()->isRealFloatingType()) {
1065 llvm::APFloat f(0.0);
1066 if (EvaluateFloat(this, f, Info)) {
1067 Result = APValue(f);
1068 return true;
1069 }
1070 }
Anders Carlsson165a70f2008-08-10 17:03:01 +00001071
Anders Carlssonc44eec62008-07-03 04:20:39 +00001072 return false;
1073}
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001074
1075/// isEvaluatable - Call tryEvaluate to see if this expression can be constant
1076/// folded, but discard the result.
1077bool Expr::isEvaluatable(ASTContext &Ctx) const {
1078 APValue V;
1079 return tryEvaluate(V, Ctx);
1080}