blob: 7a83d6c063dad62c0868ca0073a807bfbeaeafa7 [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.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000159 unsigned i = 0;
160 for (RecordDecl::field_iterator Field = RD->field_begin(),
161 FieldEnd = RD->field_end();
162 Field != FieldEnd; (void)++Field, ++i) {
163 if (*Field == FD)
Eli Friedman7888b932008-11-12 09:44:48 +0000164 break;
165 }
166
167 result.setLValue(result.getLValueBase(),
168 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
169
170 return result;
171}
172
Anders Carlsson027f2882008-11-16 19:01:22 +0000173APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
174{
175 APValue Result;
176
177 if (!EvaluatePointer(E->getBase(), Result, Info))
178 return APValue();
179
180 APSInt Index;
181 if (!EvaluateInteger(E->getIdx(), Index, Info))
182 return APValue();
183
184 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
185
186 uint64_t Offset = Index.getSExtValue() * ElementSize;
187 Result.setLValue(Result.getLValueBase(),
188 Result.getLValueOffset() + Offset);
189 return Result;
190}
Eli Friedman7888b932008-11-12 09:44:48 +0000191
192//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000193// Pointer Evaluation
194//===----------------------------------------------------------------------===//
195
Anders Carlssoncad17b52008-07-08 05:13:58 +0000196namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000197class VISIBILITY_HIDDEN PointerExprEvaluator
198 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000199 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000200public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000201
Chris Lattner422373c2008-07-11 22:52:41 +0000202 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000203
Anders Carlsson02a34c32008-07-08 14:30:00 +0000204 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000205 return APValue();
206 }
207
208 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
209
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000210 APValue VisitBinaryOperator(const BinaryOperator *E);
211 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-11-12 09:44:48 +0000212 APValue VisitUnaryOperator(const UnaryOperator *E);
213 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
214 { return APValue(E, 0); }
215 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000216};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000217} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000218
Chris Lattner422373c2008-07-11 22:52:41 +0000219static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000220 if (!E->getType()->isPointerType())
221 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000222 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000223 return Result.isLValue();
224}
225
226APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
227 if (E->getOpcode() != BinaryOperator::Add &&
228 E->getOpcode() != BinaryOperator::Sub)
229 return APValue();
230
231 const Expr *PExp = E->getLHS();
232 const Expr *IExp = E->getRHS();
233 if (IExp->getType()->isPointerType())
234 std::swap(PExp, IExp);
235
236 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000237 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000238 return APValue();
239
240 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000241 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000242 return APValue();
243
Eli Friedman7888b932008-11-12 09:44:48 +0000244 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
245 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
246
Chris Lattnera823ccf2008-07-11 18:11:29 +0000247 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000248
Chris Lattnera823ccf2008-07-11 18:11:29 +0000249 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000250 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000251 else
Eli Friedman7888b932008-11-12 09:44:48 +0000252 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
253
Chris Lattnera823ccf2008-07-11 18:11:29 +0000254 return APValue(ResultLValue.getLValueBase(), Offset);
255}
Eli Friedman7888b932008-11-12 09:44:48 +0000256
257APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
258 if (E->getOpcode() == UnaryOperator::Extension) {
259 // FIXME: Deal with warnings?
260 return Visit(E->getSubExpr());
261 }
262
263 if (E->getOpcode() == UnaryOperator::AddrOf) {
264 APValue result;
265 if (EvaluateLValue(E->getSubExpr(), result, Info))
266 return result;
267 }
268
269 return APValue();
270}
Anders Carlsson4ab88da2008-12-05 05:24:13 +0000271
Chris Lattnera823ccf2008-07-11 18:11:29 +0000272
Chris Lattnera42f09a2008-07-11 19:10:17 +0000273APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000274 const Expr* SubExpr = E->getSubExpr();
275
276 // Check for pointer->pointer cast
277 if (SubExpr->getType()->isPointerType()) {
278 APValue Result;
Chris Lattner422373c2008-07-11 22:52:41 +0000279 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000280 return Result;
281 return APValue();
282 }
283
Eli Friedman3e64dd72008-07-27 05:46:18 +0000284 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000285 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000286 if (EvaluateInteger(SubExpr, Result, Info)) {
287 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000288 return APValue(0, Result.getZExtValue());
289 }
290 }
Eli Friedman7888b932008-11-12 09:44:48 +0000291
292 if (SubExpr->getType()->isFunctionType() ||
293 SubExpr->getType()->isArrayType()) {
294 APValue Result;
295 if (EvaluateLValue(SubExpr, Result, Info))
296 return Result;
297 return APValue();
298 }
299
300 //assert(0 && "Unhandled cast");
Chris Lattnera823ccf2008-07-11 18:11:29 +0000301 return APValue();
302}
303
Eli Friedman7888b932008-11-12 09:44:48 +0000304APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
305 bool BoolResult;
306 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
307 return APValue();
308
309 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
310
311 APValue Result;
312 if (EvaluatePointer(EvalExpr, Result, Info))
313 return Result;
314 return APValue();
315}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000316
317//===----------------------------------------------------------------------===//
318// Integer Evaluation
319//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000320
321namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000322class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000323 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000324 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000325 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000326public:
Chris Lattner422373c2008-07-11 22:52:41 +0000327 IntExprEvaluator(EvalInfo &info, APSInt &result)
328 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000329
Chris Lattner2c99c712008-07-11 19:24:49 +0000330 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner82437da2008-07-12 00:14:42 +0000331 return (unsigned)Info.Ctx.getIntWidth(T);
332 }
333
Anders Carlssonfa76d822008-11-30 18:14:57 +0000334 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000335 Info.EvalResult.DiagLoc = L;
336 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000337 Info.EvalResult.DiagExpr = E;
Chris Lattner82437da2008-07-12 00:14:42 +0000338 return true; // still a constant.
339 }
340
Anders Carlssonfa76d822008-11-30 18:14:57 +0000341 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner82437da2008-07-12 00:14:42 +0000342 // If this is in an unevaluated portion of the subexpression, ignore the
343 // error.
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000344 if (Info.ShortCircuit) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000345 // If error is ignored because the value isn't evaluated, get the real
346 // type at least to prevent errors downstream.
Anders Carlssonfa76d822008-11-30 18:14:57 +0000347 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
348 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattner82437da2008-07-12 00:14:42 +0000349 return true;
Chris Lattner438f3b12008-11-12 07:43:42 +0000350 }
Chris Lattner82437da2008-07-12 00:14:42 +0000351
Chris Lattner438f3b12008-11-12 07:43:42 +0000352 // Take the first error.
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000353 if (Info.EvalResult.Diag == 0) {
354 Info.EvalResult.DiagLoc = L;
355 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000356 Info.EvalResult.DiagExpr = E;
Chris Lattner438f3b12008-11-12 07:43:42 +0000357 }
Chris Lattner82437da2008-07-12 00:14:42 +0000358 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000359 }
360
Anders Carlssoncad17b52008-07-08 05:13:58 +0000361 //===--------------------------------------------------------------------===//
362 // Visitor Methods
363 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000364
365 bool VisitStmt(Stmt *) {
366 assert(0 && "This should be called on integers, stmts are not integers");
367 return false;
368 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000369
Chris Lattner438f3b12008-11-12 07:43:42 +0000370 bool VisitExpr(Expr *E) {
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000371 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssoncad17b52008-07-08 05:13:58 +0000372 }
373
Chris Lattnera42f09a2008-07-11 19:10:17 +0000374 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000375
Chris Lattner15e59112008-07-12 00:38:25 +0000376 bool VisitIntegerLiteral(const IntegerLiteral *E) {
377 Result = E->getValue();
378 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
379 return true;
380 }
381 bool VisitCharacterLiteral(const CharacterLiteral *E) {
382 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
383 Result = E->getValue();
384 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
385 return true;
386 }
387 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
388 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000389 // Per gcc docs "this built-in function ignores top level
390 // qualifiers". We need to use the canonical version to properly
391 // be able to strip CRV qualifiers from the type.
392 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
393 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
394 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
395 T1.getUnqualifiedType());
Chris Lattner15e59112008-07-12 00:38:25 +0000396 return true;
397 }
398 bool VisitDeclRefExpr(const DeclRefExpr *E);
399 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000400 bool VisitBinaryOperator(const BinaryOperator *E);
401 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000402 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000403
Chris Lattnerff579ff2008-07-12 01:15:53 +0000404 bool VisitCastExpr(CastExpr* E) {
Anders Carlssonfa76d822008-11-30 18:14:57 +0000405 return HandleCast(E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000406 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000407 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
408
Anders Carlsson027f2882008-11-16 19:01:22 +0000409 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000410 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson027f2882008-11-16 19:01:22 +0000411 Result = E->getValue();
412 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
413 return true;
414 }
415
416 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
417 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
418 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
419 return true;
420 }
421
Chris Lattner265a0892008-07-11 21:24:13 +0000422private:
Anders Carlssonfa76d822008-11-30 18:14:57 +0000423 bool HandleCast(CastExpr* E);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000424};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000425} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000426
Chris Lattner422373c2008-07-11 22:52:41 +0000427static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
428 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000429}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000430
Chris Lattner15e59112008-07-12 00:38:25 +0000431bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
432 // Enums are integer constant exprs.
433 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
434 Result = D->getInitVal();
Eli Friedman8b10a232008-12-08 02:21:03 +0000435 // FIXME: This is an ugly hack around the fact that enums don't set their
436 // signedness consistently; see PR3173
437 Result.setIsUnsigned(!E->getType()->isSignedIntegerType());
Chris Lattner15e59112008-07-12 00:38:25 +0000438 return true;
439 }
440
441 // Otherwise, random variable references are not constants.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000442 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000443}
444
Chris Lattner1eee9402008-10-06 06:40:35 +0000445/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
446/// as GCC.
447static int EvaluateBuiltinClassifyType(const CallExpr *E) {
448 // The following enum mimics the values returned by GCC.
449 enum gcc_type_class {
450 no_type_class = -1,
451 void_type_class, integer_type_class, char_type_class,
452 enumeral_type_class, boolean_type_class,
453 pointer_type_class, reference_type_class, offset_type_class,
454 real_type_class, complex_type_class,
455 function_type_class, method_type_class,
456 record_type_class, union_type_class,
457 array_type_class, string_type_class,
458 lang_type_class
459 };
460
461 // If no argument was supplied, default to "no_type_class". This isn't
462 // ideal, however it is what gcc does.
463 if (E->getNumArgs() == 0)
464 return no_type_class;
465
466 QualType ArgTy = E->getArg(0)->getType();
467 if (ArgTy->isVoidType())
468 return void_type_class;
469 else if (ArgTy->isEnumeralType())
470 return enumeral_type_class;
471 else if (ArgTy->isBooleanType())
472 return boolean_type_class;
473 else if (ArgTy->isCharType())
474 return string_type_class; // gcc doesn't appear to use char_type_class
475 else if (ArgTy->isIntegerType())
476 return integer_type_class;
477 else if (ArgTy->isPointerType())
478 return pointer_type_class;
479 else if (ArgTy->isReferenceType())
480 return reference_type_class;
481 else if (ArgTy->isRealType())
482 return real_type_class;
483 else if (ArgTy->isComplexType())
484 return complex_type_class;
485 else if (ArgTy->isFunctionType())
486 return function_type_class;
487 else if (ArgTy->isStructureType())
488 return record_type_class;
489 else if (ArgTy->isUnionType())
490 return union_type_class;
491 else if (ArgTy->isArrayType())
492 return array_type_class;
493 else if (ArgTy->isUnionType())
494 return union_type_class;
495 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
496 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
497 return -1;
498}
499
Chris Lattner15e59112008-07-12 00:38:25 +0000500bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
501 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000502
Chris Lattner87293782008-10-06 05:28:25 +0000503 switch (E->isBuiltinCall()) {
504 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000505 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner87293782008-10-06 05:28:25 +0000506 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000507 Result.setIsSigned(true);
508 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-10-06 05:28:25 +0000509 return true;
510
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000511 case Builtin::BI__builtin_constant_p:
Chris Lattner87293782008-10-06 05:28:25 +0000512 // __builtin_constant_p always has one operand: it returns true if that
513 // operand can be folded, false otherwise.
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000514 Result = E->getArg(0)->isEvaluatable(Info.Ctx);
Chris Lattner87293782008-10-06 05:28:25 +0000515 return true;
516 }
Chris Lattner15e59112008-07-12 00:38:25 +0000517}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000518
Chris Lattnera42f09a2008-07-11 19:10:17 +0000519bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000520 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000521 if (!Visit(E->getRHS()))
522 return false;
Anders Carlsson197f6f72008-12-01 06:44:05 +0000523
524 if (!Info.ShortCircuit) {
525 // If we can't evaluate the LHS, it must be because it has
526 // side effects.
527 if (!E->getLHS()->isEvaluatable(Info.Ctx))
528 Info.EvalResult.HasSideEffects = true;
529
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000530 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson197f6f72008-12-01 06:44:05 +0000531 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000532
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000533 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000534 }
535
536 if (E->isLogicalOp()) {
537 // These need to be handled specially because the operands aren't
538 // necessarily integral
Anders Carlsson501da1f2008-11-30 16:51:17 +0000539 bool lhsResult, rhsResult;
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000540
Anders Carlsson501da1f2008-11-30 16:51:17 +0000541 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000542 // We were able to evaluate the LHS, see if we can get away with not
543 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlsson501da1f2008-11-30 16:51:17 +0000544 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
545 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000546 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
547 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlsson501da1f2008-11-30 16:51:17 +0000548 Result = lhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000549
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000550 Info.ShortCircuit++;
Anders Carlsson501da1f2008-11-30 16:51:17 +0000551 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000552 Info.ShortCircuit--;
553
Anders Carlsson501da1f2008-11-30 16:51:17 +0000554 if (rhsEvaluated)
555 return true;
556
557 // FIXME: Return an extension warning saying that the RHS could not be
558 // evaluated.
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000559 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000560 }
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000561
Anders Carlsson501da1f2008-11-30 16:51:17 +0000562 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000563 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
564 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
565 if (E->getOpcode() == BinaryOperator::LOr)
Anders Carlsson501da1f2008-11-30 16:51:17 +0000566 Result = lhsResult || rhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000567 else
Anders Carlsson501da1f2008-11-30 16:51:17 +0000568 Result = lhsResult && rhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000569 return true;
570 }
571 } else {
Anders Carlsson501da1f2008-11-30 16:51:17 +0000572 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000573 // We can't evaluate the LHS; however, sometimes the result
574 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlsson501da1f2008-11-30 16:51:17 +0000575 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
576 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000577 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
578 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlsson501da1f2008-11-30 16:51:17 +0000579 Result = rhsResult;
580
581 // Since we werent able to evaluate the left hand side, it
582 // must have had side effects.
583 Info.EvalResult.HasSideEffects = true;
584
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000585 return true;
586 }
587 }
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000588 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000589
Eli Friedman14cc7542008-11-13 06:09:17 +0000590 return false;
591 }
592
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000593 QualType LHSTy = E->getLHS()->getType();
594 QualType RHSTy = E->getRHS()->getType();
595
596 if (LHSTy->isRealFloatingType() &&
597 RHSTy->isRealFloatingType()) {
598 APFloat RHS(0.0), LHS(0.0);
599
600 if (!EvaluateFloat(E->getRHS(), RHS, Info))
601 return false;
602
603 if (!EvaluateFloat(E->getLHS(), LHS, Info))
604 return false;
605
606 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000607
608 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
609
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000610 switch (E->getOpcode()) {
611 default:
612 assert(0 && "Invalid binary operator!");
613 case BinaryOperator::LT:
614 Result = CR == APFloat::cmpLessThan;
615 break;
616 case BinaryOperator::GT:
617 Result = CR == APFloat::cmpGreaterThan;
618 break;
619 case BinaryOperator::LE:
620 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
621 break;
622 case BinaryOperator::GE:
623 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
624 break;
625 case BinaryOperator::EQ:
626 Result = CR == APFloat::cmpEqual;
627 break;
628 case BinaryOperator::NE:
629 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
630 break;
631 }
632
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000633 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
634 return true;
635 }
636
Anders Carlsson027f2882008-11-16 19:01:22 +0000637 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000638 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson027f2882008-11-16 19:01:22 +0000639 APValue LHSValue;
640 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
641 return false;
642
643 APValue RHSValue;
644 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
645 return false;
646
647 // FIXME: Is this correct? What if only one of the operands has a base?
648 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
649 return false;
650
651 const QualType Type = E->getLHS()->getType();
652 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
653
654 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
655 D /= Info.Ctx.getTypeSize(ElementType) / 8;
656
Anders Carlsson027f2882008-11-16 19:01:22 +0000657 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000658 Result = D;
Anders Carlsson027f2882008-11-16 19:01:22 +0000659 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
660
661 return true;
662 }
663 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000664 if (!LHSTy->isIntegralType() ||
665 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000666 // We can't continue from here for non-integral types, and they
667 // could potentially confuse the following operations.
668 // FIXME: Deal with EQ and friends.
669 return false;
670 }
671
Anders Carlssond1aa5812008-07-08 14:35:21 +0000672 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000673 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000674 if (!Visit(E->getLHS())) {
Chris Lattner82437da2008-07-12 00:14:42 +0000675 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000676 }
Eli Friedman3e64dd72008-07-27 05:46:18 +0000677
Eli Friedman3e64dd72008-07-27 05:46:18 +0000678
679 // FIXME Maybe we want to succeed even where we can't evaluate the
680 // right side of LAnd/LOr?
681 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000682 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000683 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000684
Anders Carlssond1aa5812008-07-08 14:35:21 +0000685 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000686 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000687 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner82437da2008-07-12 00:14:42 +0000688 case BinaryOperator::Mul: Result *= RHS; return true;
689 case BinaryOperator::Add: Result += RHS; return true;
690 case BinaryOperator::Sub: Result -= RHS; return true;
691 case BinaryOperator::And: Result &= RHS; return true;
692 case BinaryOperator::Xor: Result ^= RHS; return true;
693 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000694 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000695 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000696 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000697 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000698 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000699 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000700 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000701 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000702 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000703 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000704 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000705 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000706 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000707 break;
708 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000709 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000710 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000711
Chris Lattner045502c2008-07-11 19:29:32 +0000712 case BinaryOperator::LT:
713 Result = Result < RHS;
714 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
715 break;
716 case BinaryOperator::GT:
717 Result = Result > RHS;
718 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
719 break;
720 case BinaryOperator::LE:
721 Result = Result <= RHS;
722 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
723 break;
724 case BinaryOperator::GE:
725 Result = Result >= RHS;
726 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
727 break;
728 case BinaryOperator::EQ:
729 Result = Result == RHS;
730 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
731 break;
732 case BinaryOperator::NE:
733 Result = Result != RHS;
734 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
735 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000736 case BinaryOperator::LAnd:
737 Result = Result != 0 && RHS != 0;
738 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
739 break;
740 case BinaryOperator::LOr:
741 Result = Result != 0 || RHS != 0;
742 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
743 break;
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000744 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000745
746 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000747 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000748}
749
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000750bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes308de752008-11-16 22:06:39 +0000751 bool Cond;
752 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000753 return false;
754
Nuno Lopes308de752008-11-16 22:06:39 +0000755 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000756}
757
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000758/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
759/// expression's type.
760bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
761 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000762 // Return the result in the right width.
763 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
764 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
765
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000766 QualType SrcTy = E->getTypeOfArgument();
767
Chris Lattner265a0892008-07-11 21:24:13 +0000768 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +0000769 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +0000770 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +0000771 return true;
772 }
Chris Lattner265a0892008-07-11 21:24:13 +0000773
774 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman7888b932008-11-12 09:44:48 +0000775 // FIXME: But alignof(vla) is!
Chris Lattner265a0892008-07-11 21:24:13 +0000776 if (!SrcTy->isConstantSizeType()) {
777 // FIXME: Should we attempt to evaluate this?
778 return false;
779 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000780
781 bool isSizeOf = E->isSizeOf();
Chris Lattner265a0892008-07-11 21:24:13 +0000782
783 // GCC extension: sizeof(function) = 1.
784 if (SrcTy->isFunctionType()) {
785 // FIXME: AlignOf shouldn't be unconditionally 4!
786 Result = isSizeOf ? 1 : 4;
787 return true;
788 }
789
790 // Get information about the size or align.
Chris Lattner422373c2008-07-11 22:52:41 +0000791 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattner265a0892008-07-11 21:24:13 +0000792 if (isSizeOf)
Eli Friedman7888b932008-11-12 09:44:48 +0000793 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000794 else
Chris Lattner422373c2008-07-11 22:52:41 +0000795 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000796 return true;
797}
798
Chris Lattnera42f09a2008-07-11 19:10:17 +0000799bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000800 // Special case unary operators that do not need their subexpression
801 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +0000802 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000803 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +0000804 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +0000805 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
806 return true;
807 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000808
809 if (E->getOpcode() == UnaryOperator::LNot) {
810 // LNot's operand isn't necessarily an integer, so we handle it specially.
811 bool bres;
812 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
813 return false;
814 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
815 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
816 Result = !bres;
817 return true;
818 }
819
Chris Lattner422373c2008-07-11 22:52:41 +0000820 // Get the operand value into 'Result'.
821 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000822 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000823
Chris Lattner400d7402008-07-11 22:15:16 +0000824 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000825 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000826 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
827 // See C99 6.6p3.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000828 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000829 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +0000830 // FIXME: Should extension allow i-c-e extension expressions in its scope?
831 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +0000832 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +0000833 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +0000834 break;
835 case UnaryOperator::Minus:
836 Result = -Result;
837 break;
838 case UnaryOperator::Not:
839 Result = ~Result;
840 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000841 }
842
843 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000844 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000845}
846
Chris Lattnerff579ff2008-07-12 01:15:53 +0000847/// HandleCast - This is used to evaluate implicit or explicit casts where the
848/// result type is integer.
Anders Carlssonfa76d822008-11-30 18:14:57 +0000849bool IntExprEvaluator::HandleCast(CastExpr *E) {
850 Expr *SubExpr = E->getSubExpr();
851 QualType DestType = E->getType();
852
Chris Lattner2c99c712008-07-11 19:24:49 +0000853 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000854
Eli Friedman7888b932008-11-12 09:44:48 +0000855 if (DestType->isBooleanType()) {
856 bool BoolResult;
857 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
858 return false;
859 Result.zextOrTrunc(DestWidth);
860 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
861 Result = BoolResult;
862 return true;
863 }
864
Anders Carlssond1aa5812008-07-08 14:35:21 +0000865 // Handle simple integer->integer casts.
Eli Friedman14cc7542008-11-13 06:09:17 +0000866 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000867 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000868 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000869
870 // Figure out if this is a truncate, extend or noop cast.
871 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman7888b932008-11-12 09:44:48 +0000872 Result.extOrTrunc(DestWidth);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000873 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
874 return true;
875 }
876
877 // FIXME: Clean this up!
878 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000879 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +0000880 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000881 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000882
Anders Carlssond1aa5812008-07-08 14:35:21 +0000883 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +0000884 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000885
Anders Carlsson8ab15c82008-07-08 16:49:00 +0000886 Result.extOrTrunc(DestWidth);
887 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +0000888 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
889 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000890 }
Eli Friedman7888b932008-11-12 09:44:48 +0000891
Chris Lattnerff579ff2008-07-12 01:15:53 +0000892 if (!SubExpr->getType()->isRealFloatingType())
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000893 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000894
Eli Friedman2f445492008-08-22 00:06:13 +0000895 APFloat F(0.0);
896 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000897 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000898
899 // Determine whether we are converting to unsigned or signed.
900 bool DestSigned = DestType->isSignedIntegerType();
901
902 // FIXME: Warning for overflow.
Dale Johannesen2461f612008-10-09 23:02:32 +0000903 uint64_t Space[4];
904 bool ignored;
Eli Friedman2f445492008-08-22 00:06:13 +0000905 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesen2461f612008-10-09 23:02:32 +0000906 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000907 Result = llvm::APInt(DestWidth, 4, Space);
908 Result.setIsUnsigned(!DestSigned);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000909 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000910}
Anders Carlsson02a34c32008-07-08 14:30:00 +0000911
Chris Lattnera823ccf2008-07-11 18:11:29 +0000912//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +0000913// Float Evaluation
914//===----------------------------------------------------------------------===//
915
916namespace {
917class VISIBILITY_HIDDEN FloatExprEvaluator
918 : public StmtVisitor<FloatExprEvaluator, bool> {
919 EvalInfo &Info;
920 APFloat &Result;
921public:
922 FloatExprEvaluator(EvalInfo &info, APFloat &result)
923 : Info(info), Result(result) {}
924
925 bool VisitStmt(Stmt *S) {
926 return false;
927 }
928
929 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +0000930 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000931
Daniel Dunbar804ead02008-10-16 03:51:50 +0000932 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000933 bool VisitBinaryOperator(const BinaryOperator *E);
934 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000935 bool VisitCastExpr(CastExpr *E);
936 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000937};
938} // end anonymous namespace
939
940static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
941 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
942}
943
Chris Lattner87293782008-10-06 05:28:25 +0000944bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner87293782008-10-06 05:28:25 +0000945 switch (E->isBuiltinCall()) {
Chris Lattner27cde262008-10-06 05:53:16 +0000946 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +0000947 case Builtin::BI__builtin_huge_val:
948 case Builtin::BI__builtin_huge_valf:
949 case Builtin::BI__builtin_huge_vall:
950 case Builtin::BI__builtin_inf:
951 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000952 case Builtin::BI__builtin_infl: {
953 const llvm::fltSemantics &Sem =
954 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +0000955 Result = llvm::APFloat::getInf(Sem);
956 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000957 }
Chris Lattner667e1ee2008-10-06 06:31:58 +0000958
959 case Builtin::BI__builtin_nan:
960 case Builtin::BI__builtin_nanf:
961 case Builtin::BI__builtin_nanl:
962 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
963 // can't constant fold it.
964 if (const StringLiteral *S =
965 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
966 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000967 const llvm::fltSemantics &Sem =
968 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +0000969 Result = llvm::APFloat::getNaN(Sem);
970 return true;
971 }
972 }
973 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +0000974
975 case Builtin::BI__builtin_fabs:
976 case Builtin::BI__builtin_fabsf:
977 case Builtin::BI__builtin_fabsl:
978 if (!EvaluateFloat(E->getArg(0), Result, Info))
979 return false;
980
981 if (Result.isNegative())
982 Result.changeSign();
983 return true;
984
985 case Builtin::BI__builtin_copysign:
986 case Builtin::BI__builtin_copysignf:
987 case Builtin::BI__builtin_copysignl: {
988 APFloat RHS(0.);
989 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
990 !EvaluateFloat(E->getArg(1), RHS, Info))
991 return false;
992 Result.copySign(RHS);
993 return true;
994 }
Chris Lattner87293782008-10-06 05:28:25 +0000995 }
996}
997
Daniel Dunbar804ead02008-10-16 03:51:50 +0000998bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes1cea4f42008-11-19 17:44:31 +0000999 if (E->getOpcode() == UnaryOperator::Deref)
1000 return false;
1001
Daniel Dunbar804ead02008-10-16 03:51:50 +00001002 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1003 return false;
1004
1005 switch (E->getOpcode()) {
1006 default: return false;
1007 case UnaryOperator::Plus:
1008 return true;
1009 case UnaryOperator::Minus:
1010 Result.changeSign();
1011 return true;
1012 }
1013}
Chris Lattner87293782008-10-06 05:28:25 +00001014
Eli Friedman2f445492008-08-22 00:06:13 +00001015bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1016 // FIXME: Diagnostics? I really don't understand how the warnings
1017 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +00001018 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +00001019 if (!EvaluateFloat(E->getLHS(), Result, Info))
1020 return false;
1021 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1022 return false;
1023
1024 switch (E->getOpcode()) {
1025 default: return false;
1026 case BinaryOperator::Mul:
1027 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1028 return true;
1029 case BinaryOperator::Add:
1030 Result.add(RHS, APFloat::rmNearestTiesToEven);
1031 return true;
1032 case BinaryOperator::Sub:
1033 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1034 return true;
1035 case BinaryOperator::Div:
1036 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1037 return true;
1038 case BinaryOperator::Rem:
1039 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1040 return true;
1041 }
1042}
1043
1044bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1045 Result = E->getValue();
1046 return true;
1047}
1048
Eli Friedman7888b932008-11-12 09:44:48 +00001049bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1050 Expr* SubExpr = E->getSubExpr();
1051 const llvm::fltSemantics& destSemantics =
1052 Info.Ctx.getFloatTypeSemantics(E->getType());
1053 if (SubExpr->getType()->isIntegralType()) {
1054 APSInt IntResult;
1055 if (!EvaluateInteger(E, IntResult, Info))
1056 return false;
1057 Result = APFloat(destSemantics, 1);
1058 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1059 APFloat::rmNearestTiesToEven);
1060 return true;
1061 }
1062 if (SubExpr->getType()->isRealFloatingType()) {
1063 if (!Visit(SubExpr))
1064 return false;
1065 bool ignored;
1066 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1067 return true;
1068 }
1069
1070 return false;
1071}
1072
1073bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1074 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1075 return true;
1076}
1077
Eli Friedman2f445492008-08-22 00:06:13 +00001078//===----------------------------------------------------------------------===//
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001079// Complex Float Evaluation
1080//===----------------------------------------------------------------------===//
1081
1082namespace {
1083class VISIBILITY_HIDDEN ComplexFloatExprEvaluator
1084 : public StmtVisitor<ComplexFloatExprEvaluator, APValue> {
1085 EvalInfo &Info;
1086
1087public:
1088 ComplexFloatExprEvaluator(EvalInfo &info) : Info(info) {}
1089
1090 //===--------------------------------------------------------------------===//
1091 // Visitor Methods
1092 //===--------------------------------------------------------------------===//
1093
1094 APValue VisitStmt(Stmt *S) {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001095 return APValue();
1096 }
1097
1098 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1099
1100 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1101 APFloat Result(0.0);
1102 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1103 return APValue();
1104
1105 return APValue(APFloat(0.0), Result);
1106 }
1107
Anders Carlssonad2794c2008-11-16 21:51:21 +00001108 APValue VisitCastExpr(CastExpr *E) {
1109 Expr* SubExpr = E->getSubExpr();
1110
1111 if (SubExpr->getType()->isRealFloatingType()) {
1112 APFloat Result(0.0);
1113
1114 if (!EvaluateFloat(SubExpr, Result, Info))
1115 return APValue();
1116
1117 return APValue(Result, APFloat(0.0));
1118 }
1119
1120 // FIXME: Handle more casts.
1121 return APValue();
1122 }
1123
1124 APValue VisitBinaryOperator(const BinaryOperator *E);
1125
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001126};
1127} // end anonymous namespace
1128
1129static bool EvaluateComplexFloat(const Expr *E, APValue &Result, EvalInfo &Info)
1130{
1131 Result = ComplexFloatExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1132 return Result.isComplexFloat();
1133}
1134
Anders Carlssonad2794c2008-11-16 21:51:21 +00001135APValue ComplexFloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
1136{
1137 APValue Result, RHS;
1138
1139 if (!EvaluateComplexFloat(E->getLHS(), Result, Info))
1140 return APValue();
1141
1142 if (!EvaluateComplexFloat(E->getRHS(), RHS, Info))
1143 return APValue();
1144
1145 switch (E->getOpcode()) {
1146 default: return APValue();
1147 case BinaryOperator::Add:
1148 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1149 APFloat::rmNearestTiesToEven);
1150 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1151 APFloat::rmNearestTiesToEven);
1152 case BinaryOperator::Sub:
1153 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1154 APFloat::rmNearestTiesToEven);
1155 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1156 APFloat::rmNearestTiesToEven);
1157 }
1158
1159 return Result;
1160}
1161
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001162//===----------------------------------------------------------------------===//
Chris Lattneref069662008-11-16 21:24:15 +00001163// Top level Expr::Evaluate method.
Chris Lattnera823ccf2008-07-11 18:11:29 +00001164//===----------------------------------------------------------------------===//
1165
Chris Lattneref069662008-11-16 21:24:15 +00001166/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner87293782008-10-06 05:28:25 +00001167/// any crazy technique (that has nothing to do with language standards) that
1168/// we want to. If this function returns true, it returns the folded constant
1169/// in Result.
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001170bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1171 EvalInfo Info(Ctx, Result);
Anders Carlssondd8d41f2008-11-30 16:38:33 +00001172
Anders Carlssonc0328012008-07-08 05:49:43 +00001173 if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +00001174 llvm::APSInt sInt(32);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001175 if (!EvaluateInteger(this, sInt, Info))
1176 return false;
1177
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001178 Result.Val = APValue(sInt);
Eli Friedman2f445492008-08-22 00:06:13 +00001179 } else if (getType()->isPointerType()) {
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001180 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001181 return false;
Eli Friedman2f445492008-08-22 00:06:13 +00001182 } else if (getType()->isRealFloatingType()) {
1183 llvm::APFloat f(0.0);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001184 if (!EvaluateFloat(this, f, Info))
1185 return false;
1186
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001187 Result.Val = APValue(f);
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001188 } else if (getType()->isComplexType()) {
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001189 if (!EvaluateComplexFloat(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001190 return false;
Anders Carlssoncb6a2e82008-11-22 22:56:32 +00001191 } else
1192 return false;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001193
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001194 return true;
1195}
1196
1197bool Expr::Evaluate(APValue &Result, ASTContext &Ctx, bool *isEvaluated) const {
1198 EvalResult EvalResult;
1199
1200 if (!Evaluate(EvalResult, Ctx))
1201 return false;
1202
1203 Result = EvalResult.Val;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001204 if (isEvaluated)
Anders Carlsson501da1f2008-11-30 16:51:17 +00001205 *isEvaluated = !EvalResult.HasSideEffects;
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001206
Anders Carlssonb96c2062008-11-22 21:50:49 +00001207 return true;
Anders Carlssonc7436af2008-07-03 04:20:39 +00001208}
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001209
Chris Lattneref069662008-11-16 21:24:15 +00001210/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001211/// folded, but discard the result.
1212bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson197f6f72008-12-01 06:44:05 +00001213 EvalResult Result;
1214 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001215}
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001216
1217APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
1218 APValue V;
1219 bool Result = Evaluate(V, Ctx);
1220 assert(Result && "Could not evaluate expression");
1221 assert(V.isInt() && "Expression did not evaluate to integer");
1222
1223 return V.getInt();
1224}