blob: d573236783eaf1155fda5ef08291f8c5fef30668 [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 Lattner545f39e2009-01-29 05:15:15 +000018#include "clang/AST/ASTDiagnostic.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);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +000058static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnera823ccf2008-07-11 18:11:29 +000059
60//===----------------------------------------------------------------------===//
Eli Friedman7888b932008-11-12 09:44:48 +000061// Misc utilities
62//===----------------------------------------------------------------------===//
63
64static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
65 if (E->getType()->isIntegralType()) {
66 APSInt IntResult;
67 if (!EvaluateInteger(E, IntResult, Info))
68 return false;
69 Result = IntResult != 0;
70 return true;
71 } else if (E->getType()->isRealFloatingType()) {
72 APFloat FloatResult(0.0);
73 if (!EvaluateFloat(E, FloatResult, Info))
74 return false;
75 Result = !FloatResult.isZero();
76 return true;
77 } else if (E->getType()->isPointerType()) {
78 APValue PointerResult;
79 if (!EvaluatePointer(E, PointerResult, Info))
80 return false;
81 // FIXME: Is this accurate for all kinds of bases? If not, what would
82 // the check look like?
83 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
84 return true;
85 }
86
87 return false;
88}
89
Daniel Dunbaraffa0e32009-01-29 06:16:07 +000090static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
91 APFloat &Value, ASTContext &Ctx) {
92 unsigned DestWidth = Ctx.getIntWidth(DestType);
93 // Determine whether we are converting to unsigned or signed.
94 bool DestSigned = DestType->isSignedIntegerType();
95
96 // FIXME: Warning for overflow.
97 uint64_t Space[4];
98 bool ignored;
99 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
100 llvm::APFloat::rmTowardZero, &ignored);
101 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
102}
103
104static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
105 APFloat &Value, ASTContext &Ctx) {
106 bool ignored;
107 APFloat Result = Value;
108 Result.convert(Ctx.getFloatTypeSemantics(DestType),
109 APFloat::rmNearestTiesToEven, &ignored);
110 return Result;
111}
112
113static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
114 APSInt &Value, ASTContext &Ctx) {
115 unsigned DestWidth = Ctx.getIntWidth(DestType);
116 APSInt Result = Value;
117 // Figure out if this is a truncate, extend or noop cast.
118 // If the input is signed, do a sign extend, noop, or truncate.
119 Result.extOrTrunc(DestWidth);
120 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
121 return Result;
122}
123
124static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
125 APSInt &Value, ASTContext &Ctx) {
126
127 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
128 Result.convertFromAPInt(Value, Value.isSigned(),
129 APFloat::rmNearestTiesToEven);
130 return Result;
131}
132
Eli Friedman7888b932008-11-12 09:44:48 +0000133//===----------------------------------------------------------------------===//
134// LValue Evaluation
135//===----------------------------------------------------------------------===//
136namespace {
137class VISIBILITY_HIDDEN LValueExprEvaluator
138 : public StmtVisitor<LValueExprEvaluator, APValue> {
139 EvalInfo &Info;
140public:
141
142 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
143
144 APValue VisitStmt(Stmt *S) {
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000145#if 0
Eli Friedman7888b932008-11-12 09:44:48 +0000146 // FIXME: Remove this when we support more expressions.
147 printf("Unhandled pointer statement\n");
148 S->dump();
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000149#endif
Eli Friedman7888b932008-11-12 09:44:48 +0000150 return APValue();
151 }
152
153 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssone284ebe2008-11-24 04:41:22 +0000154 APValue VisitDeclRefExpr(DeclRefExpr *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000155 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
156 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
157 APValue VisitMemberExpr(MemberExpr *E);
158 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
Anders Carlsson027f2882008-11-16 19:01:22 +0000159 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000160};
161} // end anonymous namespace
162
163static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
164 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
165 return Result.isLValue();
166}
167
Anders Carlssone284ebe2008-11-24 04:41:22 +0000168APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
169{
170 if (!E->hasGlobalStorage())
171 return APValue();
172
173 return APValue(E, 0);
174}
175
Eli Friedman7888b932008-11-12 09:44:48 +0000176APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
177 if (E->isFileScope())
178 return APValue(E, 0);
179 return APValue();
180}
181
182APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
183 APValue result;
184 QualType Ty;
185 if (E->isArrow()) {
186 if (!EvaluatePointer(E->getBase(), result, Info))
187 return APValue();
188 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
189 } else {
190 result = Visit(E->getBase());
191 if (result.isUninit())
192 return APValue();
193 Ty = E->getBase()->getType();
194 }
195
196 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
197 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor82d44772008-12-20 23:49:58 +0000198
199 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
200 if (!FD) // FIXME: deal with other kinds of member expressions
201 return APValue();
Eli Friedman7888b932008-11-12 09:44:48 +0000202
203 // FIXME: This is linear time.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000204 unsigned i = 0;
205 for (RecordDecl::field_iterator Field = RD->field_begin(),
206 FieldEnd = RD->field_end();
207 Field != FieldEnd; (void)++Field, ++i) {
208 if (*Field == FD)
Eli Friedman7888b932008-11-12 09:44:48 +0000209 break;
210 }
211
212 result.setLValue(result.getLValueBase(),
213 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
214
215 return result;
216}
217
Anders Carlsson027f2882008-11-16 19:01:22 +0000218APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
219{
220 APValue Result;
221
222 if (!EvaluatePointer(E->getBase(), Result, Info))
223 return APValue();
224
225 APSInt Index;
226 if (!EvaluateInteger(E->getIdx(), Index, Info))
227 return APValue();
228
229 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
230
231 uint64_t Offset = Index.getSExtValue() * ElementSize;
232 Result.setLValue(Result.getLValueBase(),
233 Result.getLValueOffset() + Offset);
234 return Result;
235}
Eli Friedman7888b932008-11-12 09:44:48 +0000236
237//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000238// Pointer Evaluation
239//===----------------------------------------------------------------------===//
240
Anders Carlssoncad17b52008-07-08 05:13:58 +0000241namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000242class VISIBILITY_HIDDEN PointerExprEvaluator
243 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000244 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000245public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000246
Chris Lattner422373c2008-07-11 22:52:41 +0000247 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000248
Anders Carlsson02a34c32008-07-08 14:30:00 +0000249 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000250 return APValue();
251 }
252
253 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
254
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000255 APValue VisitBinaryOperator(const BinaryOperator *E);
256 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-11-12 09:44:48 +0000257 APValue VisitUnaryOperator(const UnaryOperator *E);
258 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
259 { return APValue(E, 0); }
Eli Friedmanf1941132009-01-25 01:21:06 +0000260 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
261 { return APValue(E, 0); }
Eli Friedman67f4ac52009-01-25 01:54:01 +0000262 APValue VisitCallExpr(CallExpr *E);
Mike Stumpd55240e2009-02-19 01:01:04 +0000263 APValue VisitBlockExpr(BlockExpr *E) { return APValue(E, 0); }
Eli Friedman7888b932008-11-12 09:44:48 +0000264 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000265};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000266} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000267
Chris Lattner422373c2008-07-11 22:52:41 +0000268static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Mike Stump5b601ff2009-02-18 21:44:49 +0000269 if (!E->getType()->isPointerType()
270 && !E->getType()->isBlockPointerType())
Chris Lattnera823ccf2008-07-11 18:11:29 +0000271 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000272 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000273 return Result.isLValue();
274}
275
276APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
277 if (E->getOpcode() != BinaryOperator::Add &&
278 E->getOpcode() != BinaryOperator::Sub)
279 return APValue();
280
281 const Expr *PExp = E->getLHS();
282 const Expr *IExp = E->getRHS();
283 if (IExp->getType()->isPointerType())
284 std::swap(PExp, IExp);
285
286 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000287 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000288 return APValue();
289
290 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000291 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000292 return APValue();
293
Eli Friedman7888b932008-11-12 09:44:48 +0000294 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
295 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
296
Chris Lattnera823ccf2008-07-11 18:11:29 +0000297 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000298
Chris Lattnera823ccf2008-07-11 18:11:29 +0000299 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000300 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000301 else
Eli Friedman7888b932008-11-12 09:44:48 +0000302 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
303
Chris Lattnera823ccf2008-07-11 18:11:29 +0000304 return APValue(ResultLValue.getLValueBase(), Offset);
305}
Eli Friedman7888b932008-11-12 09:44:48 +0000306
307APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
308 if (E->getOpcode() == UnaryOperator::Extension) {
309 // FIXME: Deal with warnings?
310 return Visit(E->getSubExpr());
311 }
312
313 if (E->getOpcode() == UnaryOperator::AddrOf) {
314 APValue result;
315 if (EvaluateLValue(E->getSubExpr(), result, Info))
316 return result;
317 }
318
319 return APValue();
320}
Anders Carlsson4ab88da2008-12-05 05:24:13 +0000321
Chris Lattnera823ccf2008-07-11 18:11:29 +0000322
Chris Lattnera42f09a2008-07-11 19:10:17 +0000323APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000324 const Expr* SubExpr = E->getSubExpr();
325
326 // Check for pointer->pointer cast
327 if (SubExpr->getType()->isPointerType()) {
328 APValue Result;
Chris Lattner422373c2008-07-11 22:52:41 +0000329 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000330 return Result;
331 return APValue();
332 }
333
Eli Friedman3e64dd72008-07-27 05:46:18 +0000334 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000335 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000336 if (EvaluateInteger(SubExpr, Result, Info)) {
337 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000338 return APValue(0, Result.getZExtValue());
339 }
340 }
Eli Friedman7888b932008-11-12 09:44:48 +0000341
342 if (SubExpr->getType()->isFunctionType() ||
343 SubExpr->getType()->isArrayType()) {
344 APValue Result;
345 if (EvaluateLValue(SubExpr, Result, Info))
346 return Result;
347 return APValue();
348 }
349
350 //assert(0 && "Unhandled cast");
Chris Lattnera823ccf2008-07-11 18:11:29 +0000351 return APValue();
352}
353
Eli Friedman67f4ac52009-01-25 01:54:01 +0000354APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000355 if (E->isBuiltinCall(Info.Ctx) ==
356 Builtin::BI__builtin___CFStringMakeConstantString)
Eli Friedman67f4ac52009-01-25 01:54:01 +0000357 return APValue(E, 0);
358 return APValue();
359}
360
Eli Friedman7888b932008-11-12 09:44:48 +0000361APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
362 bool BoolResult;
363 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
364 return APValue();
365
366 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
367
368 APValue Result;
369 if (EvaluatePointer(EvalExpr, Result, Info))
370 return Result;
371 return APValue();
372}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000373
374//===----------------------------------------------------------------------===//
Nate Begemand6d2f772009-01-18 03:20:47 +0000375// Vector Evaluation
376//===----------------------------------------------------------------------===//
377
378namespace {
379 class VISIBILITY_HIDDEN VectorExprEvaluator
380 : public StmtVisitor<VectorExprEvaluator, APValue> {
381 EvalInfo &Info;
382 public:
383
384 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
385
386 APValue VisitStmt(Stmt *S) {
387 return APValue();
388 }
389
390 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
391 APValue VisitCastExpr(const CastExpr* E);
392 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
393 APValue VisitInitListExpr(const InitListExpr *E);
394 };
395} // end anonymous namespace
396
397static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
398 if (!E->getType()->isVectorType())
399 return false;
400 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
401 return !Result.isUninit();
402}
403
404APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
405 const Expr* SE = E->getSubExpr();
406
407 // Check for vector->vector bitcast.
408 if (SE->getType()->isVectorType())
409 return this->Visit(const_cast<Expr*>(SE));
410
411 return APValue();
412}
413
414APValue
415VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
416 return this->Visit(const_cast<Expr*>(E->getInitializer()));
417}
418
419APValue
420VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
421 const VectorType *VT = E->getType()->getAsVectorType();
422 unsigned NumInits = E->getNumInits();
423
424 if (!VT || VT->getNumElements() != NumInits)
425 return APValue();
426
427 QualType EltTy = VT->getElementType();
428 llvm::SmallVector<APValue, 4> Elements;
429
430 for (unsigned i = 0; i < NumInits; i++) {
431 if (EltTy->isIntegerType()) {
432 llvm::APSInt sInt(32);
433 if (!EvaluateInteger(E->getInit(i), sInt, Info))
434 return APValue();
435 Elements.push_back(APValue(sInt));
436 } else {
437 llvm::APFloat f(0.0);
438 if (!EvaluateFloat(E->getInit(i), f, Info))
439 return APValue();
440 Elements.push_back(APValue(f));
441 }
442 }
443 return APValue(&Elements[0], Elements.size());
444}
445
446//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000447// Integer Evaluation
448//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000449
450namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000451class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000452 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000453 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000454 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000455public:
Chris Lattner422373c2008-07-11 22:52:41 +0000456 IntExprEvaluator(EvalInfo &info, APSInt &result)
457 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000458
Chris Lattner2c99c712008-07-11 19:24:49 +0000459 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner82437da2008-07-12 00:14:42 +0000460 return (unsigned)Info.Ctx.getIntWidth(T);
461 }
462
Anders Carlssonfa76d822008-11-30 18:14:57 +0000463 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000464 Info.EvalResult.DiagLoc = L;
465 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000466 Info.EvalResult.DiagExpr = E;
Chris Lattner82437da2008-07-12 00:14:42 +0000467 return true; // still a constant.
468 }
469
Anders Carlssonfa76d822008-11-30 18:14:57 +0000470 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner82437da2008-07-12 00:14:42 +0000471 // If this is in an unevaluated portion of the subexpression, ignore the
472 // error.
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000473 if (Info.ShortCircuit) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000474 // If error is ignored because the value isn't evaluated, get the real
475 // type at least to prevent errors downstream.
Anders Carlssonfa76d822008-11-30 18:14:57 +0000476 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
477 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattner82437da2008-07-12 00:14:42 +0000478 return true;
Chris Lattner438f3b12008-11-12 07:43:42 +0000479 }
Chris Lattner82437da2008-07-12 00:14:42 +0000480
Chris Lattner438f3b12008-11-12 07:43:42 +0000481 // Take the first error.
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000482 if (Info.EvalResult.Diag == 0) {
483 Info.EvalResult.DiagLoc = L;
484 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000485 Info.EvalResult.DiagExpr = E;
Chris Lattner438f3b12008-11-12 07:43:42 +0000486 }
Chris Lattner82437da2008-07-12 00:14:42 +0000487 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000488 }
489
Anders Carlssoncad17b52008-07-08 05:13:58 +0000490 //===--------------------------------------------------------------------===//
491 // Visitor Methods
492 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000493
494 bool VisitStmt(Stmt *) {
495 assert(0 && "This should be called on integers, stmts are not integers");
496 return false;
497 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000498
Chris Lattner438f3b12008-11-12 07:43:42 +0000499 bool VisitExpr(Expr *E) {
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000500 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssoncad17b52008-07-08 05:13:58 +0000501 }
502
Chris Lattnera42f09a2008-07-11 19:10:17 +0000503 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000504
Chris Lattner15e59112008-07-12 00:38:25 +0000505 bool VisitIntegerLiteral(const IntegerLiteral *E) {
506 Result = E->getValue();
507 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
508 return true;
509 }
510 bool VisitCharacterLiteral(const CharacterLiteral *E) {
511 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
512 Result = E->getValue();
513 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
514 return true;
515 }
516 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
517 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000518 // Per gcc docs "this built-in function ignores top level
519 // qualifiers". We need to use the canonical version to properly
520 // be able to strip CRV qualifiers from the type.
521 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
522 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
523 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
524 T1.getUnqualifiedType());
Chris Lattner15e59112008-07-12 00:38:25 +0000525 return true;
526 }
527 bool VisitDeclRefExpr(const DeclRefExpr *E);
528 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000529 bool VisitBinaryOperator(const BinaryOperator *E);
530 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000531 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000532
Daniel Dunbaraffa0e32009-01-29 06:16:07 +0000533 bool VisitCastExpr(CastExpr* E);
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000534 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
535
Anders Carlsson027f2882008-11-16 19:01:22 +0000536 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000537 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson027f2882008-11-16 19:01:22 +0000538 Result = E->getValue();
539 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
540 return true;
541 }
542
Anders Carlsson774f9c72008-12-21 22:39:40 +0000543 bool VisitGNUNullExpr(const GNUNullExpr *E) {
544 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
545 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
546 return true;
547 }
548
Anders Carlsson027f2882008-11-16 19:01:22 +0000549 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
550 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
551 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
552 return true;
553 }
554
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000555 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
556 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbar8360a9c2009-02-17 23:20:26 +0000557 Result = E->EvaluateTrait();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000558 return true;
559 }
560
Chris Lattner265a0892008-07-11 21:24:13 +0000561private:
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000562 unsigned GetAlignOfExpr(const Expr *E);
563 unsigned GetAlignOfType(QualType T);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000564};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000565} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000566
Chris Lattner422373c2008-07-11 22:52:41 +0000567static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
568 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000569}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000570
Chris Lattner15e59112008-07-12 00:38:25 +0000571bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
572 // Enums are integer constant exprs.
573 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
574 Result = D->getInitVal();
Eli Friedman8b10a232008-12-08 02:21:03 +0000575 // FIXME: This is an ugly hack around the fact that enums don't set their
576 // signedness consistently; see PR3173
577 Result.setIsUnsigned(!E->getType()->isSignedIntegerType());
Chris Lattner15e59112008-07-12 00:38:25 +0000578 return true;
579 }
Sebastian Redl410dd872009-02-08 15:51:17 +0000580
581 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
582 if (Info.Ctx.getLangOptions().CPlusPlus &&
583 E->getType().getCVRQualifiers() == QualType::Const) {
584 if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
585 if (const Expr *Init = D->getInit())
586 return Visit(const_cast<Expr*>(Init));
587 }
588 }
589
Chris Lattner15e59112008-07-12 00:38:25 +0000590 // Otherwise, random variable references are not constants.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000591 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000592}
593
Chris Lattner1eee9402008-10-06 06:40:35 +0000594/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
595/// as GCC.
596static int EvaluateBuiltinClassifyType(const CallExpr *E) {
597 // The following enum mimics the values returned by GCC.
598 enum gcc_type_class {
599 no_type_class = -1,
600 void_type_class, integer_type_class, char_type_class,
601 enumeral_type_class, boolean_type_class,
602 pointer_type_class, reference_type_class, offset_type_class,
603 real_type_class, complex_type_class,
604 function_type_class, method_type_class,
605 record_type_class, union_type_class,
606 array_type_class, string_type_class,
607 lang_type_class
608 };
609
610 // If no argument was supplied, default to "no_type_class". This isn't
611 // ideal, however it is what gcc does.
612 if (E->getNumArgs() == 0)
613 return no_type_class;
614
615 QualType ArgTy = E->getArg(0)->getType();
616 if (ArgTy->isVoidType())
617 return void_type_class;
618 else if (ArgTy->isEnumeralType())
619 return enumeral_type_class;
620 else if (ArgTy->isBooleanType())
621 return boolean_type_class;
622 else if (ArgTy->isCharType())
623 return string_type_class; // gcc doesn't appear to use char_type_class
624 else if (ArgTy->isIntegerType())
625 return integer_type_class;
626 else if (ArgTy->isPointerType())
627 return pointer_type_class;
628 else if (ArgTy->isReferenceType())
629 return reference_type_class;
630 else if (ArgTy->isRealType())
631 return real_type_class;
632 else if (ArgTy->isComplexType())
633 return complex_type_class;
634 else if (ArgTy->isFunctionType())
635 return function_type_class;
636 else if (ArgTy->isStructureType())
637 return record_type_class;
638 else if (ArgTy->isUnionType())
639 return union_type_class;
640 else if (ArgTy->isArrayType())
641 return array_type_class;
642 else if (ArgTy->isUnionType())
643 return union_type_class;
644 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
645 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
646 return -1;
647}
648
Chris Lattner15e59112008-07-12 00:38:25 +0000649bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
650 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000651
Douglas Gregorb5af7382009-02-14 18:57:46 +0000652 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner87293782008-10-06 05:28:25 +0000653 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000654 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner87293782008-10-06 05:28:25 +0000655 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000656 Result.setIsSigned(true);
657 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-10-06 05:28:25 +0000658 return true;
659
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000660 case Builtin::BI__builtin_constant_p:
Chris Lattner87293782008-10-06 05:28:25 +0000661 // __builtin_constant_p always has one operand: it returns true if that
662 // operand can be folded, false otherwise.
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000663 Result = E->getArg(0)->isEvaluatable(Info.Ctx);
Chris Lattner87293782008-10-06 05:28:25 +0000664 return true;
665 }
Chris Lattner15e59112008-07-12 00:38:25 +0000666}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000667
Chris Lattnera42f09a2008-07-11 19:10:17 +0000668bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000669 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000670 if (!Visit(E->getRHS()))
671 return false;
Anders Carlsson197f6f72008-12-01 06:44:05 +0000672
673 if (!Info.ShortCircuit) {
674 // If we can't evaluate the LHS, it must be because it has
675 // side effects.
676 if (!E->getLHS()->isEvaluatable(Info.Ctx))
677 Info.EvalResult.HasSideEffects = true;
678
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000679 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson197f6f72008-12-01 06:44:05 +0000680 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000681
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000682 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000683 }
684
685 if (E->isLogicalOp()) {
686 // These need to be handled specially because the operands aren't
687 // necessarily integral
Anders Carlsson501da1f2008-11-30 16:51:17 +0000688 bool lhsResult, rhsResult;
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000689
Anders Carlsson501da1f2008-11-30 16:51:17 +0000690 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000691 // We were able to evaluate the LHS, see if we can get away with not
692 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlsson501da1f2008-11-30 16:51:17 +0000693 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
694 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000695 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
696 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlsson501da1f2008-11-30 16:51:17 +0000697 Result = lhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000698
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000699 Info.ShortCircuit++;
Anders Carlsson501da1f2008-11-30 16:51:17 +0000700 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000701 Info.ShortCircuit--;
702
Anders Carlsson501da1f2008-11-30 16:51:17 +0000703 if (rhsEvaluated)
704 return true;
705
706 // FIXME: Return an extension warning saying that the RHS could not be
707 // evaluated.
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000708 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000709 }
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000710
Anders Carlsson501da1f2008-11-30 16:51:17 +0000711 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000712 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
713 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
714 if (E->getOpcode() == BinaryOperator::LOr)
Anders Carlsson501da1f2008-11-30 16:51:17 +0000715 Result = lhsResult || rhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000716 else
Anders Carlsson501da1f2008-11-30 16:51:17 +0000717 Result = lhsResult && rhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000718 return true;
719 }
720 } else {
Anders Carlsson501da1f2008-11-30 16:51:17 +0000721 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000722 // We can't evaluate the LHS; however, sometimes the result
723 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlsson501da1f2008-11-30 16:51:17 +0000724 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
725 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000726 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
727 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlsson501da1f2008-11-30 16:51:17 +0000728 Result = rhsResult;
729
730 // Since we werent able to evaluate the left hand side, it
731 // must have had side effects.
732 Info.EvalResult.HasSideEffects = true;
733
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000734 return true;
735 }
736 }
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000737 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000738
Eli Friedman14cc7542008-11-13 06:09:17 +0000739 return false;
740 }
741
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000742 QualType LHSTy = E->getLHS()->getType();
743 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000744
745 if (LHSTy->isAnyComplexType()) {
746 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
747 APValue LHS, RHS;
748
749 if (!EvaluateComplex(E->getLHS(), LHS, Info))
750 return false;
751
752 if (!EvaluateComplex(E->getRHS(), RHS, Info))
753 return false;
754
755 if (LHS.isComplexFloat()) {
756 APFloat::cmpResult CR_r =
757 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
758 APFloat::cmpResult CR_i =
759 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
760
761 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
762 if (E->getOpcode() == BinaryOperator::EQ)
763 Result = (CR_r == APFloat::cmpEqual &&
764 CR_i == APFloat::cmpEqual);
765 else if (E->getOpcode() == BinaryOperator::NE)
766 Result = ((CR_r == APFloat::cmpGreaterThan ||
767 CR_r == APFloat::cmpLessThan) &&
768 (CR_i == APFloat::cmpGreaterThan ||
769 CR_i == APFloat::cmpLessThan));
770 else
771 assert(0 && "Invalid complex compartison.");
772 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
773 return true;
774 } else {
775 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
776 if (E->getOpcode() == BinaryOperator::EQ)
777 Result = (LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
778 LHS.getComplexIntImag() == RHS.getComplexIntImag());
779 else if (E->getOpcode() == BinaryOperator::NE)
780 Result = (LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
781 LHS.getComplexIntImag() != RHS.getComplexIntImag());
782 else
783 assert(0 && "Invalid complex compartison.");
784 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
785 return true;
786 }
787 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000788
789 if (LHSTy->isRealFloatingType() &&
790 RHSTy->isRealFloatingType()) {
791 APFloat RHS(0.0), LHS(0.0);
792
793 if (!EvaluateFloat(E->getRHS(), RHS, Info))
794 return false;
795
796 if (!EvaluateFloat(E->getLHS(), LHS, Info))
797 return false;
798
799 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000800
801 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
802
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000803 switch (E->getOpcode()) {
804 default:
805 assert(0 && "Invalid binary operator!");
806 case BinaryOperator::LT:
807 Result = CR == APFloat::cmpLessThan;
808 break;
809 case BinaryOperator::GT:
810 Result = CR == APFloat::cmpGreaterThan;
811 break;
812 case BinaryOperator::LE:
813 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
814 break;
815 case BinaryOperator::GE:
816 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
817 break;
818 case BinaryOperator::EQ:
819 Result = CR == APFloat::cmpEqual;
820 break;
821 case BinaryOperator::NE:
822 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
823 break;
824 }
825
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000826 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
827 return true;
828 }
829
Anders Carlsson027f2882008-11-16 19:01:22 +0000830 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000831 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson027f2882008-11-16 19:01:22 +0000832 APValue LHSValue;
833 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
834 return false;
835
836 APValue RHSValue;
837 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
838 return false;
839
840 // FIXME: Is this correct? What if only one of the operands has a base?
841 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
842 return false;
843
844 const QualType Type = E->getLHS()->getType();
845 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
846
847 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
848 D /= Info.Ctx.getTypeSize(ElementType) / 8;
849
Anders Carlsson027f2882008-11-16 19:01:22 +0000850 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000851 Result = D;
Anders Carlsson027f2882008-11-16 19:01:22 +0000852 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
853
854 return true;
855 }
856 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000857 if (!LHSTy->isIntegralType() ||
858 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000859 // We can't continue from here for non-integral types, and they
860 // could potentially confuse the following operations.
861 // FIXME: Deal with EQ and friends.
862 return false;
863 }
864
Anders Carlssond1aa5812008-07-08 14:35:21 +0000865 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000866 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000867 if (!Visit(E->getLHS())) {
Chris Lattner82437da2008-07-12 00:14:42 +0000868 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000869 }
Eli Friedman3e64dd72008-07-27 05:46:18 +0000870
Eli Friedman3e64dd72008-07-27 05:46:18 +0000871
872 // FIXME Maybe we want to succeed even where we can't evaluate the
873 // right side of LAnd/LOr?
874 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000875 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000876 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000877
Anders Carlssond1aa5812008-07-08 14:35:21 +0000878 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000879 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000880 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner82437da2008-07-12 00:14:42 +0000881 case BinaryOperator::Mul: Result *= RHS; return true;
882 case BinaryOperator::Add: Result += RHS; return true;
883 case BinaryOperator::Sub: Result -= RHS; return true;
884 case BinaryOperator::And: Result &= RHS; return true;
885 case BinaryOperator::Xor: Result ^= RHS; return true;
886 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000887 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000888 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000889 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000890 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000891 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000892 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000893 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000894 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000895 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000896 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000897 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000898 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000899 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000900 break;
901 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000902 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000903 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000904
Chris Lattner045502c2008-07-11 19:29:32 +0000905 case BinaryOperator::LT:
906 Result = Result < RHS;
907 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
908 break;
909 case BinaryOperator::GT:
910 Result = Result > RHS;
911 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
912 break;
913 case BinaryOperator::LE:
914 Result = Result <= RHS;
915 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
916 break;
917 case BinaryOperator::GE:
918 Result = Result >= RHS;
919 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
920 break;
921 case BinaryOperator::EQ:
922 Result = Result == RHS;
923 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
924 break;
925 case BinaryOperator::NE:
926 Result = Result != RHS;
927 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
928 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000929 case BinaryOperator::LAnd:
930 Result = Result != 0 && RHS != 0;
931 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
932 break;
933 case BinaryOperator::LOr:
934 Result = Result != 0 || RHS != 0;
935 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
936 break;
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000937 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000938
939 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000940 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000941}
942
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000943bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes308de752008-11-16 22:06:39 +0000944 bool Cond;
945 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000946 return false;
947
Nuno Lopes308de752008-11-16 22:06:39 +0000948 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000949}
950
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000951unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
Chris Lattnere3f61e12009-01-24 21:09:06 +0000952 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
953
954 // __alignof__(void) = 1 as a gcc extension.
955 if (Ty->isVoidType())
956 return 1;
957
958 // GCC extension: alignof(function) = 4.
959 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the
960 // attribute(align) directive.
961 if (Ty->isFunctionType())
962 return 4;
963
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000964 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty))
965 return GetAlignOfType(QualType(EXTQT->getBaseType(), 0));
Chris Lattnere3f61e12009-01-24 21:09:06 +0000966
967 // alignof VLA/incomplete array.
968 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
969 return GetAlignOfType(VAT->getElementType());
970
971 // sizeof (objc class)?
972 if (isa<ObjCInterfaceType>(Ty))
973 return 1; // FIXME: This probably isn't right.
974
975 // Get information about the alignment.
976 unsigned CharSize = Info.Ctx.Target.getCharWidth();
977 return Info.Ctx.getTypeAlign(Ty) / CharSize;
978}
979
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000980unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
981 E = E->IgnoreParens();
982
983 // alignof decl is always accepted, even if it doesn't make sense: we default
984 // to 1 in those cases.
985 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000986 return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000987
988 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000989 return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000990
Chris Lattnere3f61e12009-01-24 21:09:06 +0000991 return GetAlignOfType(E->getType());
992}
993
994
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000995/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
996/// expression's type.
997bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
998 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000999 // Return the result in the right width.
1000 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
1001 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
1002
Chris Lattnere3f61e12009-01-24 21:09:06 +00001003 // Handle alignof separately.
1004 if (!E->isSizeOf()) {
1005 if (E->isArgumentType())
1006 Result = GetAlignOfType(E->getArgumentType());
1007 else
1008 Result = GetAlignOfExpr(E->getArgumentExpr());
1009 return true;
1010 }
1011
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001012 QualType SrcTy = E->getTypeOfArgument();
1013
Chris Lattner265a0892008-07-11 21:24:13 +00001014 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +00001015 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +00001016 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +00001017 return true;
1018 }
Chris Lattner265a0892008-07-11 21:24:13 +00001019
1020 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere3f61e12009-01-24 21:09:06 +00001021 if (!SrcTy->isConstantSizeType())
Chris Lattner265a0892008-07-11 21:24:13 +00001022 return false;
Fariborz Jahanian2a032ec2009-01-16 01:42:12 +00001023
Chris Lattner265a0892008-07-11 21:24:13 +00001024 // GCC extension: sizeof(function) = 1.
1025 if (SrcTy->isFunctionType()) {
Chris Lattnere3f61e12009-01-24 21:09:06 +00001026 Result = 1;
Chris Lattner265a0892008-07-11 21:24:13 +00001027 return true;
1028 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +00001029
1030 if (SrcTy->isObjCInterfaceType()) {
1031 // Slightly unusual case: the size of an ObjC interface type is the
1032 // size of the class. This code intentionally falls through to the normal
1033 // case.
1034 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
1035 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
1036 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
1037 }
1038
Chris Lattnere3f61e12009-01-24 21:09:06 +00001039 // Get information about the size.
Chris Lattner422373c2008-07-11 22:52:41 +00001040 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnere3f61e12009-01-24 21:09:06 +00001041 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +00001042 return true;
1043}
1044
Chris Lattnera42f09a2008-07-11 19:10:17 +00001045bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +00001046 // Special case unary operators that do not need their subexpression
1047 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +00001048 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +00001049 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +00001050 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +00001051 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
1052 return true;
1053 }
Eli Friedman14cc7542008-11-13 06:09:17 +00001054
1055 if (E->getOpcode() == UnaryOperator::LNot) {
1056 // LNot's operand isn't necessarily an integer, so we handle it specially.
1057 bool bres;
1058 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1059 return false;
1060 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
1061 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
1062 Result = !bres;
1063 return true;
1064 }
1065
Chris Lattner422373c2008-07-11 22:52:41 +00001066 // Get the operand value into 'Result'.
1067 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +00001068 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001069
Chris Lattner400d7402008-07-11 22:15:16 +00001070 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +00001071 default:
Chris Lattner400d7402008-07-11 22:15:16 +00001072 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1073 // See C99 6.6p3.
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001074 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner400d7402008-07-11 22:15:16 +00001075 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +00001076 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1077 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +00001078 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +00001079 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +00001080 break;
1081 case UnaryOperator::Minus:
1082 Result = -Result;
1083 break;
1084 case UnaryOperator::Not:
1085 Result = ~Result;
1086 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001087 }
1088
1089 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +00001090 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001091}
1092
Chris Lattnerff579ff2008-07-12 01:15:53 +00001093/// HandleCast - This is used to evaluate implicit or explicit casts where the
1094/// result type is integer.
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001095bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlssonfa76d822008-11-30 18:14:57 +00001096 Expr *SubExpr = E->getSubExpr();
1097 QualType DestType = E->getType();
1098
Chris Lattner2c99c712008-07-11 19:24:49 +00001099 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +00001100
Eli Friedman7888b932008-11-12 09:44:48 +00001101 if (DestType->isBooleanType()) {
1102 bool BoolResult;
1103 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1104 return false;
1105 Result.zextOrTrunc(DestWidth);
1106 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1107 Result = BoolResult;
1108 return true;
1109 }
1110
Anders Carlssond1aa5812008-07-08 14:35:21 +00001111 // Handle simple integer->integer casts.
Eli Friedman14cc7542008-11-13 06:09:17 +00001112 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +00001113 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001114 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001115
1116 Result = HandleIntToIntCast(DestType, SubExpr->getType(), Result, Info.Ctx);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001117 return true;
1118 }
1119
1120 // FIXME: Clean this up!
1121 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +00001122 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +00001123 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001124 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001125
Anders Carlssond1aa5812008-07-08 14:35:21 +00001126 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +00001127 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001128
Anders Carlsson8ab15c82008-07-08 16:49:00 +00001129 Result.extOrTrunc(DestWidth);
1130 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +00001131 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1132 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +00001133 }
Eli Friedman7888b932008-11-12 09:44:48 +00001134
Chris Lattnerff579ff2008-07-12 01:15:53 +00001135 if (!SubExpr->getType()->isRealFloatingType())
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001136 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001137
Eli Friedman2f445492008-08-22 00:06:13 +00001138 APFloat F(0.0);
1139 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001140 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001141
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001142 Result = HandleFloatToIntCast(DestType, SubExpr->getType(), F, Info.Ctx);
Chris Lattnera42f09a2008-07-11 19:10:17 +00001143 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001144}
Anders Carlsson02a34c32008-07-08 14:30:00 +00001145
Chris Lattnera823ccf2008-07-11 18:11:29 +00001146//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +00001147// Float Evaluation
1148//===----------------------------------------------------------------------===//
1149
1150namespace {
1151class VISIBILITY_HIDDEN FloatExprEvaluator
1152 : public StmtVisitor<FloatExprEvaluator, bool> {
1153 EvalInfo &Info;
1154 APFloat &Result;
1155public:
1156 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1157 : Info(info), Result(result) {}
1158
1159 bool VisitStmt(Stmt *S) {
1160 return false;
1161 }
1162
1163 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +00001164 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001165
Daniel Dunbar804ead02008-10-16 03:51:50 +00001166 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001167 bool VisitBinaryOperator(const BinaryOperator *E);
1168 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +00001169 bool VisitCastExpr(CastExpr *E);
1170 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001171};
1172} // end anonymous namespace
1173
1174static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1175 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1176}
1177
Chris Lattner87293782008-10-06 05:28:25 +00001178bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +00001179 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner27cde262008-10-06 05:53:16 +00001180 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +00001181 case Builtin::BI__builtin_huge_val:
1182 case Builtin::BI__builtin_huge_valf:
1183 case Builtin::BI__builtin_huge_vall:
1184 case Builtin::BI__builtin_inf:
1185 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001186 case Builtin::BI__builtin_infl: {
1187 const llvm::fltSemantics &Sem =
1188 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +00001189 Result = llvm::APFloat::getInf(Sem);
1190 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001191 }
Chris Lattner667e1ee2008-10-06 06:31:58 +00001192
1193 case Builtin::BI__builtin_nan:
1194 case Builtin::BI__builtin_nanf:
1195 case Builtin::BI__builtin_nanl:
1196 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1197 // can't constant fold it.
1198 if (const StringLiteral *S =
1199 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1200 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001201 const llvm::fltSemantics &Sem =
1202 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +00001203 Result = llvm::APFloat::getNaN(Sem);
1204 return true;
1205 }
1206 }
1207 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +00001208
1209 case Builtin::BI__builtin_fabs:
1210 case Builtin::BI__builtin_fabsf:
1211 case Builtin::BI__builtin_fabsl:
1212 if (!EvaluateFloat(E->getArg(0), Result, Info))
1213 return false;
1214
1215 if (Result.isNegative())
1216 Result.changeSign();
1217 return true;
1218
1219 case Builtin::BI__builtin_copysign:
1220 case Builtin::BI__builtin_copysignf:
1221 case Builtin::BI__builtin_copysignl: {
1222 APFloat RHS(0.);
1223 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1224 !EvaluateFloat(E->getArg(1), RHS, Info))
1225 return false;
1226 Result.copySign(RHS);
1227 return true;
1228 }
Chris Lattner87293782008-10-06 05:28:25 +00001229 }
1230}
1231
Daniel Dunbar804ead02008-10-16 03:51:50 +00001232bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes1cea4f42008-11-19 17:44:31 +00001233 if (E->getOpcode() == UnaryOperator::Deref)
1234 return false;
1235
Daniel Dunbar804ead02008-10-16 03:51:50 +00001236 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1237 return false;
1238
1239 switch (E->getOpcode()) {
1240 default: return false;
1241 case UnaryOperator::Plus:
1242 return true;
1243 case UnaryOperator::Minus:
1244 Result.changeSign();
1245 return true;
1246 }
1247}
Chris Lattner87293782008-10-06 05:28:25 +00001248
Eli Friedman2f445492008-08-22 00:06:13 +00001249bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1250 // FIXME: Diagnostics? I really don't understand how the warnings
1251 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +00001252 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +00001253 if (!EvaluateFloat(E->getLHS(), Result, Info))
1254 return false;
1255 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1256 return false;
1257
1258 switch (E->getOpcode()) {
1259 default: return false;
1260 case BinaryOperator::Mul:
1261 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1262 return true;
1263 case BinaryOperator::Add:
1264 Result.add(RHS, APFloat::rmNearestTiesToEven);
1265 return true;
1266 case BinaryOperator::Sub:
1267 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1268 return true;
1269 case BinaryOperator::Div:
1270 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1271 return true;
1272 case BinaryOperator::Rem:
1273 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1274 return true;
1275 }
1276}
1277
1278bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1279 Result = E->getValue();
1280 return true;
1281}
1282
Eli Friedman7888b932008-11-12 09:44:48 +00001283bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1284 Expr* SubExpr = E->getSubExpr();
Nate Begemand6d2f772009-01-18 03:20:47 +00001285
Eli Friedman7888b932008-11-12 09:44:48 +00001286 if (SubExpr->getType()->isIntegralType()) {
1287 APSInt IntResult;
1288 if (!EvaluateInteger(E, IntResult, Info))
1289 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001290 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1291 IntResult, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001292 return true;
1293 }
1294 if (SubExpr->getType()->isRealFloatingType()) {
1295 if (!Visit(SubExpr))
1296 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001297 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1298 Result, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001299 return true;
1300 }
1301
1302 return false;
1303}
1304
1305bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1306 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1307 return true;
1308}
1309
Eli Friedman2f445492008-08-22 00:06:13 +00001310//===----------------------------------------------------------------------===//
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001311// Complex Evaluation (for float and integer)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001312//===----------------------------------------------------------------------===//
1313
1314namespace {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001315class VISIBILITY_HIDDEN ComplexExprEvaluator
1316 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001317 EvalInfo &Info;
1318
1319public:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001320 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001321
1322 //===--------------------------------------------------------------------===//
1323 // Visitor Methods
1324 //===--------------------------------------------------------------------===//
1325
1326 APValue VisitStmt(Stmt *S) {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001327 return APValue();
1328 }
1329
1330 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1331
1332 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001333 Expr* SubExpr = E->getSubExpr();
1334
1335 if (SubExpr->getType()->isRealFloatingType()) {
1336 APFloat Result(0.0);
1337
1338 if (!EvaluateFloat(SubExpr, Result, Info))
1339 return APValue();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001340
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001341 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001342 Result);
1343 } else {
1344 assert(SubExpr->getType()->isIntegerType() &&
1345 "Unexpected imaginary literal.");
1346
1347 llvm::APSInt Result;
1348 if (!EvaluateInteger(SubExpr, Result, Info))
1349 return APValue();
1350
1351 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1352 Zero = 0;
1353 return APValue(Zero, Result);
1354 }
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001355 }
1356
Anders Carlssonad2794c2008-11-16 21:51:21 +00001357 APValue VisitCastExpr(CastExpr *E) {
1358 Expr* SubExpr = E->getSubExpr();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001359 QualType EltType = E->getType()->getAsComplexType()->getElementType();
1360 QualType SubType = SubExpr->getType();
Anders Carlssonad2794c2008-11-16 21:51:21 +00001361
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001362 if (SubType->isRealFloatingType()) {
Anders Carlssonad2794c2008-11-16 21:51:21 +00001363 APFloat Result(0.0);
1364
1365 if (!EvaluateFloat(SubExpr, Result, Info))
1366 return APValue();
1367
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001368 // Apply float conversion if necessary.
1369 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbarf8abb942009-01-24 19:08:01 +00001370 return APValue(Result,
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001371 APFloat(Result.getSemantics(), APFloat::fcZero, false));
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001372 } else if (SubType->isIntegerType()) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001373 APSInt Result;
1374
1375 if (!EvaluateInteger(SubExpr, Result, Info))
1376 return APValue();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001377
1378 // Apply integer conversion if necessary.
1379 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001380 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1381 Zero = 0;
1382 return APValue(Result, Zero);
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001383 } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1384 APValue Src;
1385
1386 if (!EvaluateComplex(SubExpr, Src, Info))
1387 return APValue();
1388
1389 QualType SrcType = CT->getElementType();
1390
1391 if (Src.isComplexFloat()) {
1392 if (EltType->isRealFloatingType()) {
1393 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1394 Src.getComplexFloatReal(),
1395 Info.Ctx),
1396 HandleFloatToFloatCast(EltType, SrcType,
1397 Src.getComplexFloatImag(),
1398 Info.Ctx));
1399 } else {
1400 return APValue(HandleFloatToIntCast(EltType, SrcType,
1401 Src.getComplexFloatReal(),
1402 Info.Ctx),
1403 HandleFloatToIntCast(EltType, SrcType,
1404 Src.getComplexFloatImag(),
1405 Info.Ctx));
1406 }
1407 } else {
1408 assert(Src.isComplexInt() && "Invalid evaluate result.");
1409 if (EltType->isRealFloatingType()) {
1410 return APValue(HandleIntToFloatCast(EltType, SrcType,
1411 Src.getComplexIntReal(),
1412 Info.Ctx),
1413 HandleIntToFloatCast(EltType, SrcType,
1414 Src.getComplexIntImag(),
1415 Info.Ctx));
1416 } else {
1417 return APValue(HandleIntToIntCast(EltType, SrcType,
1418 Src.getComplexIntReal(),
1419 Info.Ctx),
1420 HandleIntToIntCast(EltType, SrcType,
1421 Src.getComplexIntImag(),
1422 Info.Ctx));
1423 }
1424 }
Anders Carlssonad2794c2008-11-16 21:51:21 +00001425 }
1426
1427 // FIXME: Handle more casts.
1428 return APValue();
1429 }
1430
1431 APValue VisitBinaryOperator(const BinaryOperator *E);
1432
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001433};
1434} // end anonymous namespace
1435
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001436static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001437{
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001438 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1439 assert((!Result.isComplexFloat() ||
1440 (&Result.getComplexFloatReal().getSemantics() ==
1441 &Result.getComplexFloatImag().getSemantics())) &&
1442 "Invalid complex evaluation.");
1443 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001444}
1445
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001446APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
Anders Carlssonad2794c2008-11-16 21:51:21 +00001447{
1448 APValue Result, RHS;
1449
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001450 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001451 return APValue();
1452
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001453 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001454 return APValue();
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001455
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001456 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1457 "Invalid operands to binary operator.");
Anders Carlssonad2794c2008-11-16 21:51:21 +00001458 switch (E->getOpcode()) {
1459 default: return APValue();
1460 case BinaryOperator::Add:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001461 if (Result.isComplexFloat()) {
1462 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1463 APFloat::rmNearestTiesToEven);
1464 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1465 APFloat::rmNearestTiesToEven);
1466 } else {
1467 Result.getComplexIntReal() += RHS.getComplexIntReal();
1468 Result.getComplexIntImag() += RHS.getComplexIntImag();
1469 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001470 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001471 case BinaryOperator::Sub:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001472 if (Result.isComplexFloat()) {
1473 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1474 APFloat::rmNearestTiesToEven);
1475 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1476 APFloat::rmNearestTiesToEven);
1477 } else {
1478 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1479 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1480 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001481 break;
1482 case BinaryOperator::Mul:
1483 if (Result.isComplexFloat()) {
1484 APValue LHS = Result;
1485 APFloat &LHS_r = LHS.getComplexFloatReal();
1486 APFloat &LHS_i = LHS.getComplexFloatImag();
1487 APFloat &RHS_r = RHS.getComplexFloatReal();
1488 APFloat &RHS_i = RHS.getComplexFloatImag();
1489
1490 APFloat Tmp = LHS_r;
1491 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1492 Result.getComplexFloatReal() = Tmp;
1493 Tmp = LHS_i;
1494 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1495 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1496
1497 Tmp = LHS_r;
1498 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1499 Result.getComplexFloatImag() = Tmp;
1500 Tmp = LHS_i;
1501 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1502 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1503 } else {
1504 APValue LHS = Result;
1505 Result.getComplexIntReal() =
1506 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1507 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1508 Result.getComplexIntImag() =
1509 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1510 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1511 }
1512 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001513 }
1514
1515 return Result;
1516}
1517
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001518//===----------------------------------------------------------------------===//
Chris Lattneref069662008-11-16 21:24:15 +00001519// Top level Expr::Evaluate method.
Chris Lattnera823ccf2008-07-11 18:11:29 +00001520//===----------------------------------------------------------------------===//
1521
Chris Lattneref069662008-11-16 21:24:15 +00001522/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner87293782008-10-06 05:28:25 +00001523/// any crazy technique (that has nothing to do with language standards) that
1524/// we want to. If this function returns true, it returns the folded constant
1525/// in Result.
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001526bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1527 EvalInfo Info(Ctx, Result);
Anders Carlssondd8d41f2008-11-30 16:38:33 +00001528
Nate Begemand6d2f772009-01-18 03:20:47 +00001529 if (getType()->isVectorType()) {
1530 if (!EvaluateVector(this, Result.Val, Info))
1531 return false;
1532 } else if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +00001533 llvm::APSInt sInt(32);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001534 if (!EvaluateInteger(this, sInt, Info))
1535 return false;
1536
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001537 Result.Val = APValue(sInt);
Mike Stump5b601ff2009-02-18 21:44:49 +00001538 } else if (getType()->isPointerType()
1539 || getType()->isBlockPointerType()) {
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001540 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001541 return false;
Eli Friedman2f445492008-08-22 00:06:13 +00001542 } else if (getType()->isRealFloatingType()) {
1543 llvm::APFloat f(0.0);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001544 if (!EvaluateFloat(this, f, Info))
1545 return false;
1546
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001547 Result.Val = APValue(f);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001548 } else if (getType()->isAnyComplexType()) {
1549 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001550 return false;
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001551 } else
Anders Carlssoncb6a2e82008-11-22 22:56:32 +00001552 return false;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001553
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001554 return true;
1555}
1556
Chris Lattneref069662008-11-16 21:24:15 +00001557/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001558/// folded, but discard the result.
1559bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson197f6f72008-12-01 06:44:05 +00001560 EvalResult Result;
1561 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001562}
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001563
1564APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson8c3de802008-12-19 20:58:05 +00001565 EvalResult EvalResult;
1566 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarddebeca2009-01-15 18:32:35 +00001567 Result = Result;
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001568 assert(Result && "Could not evaluate expression");
Anders Carlsson8c3de802008-12-19 20:58:05 +00001569 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001570
Anders Carlsson8c3de802008-12-19 20:58:05 +00001571 return EvalResult.Val.getInt();
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001572}