blob: 341baeab85ba1acd0382a118a16c41fc7ac49bf1 [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;
Anders Carlsson6c1a9e22008-11-30 18:26:25 +000044
45 /// ShortCircuit - will be greater than zero if the current subexpression has
46 /// will not be evaluated because it's short-circuited (according to C rules).
47 unsigned ShortCircuit;
Chris Lattner422373c2008-07-11 22:52:41 +000048
Anders Carlssondd8d41f2008-11-30 16:38:33 +000049 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx),
Anders Carlsson6c1a9e22008-11-30 18:26:25 +000050 EvalResult(evalresult), ShortCircuit(0) {}
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}
Anders Carlsson4ab88da2008-12-05 05:24:13 +0000269
Chris Lattnera823ccf2008-07-11 18:11:29 +0000270
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
Anders Carlssonfa76d822008-11-30 18:14:57 +0000332 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000333 Info.EvalResult.DiagLoc = L;
334 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000335 Info.EvalResult.DiagExpr = E;
Chris Lattner82437da2008-07-12 00:14:42 +0000336 return true; // still a constant.
337 }
338
Anders Carlssonfa76d822008-11-30 18:14:57 +0000339 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner82437da2008-07-12 00:14:42 +0000340 // If this is in an unevaluated portion of the subexpression, ignore the
341 // error.
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000342 if (Info.ShortCircuit) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000343 // If error is ignored because the value isn't evaluated, get the real
344 // type at least to prevent errors downstream.
Anders Carlssonfa76d822008-11-30 18:14:57 +0000345 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
346 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattner82437da2008-07-12 00:14:42 +0000347 return true;
Chris Lattner438f3b12008-11-12 07:43:42 +0000348 }
Chris Lattner82437da2008-07-12 00:14:42 +0000349
Chris Lattner438f3b12008-11-12 07:43:42 +0000350 // Take the first error.
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000351 if (Info.EvalResult.Diag == 0) {
352 Info.EvalResult.DiagLoc = L;
353 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000354 Info.EvalResult.DiagExpr = E;
Chris Lattner438f3b12008-11-12 07:43:42 +0000355 }
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) {
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000369 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
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) {
Anders Carlssonfa76d822008-11-30 18:14:57 +0000403 return HandleCast(E);
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) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000408 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson027f2882008-11-16 19:01:22 +0000409 Result = E->getValue();
410 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
411 return true;
412 }
413
414 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
415 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
416 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
417 return true;
418 }
419
Chris Lattner265a0892008-07-11 21:24:13 +0000420private:
Anders Carlssonfa76d822008-11-30 18:14:57 +0000421 bool HandleCast(CastExpr* E);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000422};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000423} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000424
Chris Lattner422373c2008-07-11 22:52:41 +0000425static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
426 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000427}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000428
Chris Lattner15e59112008-07-12 00:38:25 +0000429bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
430 // Enums are integer constant exprs.
431 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
432 Result = D->getInitVal();
Eli Friedman8b10a232008-12-08 02:21:03 +0000433 // FIXME: This is an ugly hack around the fact that enums don't set their
434 // signedness consistently; see PR3173
435 Result.setIsUnsigned(!E->getType()->isSignedIntegerType());
Chris Lattner15e59112008-07-12 00:38:25 +0000436 return true;
437 }
438
439 // Otherwise, random variable references are not constants.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000440 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000441}
442
Chris Lattner1eee9402008-10-06 06:40:35 +0000443/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
444/// as GCC.
445static int EvaluateBuiltinClassifyType(const CallExpr *E) {
446 // The following enum mimics the values returned by GCC.
447 enum gcc_type_class {
448 no_type_class = -1,
449 void_type_class, integer_type_class, char_type_class,
450 enumeral_type_class, boolean_type_class,
451 pointer_type_class, reference_type_class, offset_type_class,
452 real_type_class, complex_type_class,
453 function_type_class, method_type_class,
454 record_type_class, union_type_class,
455 array_type_class, string_type_class,
456 lang_type_class
457 };
458
459 // If no argument was supplied, default to "no_type_class". This isn't
460 // ideal, however it is what gcc does.
461 if (E->getNumArgs() == 0)
462 return no_type_class;
463
464 QualType ArgTy = E->getArg(0)->getType();
465 if (ArgTy->isVoidType())
466 return void_type_class;
467 else if (ArgTy->isEnumeralType())
468 return enumeral_type_class;
469 else if (ArgTy->isBooleanType())
470 return boolean_type_class;
471 else if (ArgTy->isCharType())
472 return string_type_class; // gcc doesn't appear to use char_type_class
473 else if (ArgTy->isIntegerType())
474 return integer_type_class;
475 else if (ArgTy->isPointerType())
476 return pointer_type_class;
477 else if (ArgTy->isReferenceType())
478 return reference_type_class;
479 else if (ArgTy->isRealType())
480 return real_type_class;
481 else if (ArgTy->isComplexType())
482 return complex_type_class;
483 else if (ArgTy->isFunctionType())
484 return function_type_class;
485 else if (ArgTy->isStructureType())
486 return record_type_class;
487 else if (ArgTy->isUnionType())
488 return union_type_class;
489 else if (ArgTy->isArrayType())
490 return array_type_class;
491 else if (ArgTy->isUnionType())
492 return union_type_class;
493 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
494 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
495 return -1;
496}
497
Chris Lattner15e59112008-07-12 00:38:25 +0000498bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
499 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000500
Chris Lattner87293782008-10-06 05:28:25 +0000501 switch (E->isBuiltinCall()) {
502 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000503 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner87293782008-10-06 05:28:25 +0000504 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000505 Result.setIsSigned(true);
506 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-10-06 05:28:25 +0000507 return true;
508
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000509 case Builtin::BI__builtin_constant_p:
Chris Lattner87293782008-10-06 05:28:25 +0000510 // __builtin_constant_p always has one operand: it returns true if that
511 // operand can be folded, false otherwise.
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000512 Result = E->getArg(0)->isEvaluatable(Info.Ctx);
Chris Lattner87293782008-10-06 05:28:25 +0000513 return true;
514 }
Chris Lattner15e59112008-07-12 00:38:25 +0000515}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000516
Chris Lattnera42f09a2008-07-11 19:10:17 +0000517bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000518 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000519 if (!Visit(E->getRHS()))
520 return false;
Anders Carlsson197f6f72008-12-01 06:44:05 +0000521
522 if (!Info.ShortCircuit) {
523 // If we can't evaluate the LHS, it must be because it has
524 // side effects.
525 if (!E->getLHS()->isEvaluatable(Info.Ctx))
526 Info.EvalResult.HasSideEffects = true;
527
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000528 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson197f6f72008-12-01 06:44:05 +0000529 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000530
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000531 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000532 }
533
534 if (E->isLogicalOp()) {
535 // These need to be handled specially because the operands aren't
536 // necessarily integral
Anders Carlsson501da1f2008-11-30 16:51:17 +0000537 bool lhsResult, rhsResult;
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000538
Anders Carlsson501da1f2008-11-30 16:51:17 +0000539 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000540 // We were able to evaluate the LHS, see if we can get away with not
541 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlsson501da1f2008-11-30 16:51:17 +0000542 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
543 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000544 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
545 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlsson501da1f2008-11-30 16:51:17 +0000546 Result = lhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000547
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000548 Info.ShortCircuit++;
Anders Carlsson501da1f2008-11-30 16:51:17 +0000549 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000550 Info.ShortCircuit--;
551
Anders Carlsson501da1f2008-11-30 16:51:17 +0000552 if (rhsEvaluated)
553 return true;
554
555 // FIXME: Return an extension warning saying that the RHS could not be
556 // evaluated.
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000557 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000558 }
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000559
Anders Carlsson501da1f2008-11-30 16:51:17 +0000560 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000561 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
562 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
563 if (E->getOpcode() == BinaryOperator::LOr)
Anders Carlsson501da1f2008-11-30 16:51:17 +0000564 Result = lhsResult || rhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000565 else
Anders Carlsson501da1f2008-11-30 16:51:17 +0000566 Result = lhsResult && rhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000567 return true;
568 }
569 } else {
Anders Carlsson501da1f2008-11-30 16:51:17 +0000570 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000571 // We can't evaluate the LHS; however, sometimes the result
572 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlsson501da1f2008-11-30 16:51:17 +0000573 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
574 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000575 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
576 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlsson501da1f2008-11-30 16:51:17 +0000577 Result = rhsResult;
578
579 // Since we werent able to evaluate the left hand side, it
580 // must have had side effects.
581 Info.EvalResult.HasSideEffects = true;
582
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000583 return true;
584 }
585 }
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000586 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000587
Eli Friedman14cc7542008-11-13 06:09:17 +0000588 return false;
589 }
590
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000591 QualType LHSTy = E->getLHS()->getType();
592 QualType RHSTy = E->getRHS()->getType();
593
594 if (LHSTy->isRealFloatingType() &&
595 RHSTy->isRealFloatingType()) {
596 APFloat RHS(0.0), LHS(0.0);
597
598 if (!EvaluateFloat(E->getRHS(), RHS, Info))
599 return false;
600
601 if (!EvaluateFloat(E->getLHS(), LHS, Info))
602 return false;
603
604 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000605
606 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
607
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000608 switch (E->getOpcode()) {
609 default:
610 assert(0 && "Invalid binary operator!");
611 case BinaryOperator::LT:
612 Result = CR == APFloat::cmpLessThan;
613 break;
614 case BinaryOperator::GT:
615 Result = CR == APFloat::cmpGreaterThan;
616 break;
617 case BinaryOperator::LE:
618 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
619 break;
620 case BinaryOperator::GE:
621 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
622 break;
623 case BinaryOperator::EQ:
624 Result = CR == APFloat::cmpEqual;
625 break;
626 case BinaryOperator::NE:
627 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
628 break;
629 }
630
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000631 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
632 return true;
633 }
634
Anders Carlsson027f2882008-11-16 19:01:22 +0000635 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000636 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson027f2882008-11-16 19:01:22 +0000637 APValue LHSValue;
638 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
639 return false;
640
641 APValue RHSValue;
642 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
643 return false;
644
645 // FIXME: Is this correct? What if only one of the operands has a base?
646 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
647 return false;
648
649 const QualType Type = E->getLHS()->getType();
650 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
651
652 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
653 D /= Info.Ctx.getTypeSize(ElementType) / 8;
654
Anders Carlsson027f2882008-11-16 19:01:22 +0000655 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000656 Result = D;
Anders Carlsson027f2882008-11-16 19:01:22 +0000657 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
658
659 return true;
660 }
661 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000662 if (!LHSTy->isIntegralType() ||
663 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000664 // We can't continue from here for non-integral types, and they
665 // could potentially confuse the following operations.
666 // FIXME: Deal with EQ and friends.
667 return false;
668 }
669
Anders Carlssond1aa5812008-07-08 14:35:21 +0000670 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000671 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000672 if (!Visit(E->getLHS())) {
Chris Lattner82437da2008-07-12 00:14:42 +0000673 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000674 }
Eli Friedman3e64dd72008-07-27 05:46:18 +0000675
Eli Friedman3e64dd72008-07-27 05:46:18 +0000676
677 // FIXME Maybe we want to succeed even where we can't evaluate the
678 // right side of LAnd/LOr?
679 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000680 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000681 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000682
Anders Carlssond1aa5812008-07-08 14:35:21 +0000683 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000684 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000685 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner82437da2008-07-12 00:14:42 +0000686 case BinaryOperator::Mul: Result *= RHS; return true;
687 case BinaryOperator::Add: Result += RHS; return true;
688 case BinaryOperator::Sub: Result -= RHS; return true;
689 case BinaryOperator::And: Result &= RHS; return true;
690 case BinaryOperator::Xor: Result ^= RHS; return true;
691 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000692 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000693 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000694 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000695 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000696 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000697 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000698 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000699 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000700 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000701 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000702 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000703 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000704 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000705 break;
706 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000707 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000708 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000709
Chris Lattner045502c2008-07-11 19:29:32 +0000710 case BinaryOperator::LT:
711 Result = Result < RHS;
712 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
713 break;
714 case BinaryOperator::GT:
715 Result = Result > RHS;
716 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
717 break;
718 case BinaryOperator::LE:
719 Result = Result <= RHS;
720 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
721 break;
722 case BinaryOperator::GE:
723 Result = Result >= RHS;
724 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
725 break;
726 case BinaryOperator::EQ:
727 Result = Result == RHS;
728 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
729 break;
730 case BinaryOperator::NE:
731 Result = Result != RHS;
732 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
733 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000734 case BinaryOperator::LAnd:
735 Result = Result != 0 && RHS != 0;
736 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
737 break;
738 case BinaryOperator::LOr:
739 Result = Result != 0 || RHS != 0;
740 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
741 break;
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000742 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000743
744 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000745 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000746}
747
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000748bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes308de752008-11-16 22:06:39 +0000749 bool Cond;
750 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000751 return false;
752
Nuno Lopes308de752008-11-16 22:06:39 +0000753 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000754}
755
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000756/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
757/// expression's type.
758bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
759 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000760 // Return the result in the right width.
761 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
762 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
763
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000764 QualType SrcTy = E->getTypeOfArgument();
765
Chris Lattner265a0892008-07-11 21:24:13 +0000766 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +0000767 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +0000768 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +0000769 return true;
770 }
Chris Lattner265a0892008-07-11 21:24:13 +0000771
772 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman7888b932008-11-12 09:44:48 +0000773 // FIXME: But alignof(vla) is!
Chris Lattner265a0892008-07-11 21:24:13 +0000774 if (!SrcTy->isConstantSizeType()) {
775 // FIXME: Should we attempt to evaluate this?
776 return false;
777 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000778
779 bool isSizeOf = E->isSizeOf();
Chris Lattner265a0892008-07-11 21:24:13 +0000780
781 // GCC extension: sizeof(function) = 1.
782 if (SrcTy->isFunctionType()) {
783 // FIXME: AlignOf shouldn't be unconditionally 4!
784 Result = isSizeOf ? 1 : 4;
785 return true;
786 }
787
788 // Get information about the size or align.
Chris Lattner422373c2008-07-11 22:52:41 +0000789 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattner265a0892008-07-11 21:24:13 +0000790 if (isSizeOf)
Eli Friedman7888b932008-11-12 09:44:48 +0000791 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000792 else
Chris Lattner422373c2008-07-11 22:52:41 +0000793 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000794 return true;
795}
796
Chris Lattnera42f09a2008-07-11 19:10:17 +0000797bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000798 // Special case unary operators that do not need their subexpression
799 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +0000800 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000801 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +0000802 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +0000803 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
804 return true;
805 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000806
807 if (E->getOpcode() == UnaryOperator::LNot) {
808 // LNot's operand isn't necessarily an integer, so we handle it specially.
809 bool bres;
810 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
811 return false;
812 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
813 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
814 Result = !bres;
815 return true;
816 }
817
Chris Lattner422373c2008-07-11 22:52:41 +0000818 // Get the operand value into 'Result'.
819 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000820 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000821
Chris Lattner400d7402008-07-11 22:15:16 +0000822 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000823 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000824 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
825 // See C99 6.6p3.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000826 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000827 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +0000828 // FIXME: Should extension allow i-c-e extension expressions in its scope?
829 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +0000830 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +0000831 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +0000832 break;
833 case UnaryOperator::Minus:
834 Result = -Result;
835 break;
836 case UnaryOperator::Not:
837 Result = ~Result;
838 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000839 }
840
841 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000842 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000843}
844
Chris Lattnerff579ff2008-07-12 01:15:53 +0000845/// HandleCast - This is used to evaluate implicit or explicit casts where the
846/// result type is integer.
Anders Carlssonfa76d822008-11-30 18:14:57 +0000847bool IntExprEvaluator::HandleCast(CastExpr *E) {
848 Expr *SubExpr = E->getSubExpr();
849 QualType DestType = E->getType();
850
Chris Lattner2c99c712008-07-11 19:24:49 +0000851 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000852
Eli Friedman7888b932008-11-12 09:44:48 +0000853 if (DestType->isBooleanType()) {
854 bool BoolResult;
855 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
856 return false;
857 Result.zextOrTrunc(DestWidth);
858 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
859 Result = BoolResult;
860 return true;
861 }
862
Anders Carlssond1aa5812008-07-08 14:35:21 +0000863 // Handle simple integer->integer casts.
Eli Friedman14cc7542008-11-13 06:09:17 +0000864 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000865 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000866 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000867
868 // Figure out if this is a truncate, extend or noop cast.
869 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman7888b932008-11-12 09:44:48 +0000870 Result.extOrTrunc(DestWidth);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000871 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
872 return true;
873 }
874
875 // FIXME: Clean this up!
876 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000877 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +0000878 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000879 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000880
Anders Carlssond1aa5812008-07-08 14:35:21 +0000881 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +0000882 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000883
Anders Carlsson8ab15c82008-07-08 16:49:00 +0000884 Result.extOrTrunc(DestWidth);
885 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +0000886 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
887 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000888 }
Eli Friedman7888b932008-11-12 09:44:48 +0000889
Chris Lattnerff579ff2008-07-12 01:15:53 +0000890 if (!SubExpr->getType()->isRealFloatingType())
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000891 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000892
Eli Friedman2f445492008-08-22 00:06:13 +0000893 APFloat F(0.0);
894 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000895 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000896
897 // Determine whether we are converting to unsigned or signed.
898 bool DestSigned = DestType->isSignedIntegerType();
899
900 // FIXME: Warning for overflow.
Dale Johannesen2461f612008-10-09 23:02:32 +0000901 uint64_t Space[4];
902 bool ignored;
Eli Friedman2f445492008-08-22 00:06:13 +0000903 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesen2461f612008-10-09 23:02:32 +0000904 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000905 Result = llvm::APInt(DestWidth, 4, Space);
906 Result.setIsUnsigned(!DestSigned);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000907 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000908}
Anders Carlsson02a34c32008-07-08 14:30:00 +0000909
Chris Lattnera823ccf2008-07-11 18:11:29 +0000910//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +0000911// Float Evaluation
912//===----------------------------------------------------------------------===//
913
914namespace {
915class VISIBILITY_HIDDEN FloatExprEvaluator
916 : public StmtVisitor<FloatExprEvaluator, bool> {
917 EvalInfo &Info;
918 APFloat &Result;
919public:
920 FloatExprEvaluator(EvalInfo &info, APFloat &result)
921 : Info(info), Result(result) {}
922
923 bool VisitStmt(Stmt *S) {
924 return false;
925 }
926
927 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +0000928 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000929
Daniel Dunbar804ead02008-10-16 03:51:50 +0000930 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000931 bool VisitBinaryOperator(const BinaryOperator *E);
932 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000933 bool VisitCastExpr(CastExpr *E);
934 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000935};
936} // end anonymous namespace
937
938static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
939 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
940}
941
Chris Lattner87293782008-10-06 05:28:25 +0000942bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner87293782008-10-06 05:28:25 +0000943 switch (E->isBuiltinCall()) {
Chris Lattner27cde262008-10-06 05:53:16 +0000944 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +0000945 case Builtin::BI__builtin_huge_val:
946 case Builtin::BI__builtin_huge_valf:
947 case Builtin::BI__builtin_huge_vall:
948 case Builtin::BI__builtin_inf:
949 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000950 case Builtin::BI__builtin_infl: {
951 const llvm::fltSemantics &Sem =
952 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +0000953 Result = llvm::APFloat::getInf(Sem);
954 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000955 }
Chris Lattner667e1ee2008-10-06 06:31:58 +0000956
957 case Builtin::BI__builtin_nan:
958 case Builtin::BI__builtin_nanf:
959 case Builtin::BI__builtin_nanl:
960 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
961 // can't constant fold it.
962 if (const StringLiteral *S =
963 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
964 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000965 const llvm::fltSemantics &Sem =
966 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +0000967 Result = llvm::APFloat::getNaN(Sem);
968 return true;
969 }
970 }
971 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +0000972
973 case Builtin::BI__builtin_fabs:
974 case Builtin::BI__builtin_fabsf:
975 case Builtin::BI__builtin_fabsl:
976 if (!EvaluateFloat(E->getArg(0), Result, Info))
977 return false;
978
979 if (Result.isNegative())
980 Result.changeSign();
981 return true;
982
983 case Builtin::BI__builtin_copysign:
984 case Builtin::BI__builtin_copysignf:
985 case Builtin::BI__builtin_copysignl: {
986 APFloat RHS(0.);
987 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
988 !EvaluateFloat(E->getArg(1), RHS, Info))
989 return false;
990 Result.copySign(RHS);
991 return true;
992 }
Chris Lattner87293782008-10-06 05:28:25 +0000993 }
994}
995
Daniel Dunbar804ead02008-10-16 03:51:50 +0000996bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes1cea4f42008-11-19 17:44:31 +0000997 if (E->getOpcode() == UnaryOperator::Deref)
998 return false;
999
Daniel Dunbar804ead02008-10-16 03:51:50 +00001000 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1001 return false;
1002
1003 switch (E->getOpcode()) {
1004 default: return false;
1005 case UnaryOperator::Plus:
1006 return true;
1007 case UnaryOperator::Minus:
1008 Result.changeSign();
1009 return true;
1010 }
1011}
Chris Lattner87293782008-10-06 05:28:25 +00001012
Eli Friedman2f445492008-08-22 00:06:13 +00001013bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1014 // FIXME: Diagnostics? I really don't understand how the warnings
1015 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +00001016 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +00001017 if (!EvaluateFloat(E->getLHS(), Result, Info))
1018 return false;
1019 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1020 return false;
1021
1022 switch (E->getOpcode()) {
1023 default: return false;
1024 case BinaryOperator::Mul:
1025 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1026 return true;
1027 case BinaryOperator::Add:
1028 Result.add(RHS, APFloat::rmNearestTiesToEven);
1029 return true;
1030 case BinaryOperator::Sub:
1031 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1032 return true;
1033 case BinaryOperator::Div:
1034 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1035 return true;
1036 case BinaryOperator::Rem:
1037 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1038 return true;
1039 }
1040}
1041
1042bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1043 Result = E->getValue();
1044 return true;
1045}
1046
Eli Friedman7888b932008-11-12 09:44:48 +00001047bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1048 Expr* SubExpr = E->getSubExpr();
1049 const llvm::fltSemantics& destSemantics =
1050 Info.Ctx.getFloatTypeSemantics(E->getType());
1051 if (SubExpr->getType()->isIntegralType()) {
1052 APSInt IntResult;
1053 if (!EvaluateInteger(E, IntResult, Info))
1054 return false;
1055 Result = APFloat(destSemantics, 1);
1056 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1057 APFloat::rmNearestTiesToEven);
1058 return true;
1059 }
1060 if (SubExpr->getType()->isRealFloatingType()) {
1061 if (!Visit(SubExpr))
1062 return false;
1063 bool ignored;
1064 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1065 return true;
1066 }
1067
1068 return false;
1069}
1070
1071bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1072 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1073 return true;
1074}
1075
Eli Friedman2f445492008-08-22 00:06:13 +00001076//===----------------------------------------------------------------------===//
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001077// Complex Float Evaluation
1078//===----------------------------------------------------------------------===//
1079
1080namespace {
1081class VISIBILITY_HIDDEN ComplexFloatExprEvaluator
1082 : public StmtVisitor<ComplexFloatExprEvaluator, APValue> {
1083 EvalInfo &Info;
1084
1085public:
1086 ComplexFloatExprEvaluator(EvalInfo &info) : Info(info) {}
1087
1088 //===--------------------------------------------------------------------===//
1089 // Visitor Methods
1090 //===--------------------------------------------------------------------===//
1091
1092 APValue VisitStmt(Stmt *S) {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001093 return APValue();
1094 }
1095
1096 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1097
1098 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1099 APFloat Result(0.0);
1100 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1101 return APValue();
1102
1103 return APValue(APFloat(0.0), Result);
1104 }
1105
Anders Carlssonad2794c2008-11-16 21:51:21 +00001106 APValue VisitCastExpr(CastExpr *E) {
1107 Expr* SubExpr = E->getSubExpr();
1108
1109 if (SubExpr->getType()->isRealFloatingType()) {
1110 APFloat Result(0.0);
1111
1112 if (!EvaluateFloat(SubExpr, Result, Info))
1113 return APValue();
1114
1115 return APValue(Result, APFloat(0.0));
1116 }
1117
1118 // FIXME: Handle more casts.
1119 return APValue();
1120 }
1121
1122 APValue VisitBinaryOperator(const BinaryOperator *E);
1123
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001124};
1125} // end anonymous namespace
1126
1127static bool EvaluateComplexFloat(const Expr *E, APValue &Result, EvalInfo &Info)
1128{
1129 Result = ComplexFloatExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1130 return Result.isComplexFloat();
1131}
1132
Anders Carlssonad2794c2008-11-16 21:51:21 +00001133APValue ComplexFloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
1134{
1135 APValue Result, RHS;
1136
1137 if (!EvaluateComplexFloat(E->getLHS(), Result, Info))
1138 return APValue();
1139
1140 if (!EvaluateComplexFloat(E->getRHS(), RHS, Info))
1141 return APValue();
1142
1143 switch (E->getOpcode()) {
1144 default: return APValue();
1145 case BinaryOperator::Add:
1146 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1147 APFloat::rmNearestTiesToEven);
1148 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1149 APFloat::rmNearestTiesToEven);
1150 case BinaryOperator::Sub:
1151 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1152 APFloat::rmNearestTiesToEven);
1153 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1154 APFloat::rmNearestTiesToEven);
1155 }
1156
1157 return Result;
1158}
1159
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001160//===----------------------------------------------------------------------===//
Chris Lattneref069662008-11-16 21:24:15 +00001161// Top level Expr::Evaluate method.
Chris Lattnera823ccf2008-07-11 18:11:29 +00001162//===----------------------------------------------------------------------===//
1163
Chris Lattneref069662008-11-16 21:24:15 +00001164/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner87293782008-10-06 05:28:25 +00001165/// any crazy technique (that has nothing to do with language standards) that
1166/// we want to. If this function returns true, it returns the folded constant
1167/// in Result.
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001168bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1169 EvalInfo Info(Ctx, Result);
Anders Carlssondd8d41f2008-11-30 16:38:33 +00001170
Anders Carlssonc0328012008-07-08 05:49:43 +00001171 if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +00001172 llvm::APSInt sInt(32);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001173 if (!EvaluateInteger(this, sInt, Info))
1174 return false;
1175
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001176 Result.Val = APValue(sInt);
Eli Friedman2f445492008-08-22 00:06:13 +00001177 } else if (getType()->isPointerType()) {
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001178 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001179 return false;
Eli Friedman2f445492008-08-22 00:06:13 +00001180 } else if (getType()->isRealFloatingType()) {
1181 llvm::APFloat f(0.0);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001182 if (!EvaluateFloat(this, f, Info))
1183 return false;
1184
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001185 Result.Val = APValue(f);
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001186 } else if (getType()->isComplexType()) {
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001187 if (!EvaluateComplexFloat(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001188 return false;
Anders Carlssoncb6a2e82008-11-22 22:56:32 +00001189 } else
1190 return false;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001191
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001192 return true;
1193}
1194
1195bool Expr::Evaluate(APValue &Result, ASTContext &Ctx, bool *isEvaluated) const {
1196 EvalResult EvalResult;
1197
1198 if (!Evaluate(EvalResult, Ctx))
1199 return false;
1200
1201 Result = EvalResult.Val;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001202 if (isEvaluated)
Anders Carlsson501da1f2008-11-30 16:51:17 +00001203 *isEvaluated = !EvalResult.HasSideEffects;
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001204
Anders Carlssonb96c2062008-11-22 21:50:49 +00001205 return true;
Anders Carlssonc7436af2008-07-03 04:20:39 +00001206}
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001207
Chris Lattneref069662008-11-16 21:24:15 +00001208/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001209/// folded, but discard the result.
1210bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson197f6f72008-12-01 06:44:05 +00001211 EvalResult Result;
1212 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001213}
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001214
1215APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
1216 APValue V;
1217 bool Result = Evaluate(V, Ctx);
1218 assert(Result && "Could not evaluate expression");
1219 assert(V.isInt() && "Expression did not evaluate to integer");
1220
1221 return V.getInt();
1222}