blob: bedc78c0c05d52895e709c53b9ae7a4a5a2d9adb [file] [log] [blame]
Chris Lattnera42f09a2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc7436af2008-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 Friedman7888b932008-11-12 09:44:48 +000016#include "clang/AST/RecordLayout.h"
Seo Sanghyeonefddb9c2008-07-08 07:23:12 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner82437da2008-07-12 00:14:42 +000018#include "clang/Basic/Diagnostic.h"
Anders Carlssonc0328012008-07-08 05:49:43 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssoncad17b52008-07-08 05:13:58 +000020#include "llvm/Support/Compiler.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000021using namespace clang;
Chris Lattnera823ccf2008-07-11 18:11:29 +000022using llvm::APSInt;
Eli Friedman2f445492008-08-22 00:06:13 +000023using llvm::APFloat;
Anders Carlssonc7436af2008-07-03 04:20:39 +000024
Chris Lattner422373c2008-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 Lattner82437da2008-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 Lattner422373c2008-07-11 22:52:41 +000053 ///
Chris Lattner82437da2008-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 Lattner422373c2008-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 Friedman7888b932008-11-12 09:44:48 +000066static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner422373c2008-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 Friedman2f445492008-08-22 00:06:13 +000069static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Chris Lattnera823ccf2008-07-11 18:11:29 +000070
71//===----------------------------------------------------------------------===//
Eli Friedman7888b932008-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 Dunbarff59ed82008-11-12 21:52:46 +0000113#if 0
Eli Friedman7888b932008-11-12 09:44:48 +0000114 // FIXME: Remove this when we support more expressions.
115 printf("Unhandled pointer statement\n");
116 S->dump();
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000117#endif
Eli Friedman7888b932008-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 Carlsson027f2882008-11-16 19:01:22 +0000127 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman7888b932008-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 Carlsson027f2882008-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 Friedman7888b932008-11-12 09:44:48 +0000191
192//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000193// Pointer Evaluation
194//===----------------------------------------------------------------------===//
195
Anders Carlssoncad17b52008-07-08 05:13:58 +0000196namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000197class VISIBILITY_HIDDEN PointerExprEvaluator
198 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000199 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000200public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000201
Chris Lattner422373c2008-07-11 22:52:41 +0000202 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000203
Anders Carlsson02a34c32008-07-08 14:30:00 +0000204 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000205 return APValue();
206 }
207
208 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
209
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000210 APValue VisitBinaryOperator(const BinaryOperator *E);
211 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-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 Carlssonc43f44b2008-07-08 15:34:11 +0000216};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000217} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000218
Chris Lattner422373c2008-07-11 22:52:41 +0000219static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000220 if (!E->getType()->isPointerType())
221 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000222 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-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 Lattner422373c2008-07-11 22:52:41 +0000237 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000238 return APValue();
239
240 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000241 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000242 return APValue();
243
Eli Friedman7888b932008-11-12 09:44:48 +0000244 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
245 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
246
Chris Lattnera823ccf2008-07-11 18:11:29 +0000247 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000248
Chris Lattnera823ccf2008-07-11 18:11:29 +0000249 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000250 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000251 else
Eli Friedman7888b932008-11-12 09:44:48 +0000252 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
253
Chris Lattnera823ccf2008-07-11 18:11:29 +0000254 return APValue(ResultLValue.getLValueBase(), Offset);
255}
Eli Friedman7888b932008-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 Lattnera823ccf2008-07-11 18:11:29 +0000271
272
Chris Lattnera42f09a2008-07-11 19:10:17 +0000273APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-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 Lattner422373c2008-07-11 22:52:41 +0000279 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000280 return Result;
281 return APValue();
282 }
283
Eli Friedman3e64dd72008-07-27 05:46:18 +0000284 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000285 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000286 if (EvaluateInteger(SubExpr, Result, Info)) {
287 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000288 return APValue(0, Result.getZExtValue());
289 }
290 }
Eli Friedman7888b932008-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 Lattnera823ccf2008-07-11 18:11:29 +0000301 return APValue();
302}
303
Eli Friedman7888b932008-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 Lattnera823ccf2008-07-11 18:11:29 +0000316
317//===----------------------------------------------------------------------===//
318// Integer Evaluation
319//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000320
321namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000322class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000323 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000324 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000325 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000326public:
Chris Lattner422373c2008-07-11 22:52:41 +0000327 IntExprEvaluator(EvalInfo &info, APSInt &result)
328 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000329
Chris Lattner2c99c712008-07-11 19:24:49 +0000330 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner82437da2008-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 Lattner438f3b12008-11-12 07:43:42 +0000340 bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
Chris Lattner82437da2008-07-12 00:14:42 +0000341 // If this is in an unevaluated portion of the subexpression, ignore the
342 // error.
Chris Lattner438f3b12008-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 Lattner82437da2008-07-12 00:14:42 +0000348 return true;
Chris Lattner438f3b12008-11-12 07:43:42 +0000349 }
Chris Lattner82437da2008-07-12 00:14:42 +0000350
Chris Lattner438f3b12008-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 Lattner82437da2008-07-12 00:14:42 +0000356 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000357 }
358
Anders Carlssoncad17b52008-07-08 05:13:58 +0000359 //===--------------------------------------------------------------------===//
360 // Visitor Methods
361 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-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 Lattner2c99c712008-07-11 19:24:49 +0000367
Chris Lattner438f3b12008-11-12 07:43:42 +0000368 bool VisitExpr(Expr *E) {
369 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Anders Carlssoncad17b52008-07-08 05:13:58 +0000370 }
371
Chris Lattnera42f09a2008-07-11 19:10:17 +0000372 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000373
Chris Lattner15e59112008-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 Dunbarda8ebd22008-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 Lattner15e59112008-07-12 00:38:25 +0000394 return true;
395 }
396 bool VisitDeclRefExpr(const DeclRefExpr *E);
397 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000398 bool VisitBinaryOperator(const BinaryOperator *E);
399 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000400 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000401
Chris Lattnerff579ff2008-07-12 01:15:53 +0000402 bool VisitCastExpr(CastExpr* E) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000403 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000404 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000405 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
406
Anders Carlsson027f2882008-11-16 19:01:22 +0000407 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
408 Result = E->getValue();
409 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
410 return true;
411 }
412
413 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
414 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
415 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
416 return true;
417 }
418
Chris Lattner265a0892008-07-11 21:24:13 +0000419private:
Chris Lattnerff579ff2008-07-12 01:15:53 +0000420 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000421};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000422} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000423
Chris Lattner422373c2008-07-11 22:52:41 +0000424static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
425 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000426}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000427
Chris Lattner15e59112008-07-12 00:38:25 +0000428bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
429 // Enums are integer constant exprs.
430 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
431 Result = D->getInitVal();
432 return true;
433 }
434
435 // Otherwise, random variable references are not constants.
Chris Lattner438f3b12008-11-12 07:43:42 +0000436 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner15e59112008-07-12 00:38:25 +0000437}
438
Chris Lattner1eee9402008-10-06 06:40:35 +0000439/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
440/// as GCC.
441static int EvaluateBuiltinClassifyType(const CallExpr *E) {
442 // The following enum mimics the values returned by GCC.
443 enum gcc_type_class {
444 no_type_class = -1,
445 void_type_class, integer_type_class, char_type_class,
446 enumeral_type_class, boolean_type_class,
447 pointer_type_class, reference_type_class, offset_type_class,
448 real_type_class, complex_type_class,
449 function_type_class, method_type_class,
450 record_type_class, union_type_class,
451 array_type_class, string_type_class,
452 lang_type_class
453 };
454
455 // If no argument was supplied, default to "no_type_class". This isn't
456 // ideal, however it is what gcc does.
457 if (E->getNumArgs() == 0)
458 return no_type_class;
459
460 QualType ArgTy = E->getArg(0)->getType();
461 if (ArgTy->isVoidType())
462 return void_type_class;
463 else if (ArgTy->isEnumeralType())
464 return enumeral_type_class;
465 else if (ArgTy->isBooleanType())
466 return boolean_type_class;
467 else if (ArgTy->isCharType())
468 return string_type_class; // gcc doesn't appear to use char_type_class
469 else if (ArgTy->isIntegerType())
470 return integer_type_class;
471 else if (ArgTy->isPointerType())
472 return pointer_type_class;
473 else if (ArgTy->isReferenceType())
474 return reference_type_class;
475 else if (ArgTy->isRealType())
476 return real_type_class;
477 else if (ArgTy->isComplexType())
478 return complex_type_class;
479 else if (ArgTy->isFunctionType())
480 return function_type_class;
481 else if (ArgTy->isStructureType())
482 return record_type_class;
483 else if (ArgTy->isUnionType())
484 return union_type_class;
485 else if (ArgTy->isArrayType())
486 return array_type_class;
487 else if (ArgTy->isUnionType())
488 return union_type_class;
489 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
490 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
491 return -1;
492}
493
Chris Lattner15e59112008-07-12 00:38:25 +0000494bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
495 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000496
Chris Lattner87293782008-10-06 05:28:25 +0000497 switch (E->isBuiltinCall()) {
498 default:
Chris Lattner438f3b12008-11-12 07:43:42 +0000499 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner87293782008-10-06 05:28:25 +0000500 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000501 Result.setIsSigned(true);
502 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-10-06 05:28:25 +0000503 return true;
504
505 case Builtin::BI__builtin_constant_p: {
506 // __builtin_constant_p always has one operand: it returns true if that
507 // operand can be folded, false otherwise.
508 APValue Res;
509 Result = E->getArg(0)->tryEvaluate(Res, Info.Ctx);
510 return true;
511 }
512 }
Chris Lattner15e59112008-07-12 00:38:25 +0000513}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000514
Chris Lattnera42f09a2008-07-11 19:10:17 +0000515bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000516 if (E->getOpcode() == BinaryOperator::Comma) {
517 // Evaluate the side that actually matters; this needs to be
518 // handled specially because calling Visit() on the LHS can
519 // have strange results when it doesn't have an integral type.
520 Visit(E->getRHS());
521
522 // Check for isEvaluated; the idea is that this might eventually
523 // be useful for isICE and other similar uses that care about
524 // whether a comma is evaluated. This isn't really used yet, though,
525 // and I'm not sure it really works as intended.
526 if (!Info.isEvaluated)
527 return true;
528
529 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
530 }
531
532 if (E->isLogicalOp()) {
533 // These need to be handled specially because the operands aren't
534 // necessarily integral
535 bool bres;
536 if (!HandleConversionToBool(E->getLHS(), bres, Info)) {
537 // We can't evaluate the LHS; however, sometimes the result
538 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
539 if (HandleConversionToBool(E->getRHS(), bres, Info) &&
540 bres == (E->getOpcode() == BinaryOperator::LOr)) {
541 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
542 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
543 Result = bres;
544 return true;
545 }
546
547 // Really can't evaluate
548 return false;
549 }
550
551 bool bres2;
552 if (HandleConversionToBool(E->getRHS(), bres2, Info)) {
553 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
554 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
555 if (E->getOpcode() == BinaryOperator::LOr)
556 Result = bres || bres2;
557 else
558 Result = bres && bres2;
559 return true;
560 }
561 return false;
562 }
563
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000564 QualType LHSTy = E->getLHS()->getType();
565 QualType RHSTy = E->getRHS()->getType();
566
567 if (LHSTy->isRealFloatingType() &&
568 RHSTy->isRealFloatingType()) {
569 APFloat RHS(0.0), LHS(0.0);
570
571 if (!EvaluateFloat(E->getRHS(), RHS, Info))
572 return false;
573
574 if (!EvaluateFloat(E->getLHS(), LHS, Info))
575 return false;
576
577 APFloat::cmpResult CR = LHS.compare(RHS);
578
579 switch (E->getOpcode()) {
580 default:
581 assert(0 && "Invalid binary operator!");
582 case BinaryOperator::LT:
583 Result = CR == APFloat::cmpLessThan;
584 break;
585 case BinaryOperator::GT:
586 Result = CR == APFloat::cmpGreaterThan;
587 break;
588 case BinaryOperator::LE:
589 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
590 break;
591 case BinaryOperator::GE:
592 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
593 break;
594 case BinaryOperator::EQ:
595 Result = CR == APFloat::cmpEqual;
596 break;
597 case BinaryOperator::NE:
598 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
599 break;
600 }
601
602 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
603 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
604 return true;
605 }
606
Anders Carlsson027f2882008-11-16 19:01:22 +0000607 if (E->getOpcode() == BinaryOperator::Sub) {
608 if (LHSTy->isPointerType()) {
609 if (RHSTy->isIntegralType()) {
610 // pointer - int.
611 // FIXME: Implement.
612 }
613
614 assert(RHSTy->isPointerType() && "RHS not pointer!");
615
616 APValue LHSValue;
617 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
618 return false;
619
620 APValue RHSValue;
621 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
622 return false;
623
624 // FIXME: Is this correct? What if only one of the operands has a base?
625 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
626 return false;
627
628 const QualType Type = E->getLHS()->getType();
629 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
630
631 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
632 D /= Info.Ctx.getTypeSize(ElementType) / 8;
633
634 Result = D;
635 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
636 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
637
638 return true;
639 }
640 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000641 if (!LHSTy->isIntegralType() ||
642 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000643 // We can't continue from here for non-integral types, and they
644 // could potentially confuse the following operations.
645 // FIXME: Deal with EQ and friends.
646 return false;
647 }
648
Anders Carlssond1aa5812008-07-08 14:35:21 +0000649 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000650 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000651 if (!Visit(E->getLHS())) {
Chris Lattner82437da2008-07-12 00:14:42 +0000652 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000653 }
Eli Friedman3e64dd72008-07-27 05:46:18 +0000654
Eli Friedman3e64dd72008-07-27 05:46:18 +0000655
656 // FIXME Maybe we want to succeed even where we can't evaluate the
657 // right side of LAnd/LOr?
658 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000659 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000660 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000661
Anders Carlssond1aa5812008-07-08 14:35:21 +0000662 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000663 default:
664 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner82437da2008-07-12 00:14:42 +0000665 case BinaryOperator::Mul: Result *= RHS; return true;
666 case BinaryOperator::Add: Result += RHS; return true;
667 case BinaryOperator::Sub: Result -= RHS; return true;
668 case BinaryOperator::And: Result &= RHS; return true;
669 case BinaryOperator::Xor: Result ^= RHS; return true;
670 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000671 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000672 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000673 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
674 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000675 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000676 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000677 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000678 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000679 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
680 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000681 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000682 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000683 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000684 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000685 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000686 break;
687 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000688 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000689 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000690
Chris Lattner045502c2008-07-11 19:29:32 +0000691 case BinaryOperator::LT:
692 Result = Result < RHS;
693 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
694 break;
695 case BinaryOperator::GT:
696 Result = Result > RHS;
697 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
698 break;
699 case BinaryOperator::LE:
700 Result = Result <= RHS;
701 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
702 break;
703 case BinaryOperator::GE:
704 Result = Result >= RHS;
705 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
706 break;
707 case BinaryOperator::EQ:
708 Result = Result == RHS;
709 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
710 break;
711 case BinaryOperator::NE:
712 Result = Result != RHS;
713 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
714 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000715 case BinaryOperator::LAnd:
716 Result = Result != 0 && RHS != 0;
717 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
718 break;
719 case BinaryOperator::LOr:
720 Result = Result != 0 || RHS != 0;
721 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
722 break;
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000723 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000724
725 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000726 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000727}
728
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000729bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
730 llvm::APSInt Cond(32);
731 if (!EvaluateInteger(E->getCond(), Cond, Info))
732 return false;
733
734 return Visit(Cond != 0 ? E->getTrueExpr() : E->getFalseExpr());
735}
736
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000737/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
738/// expression's type.
739bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
740 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000741 // Return the result in the right width.
742 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
743 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
744
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000745 QualType SrcTy = E->getTypeOfArgument();
746
Chris Lattner265a0892008-07-11 21:24:13 +0000747 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +0000748 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +0000749 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +0000750 return true;
751 }
Chris Lattner265a0892008-07-11 21:24:13 +0000752
753 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman7888b932008-11-12 09:44:48 +0000754 // FIXME: But alignof(vla) is!
Chris Lattner265a0892008-07-11 21:24:13 +0000755 if (!SrcTy->isConstantSizeType()) {
756 // FIXME: Should we attempt to evaluate this?
757 return false;
758 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000759
760 bool isSizeOf = E->isSizeOf();
Chris Lattner265a0892008-07-11 21:24:13 +0000761
762 // GCC extension: sizeof(function) = 1.
763 if (SrcTy->isFunctionType()) {
764 // FIXME: AlignOf shouldn't be unconditionally 4!
765 Result = isSizeOf ? 1 : 4;
766 return true;
767 }
768
769 // Get information about the size or align.
Chris Lattner422373c2008-07-11 22:52:41 +0000770 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattner265a0892008-07-11 21:24:13 +0000771 if (isSizeOf)
Eli Friedman7888b932008-11-12 09:44:48 +0000772 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000773 else
Chris Lattner422373c2008-07-11 22:52:41 +0000774 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000775 return true;
776}
777
Chris Lattnera42f09a2008-07-11 19:10:17 +0000778bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000779 // Special case unary operators that do not need their subexpression
780 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +0000781 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000782 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +0000783 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +0000784 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
785 return true;
786 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000787
788 if (E->getOpcode() == UnaryOperator::LNot) {
789 // LNot's operand isn't necessarily an integer, so we handle it specially.
790 bool bres;
791 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
792 return false;
793 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
794 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
795 Result = !bres;
796 return true;
797 }
798
Chris Lattner422373c2008-07-11 22:52:41 +0000799 // Get the operand value into 'Result'.
800 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000801 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000802
Chris Lattner400d7402008-07-11 22:15:16 +0000803 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000804 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000805 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
806 // See C99 6.6p3.
Chris Lattner438f3b12008-11-12 07:43:42 +0000807 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
808 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000809 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +0000810 // FIXME: Should extension allow i-c-e extension expressions in its scope?
811 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +0000812 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +0000813 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +0000814 break;
815 case UnaryOperator::Minus:
816 Result = -Result;
817 break;
818 case UnaryOperator::Not:
819 Result = ~Result;
820 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000821 }
822
823 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000824 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000825}
826
Chris Lattnerff579ff2008-07-12 01:15:53 +0000827/// HandleCast - This is used to evaluate implicit or explicit casts where the
828/// result type is integer.
829bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
830 Expr *SubExpr, QualType DestType) {
Chris Lattner2c99c712008-07-11 19:24:49 +0000831 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000832
Eli Friedman7888b932008-11-12 09:44:48 +0000833 if (DestType->isBooleanType()) {
834 bool BoolResult;
835 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
836 return false;
837 Result.zextOrTrunc(DestWidth);
838 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
839 Result = BoolResult;
840 return true;
841 }
842
Anders Carlssond1aa5812008-07-08 14:35:21 +0000843 // Handle simple integer->integer casts.
Eli Friedman14cc7542008-11-13 06:09:17 +0000844 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000845 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000846 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000847
848 // Figure out if this is a truncate, extend or noop cast.
849 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman7888b932008-11-12 09:44:48 +0000850 Result.extOrTrunc(DestWidth);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000851 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
852 return true;
853 }
854
855 // FIXME: Clean this up!
856 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000857 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +0000858 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000859 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000860
Anders Carlssond1aa5812008-07-08 14:35:21 +0000861 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +0000862 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000863
Anders Carlsson8ab15c82008-07-08 16:49:00 +0000864 Result.extOrTrunc(DestWidth);
865 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +0000866 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
867 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000868 }
Eli Friedman7888b932008-11-12 09:44:48 +0000869
Chris Lattnerff579ff2008-07-12 01:15:53 +0000870 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner438f3b12008-11-12 07:43:42 +0000871 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000872
Eli Friedman2f445492008-08-22 00:06:13 +0000873 APFloat F(0.0);
874 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner438f3b12008-11-12 07:43:42 +0000875 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000876
877 // Determine whether we are converting to unsigned or signed.
878 bool DestSigned = DestType->isSignedIntegerType();
879
880 // FIXME: Warning for overflow.
Dale Johannesen2461f612008-10-09 23:02:32 +0000881 uint64_t Space[4];
882 bool ignored;
Eli Friedman2f445492008-08-22 00:06:13 +0000883 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesen2461f612008-10-09 23:02:32 +0000884 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000885 Result = llvm::APInt(DestWidth, 4, Space);
886 Result.setIsUnsigned(!DestSigned);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000887 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000888}
Anders Carlsson02a34c32008-07-08 14:30:00 +0000889
Chris Lattnera823ccf2008-07-11 18:11:29 +0000890//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +0000891// Float Evaluation
892//===----------------------------------------------------------------------===//
893
894namespace {
895class VISIBILITY_HIDDEN FloatExprEvaluator
896 : public StmtVisitor<FloatExprEvaluator, bool> {
897 EvalInfo &Info;
898 APFloat &Result;
899public:
900 FloatExprEvaluator(EvalInfo &info, APFloat &result)
901 : Info(info), Result(result) {}
902
903 bool VisitStmt(Stmt *S) {
904 return false;
905 }
906
907 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +0000908 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000909
Daniel Dunbar804ead02008-10-16 03:51:50 +0000910 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000911 bool VisitBinaryOperator(const BinaryOperator *E);
912 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000913 bool VisitCastExpr(CastExpr *E);
914 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000915};
916} // end anonymous namespace
917
918static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
919 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
920}
921
Chris Lattner87293782008-10-06 05:28:25 +0000922bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner87293782008-10-06 05:28:25 +0000923 switch (E->isBuiltinCall()) {
Chris Lattner27cde262008-10-06 05:53:16 +0000924 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +0000925 case Builtin::BI__builtin_huge_val:
926 case Builtin::BI__builtin_huge_valf:
927 case Builtin::BI__builtin_huge_vall:
928 case Builtin::BI__builtin_inf:
929 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000930 case Builtin::BI__builtin_infl: {
931 const llvm::fltSemantics &Sem =
932 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +0000933 Result = llvm::APFloat::getInf(Sem);
934 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000935 }
Chris Lattner667e1ee2008-10-06 06:31:58 +0000936
937 case Builtin::BI__builtin_nan:
938 case Builtin::BI__builtin_nanf:
939 case Builtin::BI__builtin_nanl:
940 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
941 // can't constant fold it.
942 if (const StringLiteral *S =
943 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
944 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000945 const llvm::fltSemantics &Sem =
946 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +0000947 Result = llvm::APFloat::getNaN(Sem);
948 return true;
949 }
950 }
951 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +0000952
953 case Builtin::BI__builtin_fabs:
954 case Builtin::BI__builtin_fabsf:
955 case Builtin::BI__builtin_fabsl:
956 if (!EvaluateFloat(E->getArg(0), Result, Info))
957 return false;
958
959 if (Result.isNegative())
960 Result.changeSign();
961 return true;
962
963 case Builtin::BI__builtin_copysign:
964 case Builtin::BI__builtin_copysignf:
965 case Builtin::BI__builtin_copysignl: {
966 APFloat RHS(0.);
967 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
968 !EvaluateFloat(E->getArg(1), RHS, Info))
969 return false;
970 Result.copySign(RHS);
971 return true;
972 }
Chris Lattner87293782008-10-06 05:28:25 +0000973 }
974}
975
Daniel Dunbar804ead02008-10-16 03:51:50 +0000976bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
977 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
978 return false;
979
980 switch (E->getOpcode()) {
981 default: return false;
982 case UnaryOperator::Plus:
983 return true;
984 case UnaryOperator::Minus:
985 Result.changeSign();
986 return true;
987 }
988}
Chris Lattner87293782008-10-06 05:28:25 +0000989
Eli Friedman2f445492008-08-22 00:06:13 +0000990bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
991 // FIXME: Diagnostics? I really don't understand how the warnings
992 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +0000993 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +0000994 if (!EvaluateFloat(E->getLHS(), Result, Info))
995 return false;
996 if (!EvaluateFloat(E->getRHS(), RHS, Info))
997 return false;
998
999 switch (E->getOpcode()) {
1000 default: return false;
1001 case BinaryOperator::Mul:
1002 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1003 return true;
1004 case BinaryOperator::Add:
1005 Result.add(RHS, APFloat::rmNearestTiesToEven);
1006 return true;
1007 case BinaryOperator::Sub:
1008 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1009 return true;
1010 case BinaryOperator::Div:
1011 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1012 return true;
1013 case BinaryOperator::Rem:
1014 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1015 return true;
1016 }
1017}
1018
1019bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1020 Result = E->getValue();
1021 return true;
1022}
1023
Eli Friedman7888b932008-11-12 09:44:48 +00001024bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1025 Expr* SubExpr = E->getSubExpr();
1026 const llvm::fltSemantics& destSemantics =
1027 Info.Ctx.getFloatTypeSemantics(E->getType());
1028 if (SubExpr->getType()->isIntegralType()) {
1029 APSInt IntResult;
1030 if (!EvaluateInteger(E, IntResult, Info))
1031 return false;
1032 Result = APFloat(destSemantics, 1);
1033 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1034 APFloat::rmNearestTiesToEven);
1035 return true;
1036 }
1037 if (SubExpr->getType()->isRealFloatingType()) {
1038 if (!Visit(SubExpr))
1039 return false;
1040 bool ignored;
1041 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1042 return true;
1043 }
1044
1045 return false;
1046}
1047
1048bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1049 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1050 return true;
1051}
1052
Eli Friedman2f445492008-08-22 00:06:13 +00001053//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +00001054// Top level TryEvaluate.
1055//===----------------------------------------------------------------------===//
1056
Chris Lattner87293782008-10-06 05:28:25 +00001057/// tryEvaluate - Return true if this is a constant which we can fold using
1058/// any crazy technique (that has nothing to do with language standards) that
1059/// we want to. If this function returns true, it returns the folded constant
1060/// in Result.
Chris Lattnera42f09a2008-07-11 19:10:17 +00001061bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner422373c2008-07-11 22:52:41 +00001062 EvalInfo Info(Ctx);
Anders Carlssonc0328012008-07-08 05:49:43 +00001063 if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +00001064 llvm::APSInt sInt(32);
Chris Lattner422373c2008-07-11 22:52:41 +00001065 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlssonc0328012008-07-08 05:49:43 +00001066 Result = APValue(sInt);
1067 return true;
1068 }
Eli Friedman2f445492008-08-22 00:06:13 +00001069 } else if (getType()->isPointerType()) {
1070 if (EvaluatePointer(this, Result, Info)) {
1071 return true;
1072 }
1073 } else if (getType()->isRealFloatingType()) {
1074 llvm::APFloat f(0.0);
1075 if (EvaluateFloat(this, f, Info)) {
1076 Result = APValue(f);
1077 return true;
1078 }
1079 }
Anders Carlsson47968a92008-08-10 17:03:01 +00001080
Anders Carlssonc7436af2008-07-03 04:20:39 +00001081 return false;
1082}
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001083
1084/// isEvaluatable - Call tryEvaluate to see if this expression can be constant
1085/// folded, but discard the result.
1086bool Expr::isEvaluatable(ASTContext &Ctx) const {
1087 APValue V;
1088 return tryEvaluate(V, Ctx);
1089}