blob: 2b7a6468860fb131d145fa10ba447184d2cce7d4 [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
Anders Carlssondd8d41f2008-11-30 16:38:33 +000042 /// EvalResult - Contains information about the evaluation.
43 Expr::EvalResult &EvalResult;
44
Chris Lattner422373c2008-07-11 22:52:41 +000045 /// isEvaluated - True if the subexpression is required to be evaluated, false
46 /// if it is short-circuited (according to C rules).
47 bool isEvaluated;
Chris Lattner422373c2008-07-11 22:52:41 +000048
Anders Carlssondd8d41f2008-11-30 16:38:33 +000049 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx),
50 EvalResult(evalresult), isEvaluated(true) {}
Chris Lattner422373c2008-07-11 22:52:41 +000051};
52
53
Eli Friedman7888b932008-11-12 09:44:48 +000054static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner422373c2008-07-11 22:52:41 +000055static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
56static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Eli Friedman2f445492008-08-22 00:06:13 +000057static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Anders Carlssonf1bb2962008-11-16 20:27:53 +000058static bool EvaluateComplexFloat(const Expr *E, APValue &Result,
59 EvalInfo &Info);
Chris Lattnera823ccf2008-07-11 18:11:29 +000060
61//===----------------------------------------------------------------------===//
Eli Friedman7888b932008-11-12 09:44:48 +000062// Misc utilities
63//===----------------------------------------------------------------------===//
64
65static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
66 if (E->getType()->isIntegralType()) {
67 APSInt IntResult;
68 if (!EvaluateInteger(E, IntResult, Info))
69 return false;
70 Result = IntResult != 0;
71 return true;
72 } else if (E->getType()->isRealFloatingType()) {
73 APFloat FloatResult(0.0);
74 if (!EvaluateFloat(E, FloatResult, Info))
75 return false;
76 Result = !FloatResult.isZero();
77 return true;
78 } else if (E->getType()->isPointerType()) {
79 APValue PointerResult;
80 if (!EvaluatePointer(E, PointerResult, Info))
81 return false;
82 // FIXME: Is this accurate for all kinds of bases? If not, what would
83 // the check look like?
84 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
85 return true;
86 }
87
88 return false;
89}
90
91//===----------------------------------------------------------------------===//
92// LValue Evaluation
93//===----------------------------------------------------------------------===//
94namespace {
95class VISIBILITY_HIDDEN LValueExprEvaluator
96 : public StmtVisitor<LValueExprEvaluator, APValue> {
97 EvalInfo &Info;
98public:
99
100 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
101
102 APValue VisitStmt(Stmt *S) {
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000103#if 0
Eli Friedman7888b932008-11-12 09:44:48 +0000104 // FIXME: Remove this when we support more expressions.
105 printf("Unhandled pointer statement\n");
106 S->dump();
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000107#endif
Eli Friedman7888b932008-11-12 09:44:48 +0000108 return APValue();
109 }
110
111 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssone284ebe2008-11-24 04:41:22 +0000112 APValue VisitDeclRefExpr(DeclRefExpr *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000113 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
114 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
115 APValue VisitMemberExpr(MemberExpr *E);
116 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
Anders Carlsson027f2882008-11-16 19:01:22 +0000117 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000118};
119} // end anonymous namespace
120
121static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
122 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
123 return Result.isLValue();
124}
125
Anders Carlssone284ebe2008-11-24 04:41:22 +0000126APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
127{
128 if (!E->hasGlobalStorage())
129 return APValue();
130
131 return APValue(E, 0);
132}
133
Eli Friedman7888b932008-11-12 09:44:48 +0000134APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
135 if (E->isFileScope())
136 return APValue(E, 0);
137 return APValue();
138}
139
140APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
141 APValue result;
142 QualType Ty;
143 if (E->isArrow()) {
144 if (!EvaluatePointer(E->getBase(), result, Info))
145 return APValue();
146 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
147 } else {
148 result = Visit(E->getBase());
149 if (result.isUninit())
150 return APValue();
151 Ty = E->getBase()->getType();
152 }
153
154 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
155 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
156 FieldDecl *FD = E->getMemberDecl();
157
158 // FIXME: This is linear time.
159 unsigned i = 0, e = 0;
160 for (i = 0, e = RD->getNumMembers(); i != e; i++) {
161 if (RD->getMember(i) == FD)
162 break;
163 }
164
165 result.setLValue(result.getLValueBase(),
166 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
167
168 return result;
169}
170
Anders Carlsson027f2882008-11-16 19:01:22 +0000171APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
172{
173 APValue Result;
174
175 if (!EvaluatePointer(E->getBase(), Result, Info))
176 return APValue();
177
178 APSInt Index;
179 if (!EvaluateInteger(E->getIdx(), Index, Info))
180 return APValue();
181
182 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
183
184 uint64_t Offset = Index.getSExtValue() * ElementSize;
185 Result.setLValue(Result.getLValueBase(),
186 Result.getLValueOffset() + Offset);
187 return Result;
188}
Eli Friedman7888b932008-11-12 09:44:48 +0000189
190//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000191// Pointer Evaluation
192//===----------------------------------------------------------------------===//
193
Anders Carlssoncad17b52008-07-08 05:13:58 +0000194namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000195class VISIBILITY_HIDDEN PointerExprEvaluator
196 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000197 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000198public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000199
Chris Lattner422373c2008-07-11 22:52:41 +0000200 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000201
Anders Carlsson02a34c32008-07-08 14:30:00 +0000202 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000203 return APValue();
204 }
205
206 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
207
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000208 APValue VisitBinaryOperator(const BinaryOperator *E);
209 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-11-12 09:44:48 +0000210 APValue VisitUnaryOperator(const UnaryOperator *E);
211 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
212 { return APValue(E, 0); }
213 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000214};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000215} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000216
Chris Lattner422373c2008-07-11 22:52:41 +0000217static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000218 if (!E->getType()->isPointerType())
219 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000220 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000221 return Result.isLValue();
222}
223
224APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
225 if (E->getOpcode() != BinaryOperator::Add &&
226 E->getOpcode() != BinaryOperator::Sub)
227 return APValue();
228
229 const Expr *PExp = E->getLHS();
230 const Expr *IExp = E->getRHS();
231 if (IExp->getType()->isPointerType())
232 std::swap(PExp, IExp);
233
234 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000235 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000236 return APValue();
237
238 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000239 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000240 return APValue();
241
Eli Friedman7888b932008-11-12 09:44:48 +0000242 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
243 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
244
Chris Lattnera823ccf2008-07-11 18:11:29 +0000245 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000246
Chris Lattnera823ccf2008-07-11 18:11:29 +0000247 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000248 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000249 else
Eli Friedman7888b932008-11-12 09:44:48 +0000250 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
251
Chris Lattnera823ccf2008-07-11 18:11:29 +0000252 return APValue(ResultLValue.getLValueBase(), Offset);
253}
Eli Friedman7888b932008-11-12 09:44:48 +0000254
255APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
256 if (E->getOpcode() == UnaryOperator::Extension) {
257 // FIXME: Deal with warnings?
258 return Visit(E->getSubExpr());
259 }
260
261 if (E->getOpcode() == UnaryOperator::AddrOf) {
262 APValue result;
263 if (EvaluateLValue(E->getSubExpr(), result, Info))
264 return result;
265 }
266
267 return APValue();
268}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000269
270
Chris Lattnera42f09a2008-07-11 19:10:17 +0000271APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000272 const Expr* SubExpr = E->getSubExpr();
273
274 // Check for pointer->pointer cast
275 if (SubExpr->getType()->isPointerType()) {
276 APValue Result;
Chris Lattner422373c2008-07-11 22:52:41 +0000277 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000278 return Result;
279 return APValue();
280 }
281
Eli Friedman3e64dd72008-07-27 05:46:18 +0000282 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000283 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000284 if (EvaluateInteger(SubExpr, Result, Info)) {
285 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000286 return APValue(0, Result.getZExtValue());
287 }
288 }
Eli Friedman7888b932008-11-12 09:44:48 +0000289
290 if (SubExpr->getType()->isFunctionType() ||
291 SubExpr->getType()->isArrayType()) {
292 APValue Result;
293 if (EvaluateLValue(SubExpr, Result, Info))
294 return Result;
295 return APValue();
296 }
297
298 //assert(0 && "Unhandled cast");
Chris Lattnera823ccf2008-07-11 18:11:29 +0000299 return APValue();
300}
301
Eli Friedman7888b932008-11-12 09:44:48 +0000302APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
303 bool BoolResult;
304 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
305 return APValue();
306
307 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
308
309 APValue Result;
310 if (EvaluatePointer(EvalExpr, Result, Info))
311 return Result;
312 return APValue();
313}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000314
315//===----------------------------------------------------------------------===//
316// Integer Evaluation
317//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000318
319namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000320class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000321 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000322 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000323 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000324public:
Chris Lattner422373c2008-07-11 22:52:41 +0000325 IntExprEvaluator(EvalInfo &info, APSInt &result)
326 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000327
Chris Lattner2c99c712008-07-11 19:24:49 +0000328 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner82437da2008-07-12 00:14:42 +0000329 return (unsigned)Info.Ctx.getIntWidth(T);
330 }
331
332 bool Extension(SourceLocation L, diag::kind D) {
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000333 Info.EvalResult.DiagLoc = L;
334 Info.EvalResult.Diag = D;
Chris Lattner82437da2008-07-12 00:14:42 +0000335 return true; // still a constant.
336 }
337
Chris Lattner438f3b12008-11-12 07:43:42 +0000338 bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
Chris Lattner82437da2008-07-12 00:14:42 +0000339 // If this is in an unevaluated portion of the subexpression, ignore the
340 // error.
Chris Lattner438f3b12008-11-12 07:43:42 +0000341 if (!Info.isEvaluated) {
342 // If error is ignored because the value isn't evaluated, get the real
343 // type at least to prevent errors downstream.
344 Result.zextOrTrunc(getIntTypeSizeInBits(ExprTy));
345 Result.setIsUnsigned(ExprTy->isUnsignedIntegerType());
Chris Lattner82437da2008-07-12 00:14:42 +0000346 return true;
Chris Lattner438f3b12008-11-12 07:43:42 +0000347 }
Chris Lattner82437da2008-07-12 00:14:42 +0000348
Chris Lattner438f3b12008-11-12 07:43:42 +0000349 // Take the first error.
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000350 if (Info.EvalResult.Diag == 0) {
351 Info.EvalResult.DiagLoc = L;
352 Info.EvalResult.Diag = D;
Chris Lattner438f3b12008-11-12 07:43:42 +0000353 }
Chris Lattner82437da2008-07-12 00:14:42 +0000354 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000355 }
356
Anders Carlssoncad17b52008-07-08 05:13:58 +0000357 //===--------------------------------------------------------------------===//
358 // Visitor Methods
359 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000360
361 bool VisitStmt(Stmt *) {
362 assert(0 && "This should be called on integers, stmts are not integers");
363 return false;
364 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000365
Chris Lattner438f3b12008-11-12 07:43:42 +0000366 bool VisitExpr(Expr *E) {
367 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Anders Carlssoncad17b52008-07-08 05:13:58 +0000368 }
369
Chris Lattnera42f09a2008-07-11 19:10:17 +0000370 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000371
Chris Lattner15e59112008-07-12 00:38:25 +0000372 bool VisitIntegerLiteral(const IntegerLiteral *E) {
373 Result = E->getValue();
374 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
375 return true;
376 }
377 bool VisitCharacterLiteral(const CharacterLiteral *E) {
378 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
379 Result = E->getValue();
380 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
381 return true;
382 }
383 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
384 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000385 // Per gcc docs "this built-in function ignores top level
386 // qualifiers". We need to use the canonical version to properly
387 // be able to strip CRV qualifiers from the type.
388 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
389 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
390 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
391 T1.getUnqualifiedType());
Chris Lattner15e59112008-07-12 00:38:25 +0000392 return true;
393 }
394 bool VisitDeclRefExpr(const DeclRefExpr *E);
395 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000396 bool VisitBinaryOperator(const BinaryOperator *E);
397 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000398 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000399
Chris Lattnerff579ff2008-07-12 01:15:53 +0000400 bool VisitCastExpr(CastExpr* E) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000401 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000402 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000403 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
404
Anders Carlsson027f2882008-11-16 19:01:22 +0000405 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000406 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson027f2882008-11-16 19:01:22 +0000407 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 Lattner265a0892008-07-11 21:24:13 +0000418private:
Chris Lattnerff579ff2008-07-12 01:15:53 +0000419 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000420};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000421} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000422
Chris Lattner422373c2008-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 Carlssonc43f44b2008-07-08 15:34:11 +0000425}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000426
Chris Lattner15e59112008-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 Lattner438f3b12008-11-12 07:43:42 +0000435 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner15e59112008-07-12 00:38:25 +0000436}
437
Chris Lattner1eee9402008-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 Lattner15e59112008-07-12 00:38:25 +0000493bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
494 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000495
Chris Lattner87293782008-10-06 05:28:25 +0000496 switch (E->isBuiltinCall()) {
497 default:
Chris Lattner438f3b12008-11-12 07:43:42 +0000498 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner87293782008-10-06 05:28:25 +0000499 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000500 Result.setIsSigned(true);
501 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-10-06 05:28:25 +0000502 return true;
503
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000504 case Builtin::BI__builtin_constant_p:
Chris Lattner87293782008-10-06 05:28:25 +0000505 // __builtin_constant_p always has one operand: it returns true if that
506 // operand can be folded, false otherwise.
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000507 Result = E->getArg(0)->isEvaluatable(Info.Ctx);
Chris Lattner87293782008-10-06 05:28:25 +0000508 return true;
509 }
Chris Lattner15e59112008-07-12 00:38:25 +0000510}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000511
Chris Lattnera42f09a2008-07-11 19:10:17 +0000512bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000513 if (E->getOpcode() == BinaryOperator::Comma) {
514 // Evaluate the side that actually matters; this needs to be
515 // handled specially because calling Visit() on the LHS can
516 // have strange results when it doesn't have an integral type.
Nuno Lopesd88cb9c2008-11-16 20:09:07 +0000517 if (Visit(E->getRHS()))
518 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000519
520 // Check for isEvaluated; the idea is that this might eventually
521 // be useful for isICE and other similar uses that care about
522 // whether a comma is evaluated. This isn't really used yet, though,
523 // and I'm not sure it really works as intended.
524 if (!Info.isEvaluated)
Nuno Lopesd88cb9c2008-11-16 20:09:07 +0000525 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
Eli Friedman14cc7542008-11-13 06:09:17 +0000526
Nuno Lopesd88cb9c2008-11-16 20:09:07 +0000527 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000528 }
529
530 if (E->isLogicalOp()) {
531 // These need to be handled specially because the operands aren't
532 // necessarily integral
533 bool bres;
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000534
535 if (HandleConversionToBool(E->getLHS(), bres, Info)) {
536 // We were able to evaluate the LHS, see if we can get away with not
537 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000538 if (bres == (E->getOpcode() == BinaryOperator::LOr) ||
539 !bres == (E->getOpcode() == BinaryOperator::LAnd)) {
540 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
541 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
542 Result = bres;
543
544 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000545 }
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000546
547 bool bres2;
548 if (HandleConversionToBool(E->getRHS(), bres2, Info)) {
549 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
550 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
551 if (E->getOpcode() == BinaryOperator::LOr)
552 Result = bres || bres2;
553 else
554 Result = bres && bres2;
555 return true;
556 }
557 } else {
558 if (HandleConversionToBool(E->getRHS(), bres, Info)) {
559 // We can't evaluate the LHS; however, sometimes the result
560 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
561 if (bres == (E->getOpcode() == BinaryOperator::LOr) ||
562 !bres == (E->getOpcode() == BinaryOperator::LAnd)) {
563 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
564 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
565 Result = bres;
566 Info.isEvaluated = false;
567
568 return true;
569 }
570 }
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000571 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000572
Eli Friedman14cc7542008-11-13 06:09:17 +0000573 return false;
574 }
575
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000576 QualType LHSTy = E->getLHS()->getType();
577 QualType RHSTy = E->getRHS()->getType();
578
579 if (LHSTy->isRealFloatingType() &&
580 RHSTy->isRealFloatingType()) {
581 APFloat RHS(0.0), LHS(0.0);
582
583 if (!EvaluateFloat(E->getRHS(), RHS, Info))
584 return false;
585
586 if (!EvaluateFloat(E->getLHS(), LHS, Info))
587 return false;
588
589 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000590
591 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
592
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000593 switch (E->getOpcode()) {
594 default:
595 assert(0 && "Invalid binary operator!");
596 case BinaryOperator::LT:
597 Result = CR == APFloat::cmpLessThan;
598 break;
599 case BinaryOperator::GT:
600 Result = CR == APFloat::cmpGreaterThan;
601 break;
602 case BinaryOperator::LE:
603 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
604 break;
605 case BinaryOperator::GE:
606 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
607 break;
608 case BinaryOperator::EQ:
609 Result = CR == APFloat::cmpEqual;
610 break;
611 case BinaryOperator::NE:
612 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
613 break;
614 }
615
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000616 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
617 return true;
618 }
619
Anders Carlsson027f2882008-11-16 19:01:22 +0000620 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000621 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson027f2882008-11-16 19:01:22 +0000622 APValue LHSValue;
623 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
624 return false;
625
626 APValue RHSValue;
627 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
628 return false;
629
630 // FIXME: Is this correct? What if only one of the operands has a base?
631 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
632 return false;
633
634 const QualType Type = E->getLHS()->getType();
635 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
636
637 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
638 D /= Info.Ctx.getTypeSize(ElementType) / 8;
639
Anders Carlsson027f2882008-11-16 19:01:22 +0000640 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000641 Result = D;
Anders Carlsson027f2882008-11-16 19:01:22 +0000642 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
643
644 return true;
645 }
646 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000647 if (!LHSTy->isIntegralType() ||
648 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000649 // We can't continue from here for non-integral types, and they
650 // could potentially confuse the following operations.
651 // FIXME: Deal with EQ and friends.
652 return false;
653 }
654
Anders Carlssond1aa5812008-07-08 14:35:21 +0000655 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000656 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000657 if (!Visit(E->getLHS())) {
Chris Lattner82437da2008-07-12 00:14:42 +0000658 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000659 }
Eli Friedman3e64dd72008-07-27 05:46:18 +0000660
Eli Friedman3e64dd72008-07-27 05:46:18 +0000661
662 // FIXME Maybe we want to succeed even where we can't evaluate the
663 // right side of LAnd/LOr?
664 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000665 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000666 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000667
Anders Carlssond1aa5812008-07-08 14:35:21 +0000668 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000669 default:
670 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner82437da2008-07-12 00:14:42 +0000671 case BinaryOperator::Mul: Result *= RHS; return true;
672 case BinaryOperator::Add: Result += RHS; return true;
673 case BinaryOperator::Sub: Result -= RHS; return true;
674 case BinaryOperator::And: Result &= RHS; return true;
675 case BinaryOperator::Xor: Result ^= RHS; return true;
676 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000677 case BinaryOperator::Div:
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;
Chris Lattner400d7402008-07-11 22:15:16 +0000683 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000684 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000685 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
686 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000687 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000688 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000689 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000690 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000691 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000692 break;
693 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000694 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000695 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000696
Chris Lattner045502c2008-07-11 19:29:32 +0000697 case BinaryOperator::LT:
698 Result = Result < RHS;
699 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
700 break;
701 case BinaryOperator::GT:
702 Result = Result > RHS;
703 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
704 break;
705 case BinaryOperator::LE:
706 Result = Result <= RHS;
707 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
708 break;
709 case BinaryOperator::GE:
710 Result = Result >= RHS;
711 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
712 break;
713 case BinaryOperator::EQ:
714 Result = Result == RHS;
715 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
716 break;
717 case BinaryOperator::NE:
718 Result = Result != RHS;
719 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
720 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000721 case BinaryOperator::LAnd:
722 Result = Result != 0 && RHS != 0;
723 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
724 break;
725 case BinaryOperator::LOr:
726 Result = Result != 0 || RHS != 0;
727 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
728 break;
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000729 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000730
731 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000732 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000733}
734
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000735bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes308de752008-11-16 22:06:39 +0000736 bool Cond;
737 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000738 return false;
739
Nuno Lopes308de752008-11-16 22:06:39 +0000740 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000741}
742
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000743/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
744/// expression's type.
745bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
746 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000747 // Return the result in the right width.
748 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
749 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
750
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000751 QualType SrcTy = E->getTypeOfArgument();
752
Chris Lattner265a0892008-07-11 21:24:13 +0000753 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +0000754 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +0000755 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +0000756 return true;
757 }
Chris Lattner265a0892008-07-11 21:24:13 +0000758
759 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman7888b932008-11-12 09:44:48 +0000760 // FIXME: But alignof(vla) is!
Chris Lattner265a0892008-07-11 21:24:13 +0000761 if (!SrcTy->isConstantSizeType()) {
762 // FIXME: Should we attempt to evaluate this?
763 return false;
764 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000765
766 bool isSizeOf = E->isSizeOf();
Chris Lattner265a0892008-07-11 21:24:13 +0000767
768 // GCC extension: sizeof(function) = 1.
769 if (SrcTy->isFunctionType()) {
770 // FIXME: AlignOf shouldn't be unconditionally 4!
771 Result = isSizeOf ? 1 : 4;
772 return true;
773 }
774
775 // Get information about the size or align.
Chris Lattner422373c2008-07-11 22:52:41 +0000776 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattner265a0892008-07-11 21:24:13 +0000777 if (isSizeOf)
Eli Friedman7888b932008-11-12 09:44:48 +0000778 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000779 else
Chris Lattner422373c2008-07-11 22:52:41 +0000780 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000781 return true;
782}
783
Chris Lattnera42f09a2008-07-11 19:10:17 +0000784bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000785 // Special case unary operators that do not need their subexpression
786 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +0000787 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000788 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +0000789 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +0000790 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
791 return true;
792 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000793
794 if (E->getOpcode() == UnaryOperator::LNot) {
795 // LNot's operand isn't necessarily an integer, so we handle it specially.
796 bool bres;
797 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
798 return false;
799 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
800 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
801 Result = !bres;
802 return true;
803 }
804
Chris Lattner422373c2008-07-11 22:52:41 +0000805 // Get the operand value into 'Result'.
806 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000807 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000808
Chris Lattner400d7402008-07-11 22:15:16 +0000809 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000810 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000811 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
812 // See C99 6.6p3.
Chris Lattner438f3b12008-11-12 07:43:42 +0000813 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
814 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000815 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +0000816 // FIXME: Should extension allow i-c-e extension expressions in its scope?
817 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +0000818 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +0000819 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +0000820 break;
821 case UnaryOperator::Minus:
822 Result = -Result;
823 break;
824 case UnaryOperator::Not:
825 Result = ~Result;
826 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000827 }
828
829 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000830 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000831}
832
Chris Lattnerff579ff2008-07-12 01:15:53 +0000833/// HandleCast - This is used to evaluate implicit or explicit casts where the
834/// result type is integer.
835bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
836 Expr *SubExpr, QualType DestType) {
Chris Lattner2c99c712008-07-11 19:24:49 +0000837 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000838
Eli Friedman7888b932008-11-12 09:44:48 +0000839 if (DestType->isBooleanType()) {
840 bool BoolResult;
841 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
842 return false;
843 Result.zextOrTrunc(DestWidth);
844 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
845 Result = BoolResult;
846 return true;
847 }
848
Anders Carlssond1aa5812008-07-08 14:35:21 +0000849 // Handle simple integer->integer casts.
Eli Friedman14cc7542008-11-13 06:09:17 +0000850 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000851 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000852 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000853
854 // Figure out if this is a truncate, extend or noop cast.
855 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman7888b932008-11-12 09:44:48 +0000856 Result.extOrTrunc(DestWidth);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000857 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
858 return true;
859 }
860
861 // FIXME: Clean this up!
862 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000863 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +0000864 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000865 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000866
Anders Carlssond1aa5812008-07-08 14:35:21 +0000867 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +0000868 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000869
Anders Carlsson8ab15c82008-07-08 16:49:00 +0000870 Result.extOrTrunc(DestWidth);
871 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +0000872 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
873 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000874 }
Eli Friedman7888b932008-11-12 09:44:48 +0000875
Chris Lattnerff579ff2008-07-12 01:15:53 +0000876 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner438f3b12008-11-12 07:43:42 +0000877 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000878
Eli Friedman2f445492008-08-22 00:06:13 +0000879 APFloat F(0.0);
880 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner438f3b12008-11-12 07:43:42 +0000881 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000882
883 // Determine whether we are converting to unsigned or signed.
884 bool DestSigned = DestType->isSignedIntegerType();
885
886 // FIXME: Warning for overflow.
Dale Johannesen2461f612008-10-09 23:02:32 +0000887 uint64_t Space[4];
888 bool ignored;
Eli Friedman2f445492008-08-22 00:06:13 +0000889 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesen2461f612008-10-09 23:02:32 +0000890 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000891 Result = llvm::APInt(DestWidth, 4, Space);
892 Result.setIsUnsigned(!DestSigned);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000893 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000894}
Anders Carlsson02a34c32008-07-08 14:30:00 +0000895
Chris Lattnera823ccf2008-07-11 18:11:29 +0000896//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +0000897// Float Evaluation
898//===----------------------------------------------------------------------===//
899
900namespace {
901class VISIBILITY_HIDDEN FloatExprEvaluator
902 : public StmtVisitor<FloatExprEvaluator, bool> {
903 EvalInfo &Info;
904 APFloat &Result;
905public:
906 FloatExprEvaluator(EvalInfo &info, APFloat &result)
907 : Info(info), Result(result) {}
908
909 bool VisitStmt(Stmt *S) {
910 return false;
911 }
912
913 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +0000914 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000915
Daniel Dunbar804ead02008-10-16 03:51:50 +0000916 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000917 bool VisitBinaryOperator(const BinaryOperator *E);
918 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000919 bool VisitCastExpr(CastExpr *E);
920 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000921};
922} // end anonymous namespace
923
924static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
925 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
926}
927
Chris Lattner87293782008-10-06 05:28:25 +0000928bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner87293782008-10-06 05:28:25 +0000929 switch (E->isBuiltinCall()) {
Chris Lattner27cde262008-10-06 05:53:16 +0000930 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +0000931 case Builtin::BI__builtin_huge_val:
932 case Builtin::BI__builtin_huge_valf:
933 case Builtin::BI__builtin_huge_vall:
934 case Builtin::BI__builtin_inf:
935 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000936 case Builtin::BI__builtin_infl: {
937 const llvm::fltSemantics &Sem =
938 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +0000939 Result = llvm::APFloat::getInf(Sem);
940 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000941 }
Chris Lattner667e1ee2008-10-06 06:31:58 +0000942
943 case Builtin::BI__builtin_nan:
944 case Builtin::BI__builtin_nanf:
945 case Builtin::BI__builtin_nanl:
946 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
947 // can't constant fold it.
948 if (const StringLiteral *S =
949 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
950 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000951 const llvm::fltSemantics &Sem =
952 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +0000953 Result = llvm::APFloat::getNaN(Sem);
954 return true;
955 }
956 }
957 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +0000958
959 case Builtin::BI__builtin_fabs:
960 case Builtin::BI__builtin_fabsf:
961 case Builtin::BI__builtin_fabsl:
962 if (!EvaluateFloat(E->getArg(0), Result, Info))
963 return false;
964
965 if (Result.isNegative())
966 Result.changeSign();
967 return true;
968
969 case Builtin::BI__builtin_copysign:
970 case Builtin::BI__builtin_copysignf:
971 case Builtin::BI__builtin_copysignl: {
972 APFloat RHS(0.);
973 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
974 !EvaluateFloat(E->getArg(1), RHS, Info))
975 return false;
976 Result.copySign(RHS);
977 return true;
978 }
Chris Lattner87293782008-10-06 05:28:25 +0000979 }
980}
981
Daniel Dunbar804ead02008-10-16 03:51:50 +0000982bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes1cea4f42008-11-19 17:44:31 +0000983 if (E->getOpcode() == UnaryOperator::Deref)
984 return false;
985
Daniel Dunbar804ead02008-10-16 03:51:50 +0000986 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
987 return false;
988
989 switch (E->getOpcode()) {
990 default: return false;
991 case UnaryOperator::Plus:
992 return true;
993 case UnaryOperator::Minus:
994 Result.changeSign();
995 return true;
996 }
997}
Chris Lattner87293782008-10-06 05:28:25 +0000998
Eli Friedman2f445492008-08-22 00:06:13 +0000999bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1000 // FIXME: Diagnostics? I really don't understand how the warnings
1001 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +00001002 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +00001003 if (!EvaluateFloat(E->getLHS(), Result, Info))
1004 return false;
1005 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1006 return false;
1007
1008 switch (E->getOpcode()) {
1009 default: return false;
1010 case BinaryOperator::Mul:
1011 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1012 return true;
1013 case BinaryOperator::Add:
1014 Result.add(RHS, APFloat::rmNearestTiesToEven);
1015 return true;
1016 case BinaryOperator::Sub:
1017 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1018 return true;
1019 case BinaryOperator::Div:
1020 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1021 return true;
1022 case BinaryOperator::Rem:
1023 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1024 return true;
1025 }
1026}
1027
1028bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1029 Result = E->getValue();
1030 return true;
1031}
1032
Eli Friedman7888b932008-11-12 09:44:48 +00001033bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1034 Expr* SubExpr = E->getSubExpr();
1035 const llvm::fltSemantics& destSemantics =
1036 Info.Ctx.getFloatTypeSemantics(E->getType());
1037 if (SubExpr->getType()->isIntegralType()) {
1038 APSInt IntResult;
1039 if (!EvaluateInteger(E, IntResult, Info))
1040 return false;
1041 Result = APFloat(destSemantics, 1);
1042 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1043 APFloat::rmNearestTiesToEven);
1044 return true;
1045 }
1046 if (SubExpr->getType()->isRealFloatingType()) {
1047 if (!Visit(SubExpr))
1048 return false;
1049 bool ignored;
1050 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1051 return true;
1052 }
1053
1054 return false;
1055}
1056
1057bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1058 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1059 return true;
1060}
1061
Eli Friedman2f445492008-08-22 00:06:13 +00001062//===----------------------------------------------------------------------===//
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001063// Complex Float Evaluation
1064//===----------------------------------------------------------------------===//
1065
1066namespace {
1067class VISIBILITY_HIDDEN ComplexFloatExprEvaluator
1068 : public StmtVisitor<ComplexFloatExprEvaluator, APValue> {
1069 EvalInfo &Info;
1070
1071public:
1072 ComplexFloatExprEvaluator(EvalInfo &info) : Info(info) {}
1073
1074 //===--------------------------------------------------------------------===//
1075 // Visitor Methods
1076 //===--------------------------------------------------------------------===//
1077
1078 APValue VisitStmt(Stmt *S) {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001079 return APValue();
1080 }
1081
1082 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1083
1084 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1085 APFloat Result(0.0);
1086 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1087 return APValue();
1088
1089 return APValue(APFloat(0.0), Result);
1090 }
1091
Anders Carlssonad2794c2008-11-16 21:51:21 +00001092 APValue VisitCastExpr(CastExpr *E) {
1093 Expr* SubExpr = E->getSubExpr();
1094
1095 if (SubExpr->getType()->isRealFloatingType()) {
1096 APFloat Result(0.0);
1097
1098 if (!EvaluateFloat(SubExpr, Result, Info))
1099 return APValue();
1100
1101 return APValue(Result, APFloat(0.0));
1102 }
1103
1104 // FIXME: Handle more casts.
1105 return APValue();
1106 }
1107
1108 APValue VisitBinaryOperator(const BinaryOperator *E);
1109
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001110};
1111} // end anonymous namespace
1112
1113static bool EvaluateComplexFloat(const Expr *E, APValue &Result, EvalInfo &Info)
1114{
1115 Result = ComplexFloatExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1116 return Result.isComplexFloat();
1117}
1118
Anders Carlssonad2794c2008-11-16 21:51:21 +00001119APValue ComplexFloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
1120{
1121 APValue Result, RHS;
1122
1123 if (!EvaluateComplexFloat(E->getLHS(), Result, Info))
1124 return APValue();
1125
1126 if (!EvaluateComplexFloat(E->getRHS(), RHS, Info))
1127 return APValue();
1128
1129 switch (E->getOpcode()) {
1130 default: return APValue();
1131 case BinaryOperator::Add:
1132 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1133 APFloat::rmNearestTiesToEven);
1134 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1135 APFloat::rmNearestTiesToEven);
1136 case BinaryOperator::Sub:
1137 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1138 APFloat::rmNearestTiesToEven);
1139 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1140 APFloat::rmNearestTiesToEven);
1141 }
1142
1143 return Result;
1144}
1145
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001146//===----------------------------------------------------------------------===//
Chris Lattneref069662008-11-16 21:24:15 +00001147// Top level Expr::Evaluate method.
Chris Lattnera823ccf2008-07-11 18:11:29 +00001148//===----------------------------------------------------------------------===//
1149
Chris Lattneref069662008-11-16 21:24:15 +00001150/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner87293782008-10-06 05:28:25 +00001151/// any crazy technique (that has nothing to do with language standards) that
1152/// we want to. If this function returns true, it returns the folded constant
1153/// in Result.
Anders Carlssonb96c2062008-11-22 21:50:49 +00001154bool Expr::Evaluate(APValue &Result, ASTContext &Ctx, bool *isEvaluated) const {
Anders Carlssondd8d41f2008-11-30 16:38:33 +00001155 Expr::EvalResult EvalResult;
1156 EvalInfo Info(Ctx, EvalResult);
1157
Anders Carlssonc0328012008-07-08 05:49:43 +00001158 if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +00001159 llvm::APSInt sInt(32);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001160 if (!EvaluateInteger(this, sInt, Info))
1161 return false;
1162
1163 Result = APValue(sInt);
Eli Friedman2f445492008-08-22 00:06:13 +00001164 } else if (getType()->isPointerType()) {
Anders Carlssonb96c2062008-11-22 21:50:49 +00001165 if (!EvaluatePointer(this, Result, Info))
1166 return false;
Eli Friedman2f445492008-08-22 00:06:13 +00001167 } else if (getType()->isRealFloatingType()) {
1168 llvm::APFloat f(0.0);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001169 if (!EvaluateFloat(this, f, Info))
1170 return false;
1171
1172 Result = APValue(f);
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001173 } else if (getType()->isComplexType()) {
Anders Carlssonb96c2062008-11-22 21:50:49 +00001174 if (!EvaluateComplexFloat(this, Result, Info))
1175 return false;
Anders Carlssoncb6a2e82008-11-22 22:56:32 +00001176 } else
1177 return false;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001178
1179 if (isEvaluated)
1180 *isEvaluated = Info.isEvaluated;
1181 return true;
Anders Carlssonc7436af2008-07-03 04:20:39 +00001182}
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001183
Chris Lattneref069662008-11-16 21:24:15 +00001184/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001185/// folded, but discard the result.
1186bool Expr::isEvaluatable(ASTContext &Ctx) const {
1187 APValue V;
Chris Lattneref069662008-11-16 21:24:15 +00001188 return Evaluate(V, Ctx);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001189}
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001190
1191APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
1192 APValue V;
1193 bool Result = Evaluate(V, Ctx);
1194 assert(Result && "Could not evaluate expression");
1195 assert(V.isInt() && "Expression did not evaluate to integer");
1196
1197 return V.getInt();
1198}