blob: ee698d6c93fb07df747482012559b4fda12dff07 [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);
Eli Friedman7888b932008-11-12 09:44:48 +0000263 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000264};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000265} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000266
Chris Lattner422373c2008-07-11 22:52:41 +0000267static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Mike Stump5b601ff2009-02-18 21:44:49 +0000268 if (!E->getType()->isPointerType()
269 && !E->getType()->isBlockPointerType())
Chris Lattnera823ccf2008-07-11 18:11:29 +0000270 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000271 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000272 return Result.isLValue();
273}
274
275APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
276 if (E->getOpcode() != BinaryOperator::Add &&
277 E->getOpcode() != BinaryOperator::Sub)
278 return APValue();
279
280 const Expr *PExp = E->getLHS();
281 const Expr *IExp = E->getRHS();
282 if (IExp->getType()->isPointerType())
283 std::swap(PExp, IExp);
284
285 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000286 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000287 return APValue();
288
289 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000290 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000291 return APValue();
292
Eli Friedman7888b932008-11-12 09:44:48 +0000293 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
294 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
295
Chris Lattnera823ccf2008-07-11 18:11:29 +0000296 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000297
Chris Lattnera823ccf2008-07-11 18:11:29 +0000298 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000299 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000300 else
Eli Friedman7888b932008-11-12 09:44:48 +0000301 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
302
Chris Lattnera823ccf2008-07-11 18:11:29 +0000303 return APValue(ResultLValue.getLValueBase(), Offset);
304}
Eli Friedman7888b932008-11-12 09:44:48 +0000305
306APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
307 if (E->getOpcode() == UnaryOperator::Extension) {
308 // FIXME: Deal with warnings?
309 return Visit(E->getSubExpr());
310 }
311
312 if (E->getOpcode() == UnaryOperator::AddrOf) {
313 APValue result;
314 if (EvaluateLValue(E->getSubExpr(), result, Info))
315 return result;
316 }
317
318 return APValue();
319}
Anders Carlsson4ab88da2008-12-05 05:24:13 +0000320
Chris Lattnera823ccf2008-07-11 18:11:29 +0000321
Chris Lattnera42f09a2008-07-11 19:10:17 +0000322APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000323 const Expr* SubExpr = E->getSubExpr();
324
325 // Check for pointer->pointer cast
326 if (SubExpr->getType()->isPointerType()) {
327 APValue Result;
Chris Lattner422373c2008-07-11 22:52:41 +0000328 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000329 return Result;
330 return APValue();
331 }
332
Eli Friedman3e64dd72008-07-27 05:46:18 +0000333 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000334 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000335 if (EvaluateInteger(SubExpr, Result, Info)) {
336 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000337 return APValue(0, Result.getZExtValue());
338 }
339 }
Eli Friedman7888b932008-11-12 09:44:48 +0000340
341 if (SubExpr->getType()->isFunctionType() ||
342 SubExpr->getType()->isArrayType()) {
343 APValue Result;
344 if (EvaluateLValue(SubExpr, Result, Info))
345 return Result;
346 return APValue();
347 }
348
349 //assert(0 && "Unhandled cast");
Chris Lattnera823ccf2008-07-11 18:11:29 +0000350 return APValue();
351}
352
Eli Friedman67f4ac52009-01-25 01:54:01 +0000353APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000354 if (E->isBuiltinCall(Info.Ctx) ==
355 Builtin::BI__builtin___CFStringMakeConstantString)
Eli Friedman67f4ac52009-01-25 01:54:01 +0000356 return APValue(E, 0);
357 return APValue();
358}
359
Eli Friedman7888b932008-11-12 09:44:48 +0000360APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
361 bool BoolResult;
362 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
363 return APValue();
364
365 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
366
367 APValue Result;
368 if (EvaluatePointer(EvalExpr, Result, Info))
369 return Result;
370 return APValue();
371}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000372
373//===----------------------------------------------------------------------===//
Nate Begemand6d2f772009-01-18 03:20:47 +0000374// Vector Evaluation
375//===----------------------------------------------------------------------===//
376
377namespace {
378 class VISIBILITY_HIDDEN VectorExprEvaluator
379 : public StmtVisitor<VectorExprEvaluator, APValue> {
380 EvalInfo &Info;
381 public:
382
383 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
384
385 APValue VisitStmt(Stmt *S) {
386 return APValue();
387 }
388
389 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
390 APValue VisitCastExpr(const CastExpr* E);
391 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
392 APValue VisitInitListExpr(const InitListExpr *E);
393 };
394} // end anonymous namespace
395
396static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
397 if (!E->getType()->isVectorType())
398 return false;
399 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
400 return !Result.isUninit();
401}
402
403APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
404 const Expr* SE = E->getSubExpr();
405
406 // Check for vector->vector bitcast.
407 if (SE->getType()->isVectorType())
408 return this->Visit(const_cast<Expr*>(SE));
409
410 return APValue();
411}
412
413APValue
414VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
415 return this->Visit(const_cast<Expr*>(E->getInitializer()));
416}
417
418APValue
419VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
420 const VectorType *VT = E->getType()->getAsVectorType();
421 unsigned NumInits = E->getNumInits();
422
423 if (!VT || VT->getNumElements() != NumInits)
424 return APValue();
425
426 QualType EltTy = VT->getElementType();
427 llvm::SmallVector<APValue, 4> Elements;
428
429 for (unsigned i = 0; i < NumInits; i++) {
430 if (EltTy->isIntegerType()) {
431 llvm::APSInt sInt(32);
432 if (!EvaluateInteger(E->getInit(i), sInt, Info))
433 return APValue();
434 Elements.push_back(APValue(sInt));
435 } else {
436 llvm::APFloat f(0.0);
437 if (!EvaluateFloat(E->getInit(i), f, Info))
438 return APValue();
439 Elements.push_back(APValue(f));
440 }
441 }
442 return APValue(&Elements[0], Elements.size());
443}
444
445//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000446// Integer Evaluation
447//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000448
449namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000450class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000451 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000452 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000453 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000454public:
Chris Lattner422373c2008-07-11 22:52:41 +0000455 IntExprEvaluator(EvalInfo &info, APSInt &result)
456 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000457
Chris Lattner2c99c712008-07-11 19:24:49 +0000458 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner82437da2008-07-12 00:14:42 +0000459 return (unsigned)Info.Ctx.getIntWidth(T);
460 }
461
Anders Carlssonfa76d822008-11-30 18:14:57 +0000462 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000463 Info.EvalResult.DiagLoc = L;
464 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000465 Info.EvalResult.DiagExpr = E;
Chris Lattner82437da2008-07-12 00:14:42 +0000466 return true; // still a constant.
467 }
468
Anders Carlssonfa76d822008-11-30 18:14:57 +0000469 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner82437da2008-07-12 00:14:42 +0000470 // If this is in an unevaluated portion of the subexpression, ignore the
471 // error.
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000472 if (Info.ShortCircuit) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000473 // If error is ignored because the value isn't evaluated, get the real
474 // type at least to prevent errors downstream.
Anders Carlssonfa76d822008-11-30 18:14:57 +0000475 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
476 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattner82437da2008-07-12 00:14:42 +0000477 return true;
Chris Lattner438f3b12008-11-12 07:43:42 +0000478 }
Chris Lattner82437da2008-07-12 00:14:42 +0000479
Chris Lattner438f3b12008-11-12 07:43:42 +0000480 // Take the first error.
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000481 if (Info.EvalResult.Diag == 0) {
482 Info.EvalResult.DiagLoc = L;
483 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000484 Info.EvalResult.DiagExpr = E;
Chris Lattner438f3b12008-11-12 07:43:42 +0000485 }
Chris Lattner82437da2008-07-12 00:14:42 +0000486 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000487 }
488
Anders Carlssoncad17b52008-07-08 05:13:58 +0000489 //===--------------------------------------------------------------------===//
490 // Visitor Methods
491 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000492
493 bool VisitStmt(Stmt *) {
494 assert(0 && "This should be called on integers, stmts are not integers");
495 return false;
496 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000497
Chris Lattner438f3b12008-11-12 07:43:42 +0000498 bool VisitExpr(Expr *E) {
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000499 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssoncad17b52008-07-08 05:13:58 +0000500 }
501
Chris Lattnera42f09a2008-07-11 19:10:17 +0000502 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000503
Chris Lattner15e59112008-07-12 00:38:25 +0000504 bool VisitIntegerLiteral(const IntegerLiteral *E) {
505 Result = E->getValue();
506 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
507 return true;
508 }
509 bool VisitCharacterLiteral(const CharacterLiteral *E) {
510 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
511 Result = E->getValue();
512 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
513 return true;
514 }
515 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
516 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000517 // Per gcc docs "this built-in function ignores top level
518 // qualifiers". We need to use the canonical version to properly
519 // be able to strip CRV qualifiers from the type.
520 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
521 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
522 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
523 T1.getUnqualifiedType());
Chris Lattner15e59112008-07-12 00:38:25 +0000524 return true;
525 }
526 bool VisitDeclRefExpr(const DeclRefExpr *E);
527 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000528 bool VisitBinaryOperator(const BinaryOperator *E);
529 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000530 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000531
Daniel Dunbaraffa0e32009-01-29 06:16:07 +0000532 bool VisitCastExpr(CastExpr* E);
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000533 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
534
Anders Carlsson027f2882008-11-16 19:01:22 +0000535 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000536 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson027f2882008-11-16 19:01:22 +0000537 Result = E->getValue();
538 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
539 return true;
540 }
541
Anders Carlsson774f9c72008-12-21 22:39:40 +0000542 bool VisitGNUNullExpr(const GNUNullExpr *E) {
543 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
544 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
545 return true;
546 }
547
Anders Carlsson027f2882008-11-16 19:01:22 +0000548 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
549 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
550 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
551 return true;
552 }
553
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000554 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
555 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbar8360a9c2009-02-17 23:20:26 +0000556 Result = E->EvaluateTrait();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000557 return true;
558 }
559
Chris Lattner265a0892008-07-11 21:24:13 +0000560private:
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000561 unsigned GetAlignOfExpr(const Expr *E);
562 unsigned GetAlignOfType(QualType T);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000563};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000564} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000565
Chris Lattner422373c2008-07-11 22:52:41 +0000566static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
567 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000568}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000569
Chris Lattner15e59112008-07-12 00:38:25 +0000570bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
571 // Enums are integer constant exprs.
572 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
573 Result = D->getInitVal();
Eli Friedman8b10a232008-12-08 02:21:03 +0000574 // FIXME: This is an ugly hack around the fact that enums don't set their
575 // signedness consistently; see PR3173
576 Result.setIsUnsigned(!E->getType()->isSignedIntegerType());
Chris Lattner15e59112008-07-12 00:38:25 +0000577 return true;
578 }
Sebastian Redl410dd872009-02-08 15:51:17 +0000579
580 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
581 if (Info.Ctx.getLangOptions().CPlusPlus &&
582 E->getType().getCVRQualifiers() == QualType::Const) {
583 if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
584 if (const Expr *Init = D->getInit())
585 return Visit(const_cast<Expr*>(Init));
586 }
587 }
588
Chris Lattner15e59112008-07-12 00:38:25 +0000589 // Otherwise, random variable references are not constants.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000590 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000591}
592
Chris Lattner1eee9402008-10-06 06:40:35 +0000593/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
594/// as GCC.
595static int EvaluateBuiltinClassifyType(const CallExpr *E) {
596 // The following enum mimics the values returned by GCC.
597 enum gcc_type_class {
598 no_type_class = -1,
599 void_type_class, integer_type_class, char_type_class,
600 enumeral_type_class, boolean_type_class,
601 pointer_type_class, reference_type_class, offset_type_class,
602 real_type_class, complex_type_class,
603 function_type_class, method_type_class,
604 record_type_class, union_type_class,
605 array_type_class, string_type_class,
606 lang_type_class
607 };
608
609 // If no argument was supplied, default to "no_type_class". This isn't
610 // ideal, however it is what gcc does.
611 if (E->getNumArgs() == 0)
612 return no_type_class;
613
614 QualType ArgTy = E->getArg(0)->getType();
615 if (ArgTy->isVoidType())
616 return void_type_class;
617 else if (ArgTy->isEnumeralType())
618 return enumeral_type_class;
619 else if (ArgTy->isBooleanType())
620 return boolean_type_class;
621 else if (ArgTy->isCharType())
622 return string_type_class; // gcc doesn't appear to use char_type_class
623 else if (ArgTy->isIntegerType())
624 return integer_type_class;
625 else if (ArgTy->isPointerType())
626 return pointer_type_class;
627 else if (ArgTy->isReferenceType())
628 return reference_type_class;
629 else if (ArgTy->isRealType())
630 return real_type_class;
631 else if (ArgTy->isComplexType())
632 return complex_type_class;
633 else if (ArgTy->isFunctionType())
634 return function_type_class;
635 else if (ArgTy->isStructureType())
636 return record_type_class;
637 else if (ArgTy->isUnionType())
638 return union_type_class;
639 else if (ArgTy->isArrayType())
640 return array_type_class;
641 else if (ArgTy->isUnionType())
642 return union_type_class;
643 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
644 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
645 return -1;
646}
647
Chris Lattner15e59112008-07-12 00:38:25 +0000648bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
649 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000650
Douglas Gregorb5af7382009-02-14 18:57:46 +0000651 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner87293782008-10-06 05:28:25 +0000652 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000653 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner87293782008-10-06 05:28:25 +0000654 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000655 Result.setIsSigned(true);
656 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-10-06 05:28:25 +0000657 return true;
658
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000659 case Builtin::BI__builtin_constant_p:
Chris Lattner87293782008-10-06 05:28:25 +0000660 // __builtin_constant_p always has one operand: it returns true if that
661 // operand can be folded, false otherwise.
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000662 Result = E->getArg(0)->isEvaluatable(Info.Ctx);
Chris Lattner87293782008-10-06 05:28:25 +0000663 return true;
664 }
Chris Lattner15e59112008-07-12 00:38:25 +0000665}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000666
Chris Lattnera42f09a2008-07-11 19:10:17 +0000667bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000668 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000669 if (!Visit(E->getRHS()))
670 return false;
Anders Carlsson197f6f72008-12-01 06:44:05 +0000671
672 if (!Info.ShortCircuit) {
673 // If we can't evaluate the LHS, it must be because it has
674 // side effects.
675 if (!E->getLHS()->isEvaluatable(Info.Ctx))
676 Info.EvalResult.HasSideEffects = true;
677
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000678 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson197f6f72008-12-01 06:44:05 +0000679 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000680
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000681 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000682 }
683
684 if (E->isLogicalOp()) {
685 // These need to be handled specially because the operands aren't
686 // necessarily integral
Anders Carlsson501da1f2008-11-30 16:51:17 +0000687 bool lhsResult, rhsResult;
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000688
Anders Carlsson501da1f2008-11-30 16:51:17 +0000689 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000690 // We were able to evaluate the LHS, see if we can get away with not
691 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlsson501da1f2008-11-30 16:51:17 +0000692 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
693 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000694 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
695 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlsson501da1f2008-11-30 16:51:17 +0000696 Result = lhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000697
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000698 Info.ShortCircuit++;
Anders Carlsson501da1f2008-11-30 16:51:17 +0000699 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000700 Info.ShortCircuit--;
701
Anders Carlsson501da1f2008-11-30 16:51:17 +0000702 if (rhsEvaluated)
703 return true;
704
705 // FIXME: Return an extension warning saying that the RHS could not be
706 // evaluated.
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000707 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000708 }
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000709
Anders Carlsson501da1f2008-11-30 16:51:17 +0000710 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000711 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
712 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
713 if (E->getOpcode() == BinaryOperator::LOr)
Anders Carlsson501da1f2008-11-30 16:51:17 +0000714 Result = lhsResult || rhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000715 else
Anders Carlsson501da1f2008-11-30 16:51:17 +0000716 Result = lhsResult && rhsResult;
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000717 return true;
718 }
719 } else {
Anders Carlsson501da1f2008-11-30 16:51:17 +0000720 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000721 // We can't evaluate the LHS; however, sometimes the result
722 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlsson501da1f2008-11-30 16:51:17 +0000723 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
724 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000725 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
726 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlsson501da1f2008-11-30 16:51:17 +0000727 Result = rhsResult;
728
729 // Since we werent able to evaluate the left hand side, it
730 // must have had side effects.
731 Info.EvalResult.HasSideEffects = true;
732
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000733 return true;
734 }
735 }
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000736 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000737
Eli Friedman14cc7542008-11-13 06:09:17 +0000738 return false;
739 }
740
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000741 QualType LHSTy = E->getLHS()->getType();
742 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000743
744 if (LHSTy->isAnyComplexType()) {
745 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
746 APValue LHS, RHS;
747
748 if (!EvaluateComplex(E->getLHS(), LHS, Info))
749 return false;
750
751 if (!EvaluateComplex(E->getRHS(), RHS, Info))
752 return false;
753
754 if (LHS.isComplexFloat()) {
755 APFloat::cmpResult CR_r =
756 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
757 APFloat::cmpResult CR_i =
758 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
759
760 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
761 if (E->getOpcode() == BinaryOperator::EQ)
762 Result = (CR_r == APFloat::cmpEqual &&
763 CR_i == APFloat::cmpEqual);
764 else if (E->getOpcode() == BinaryOperator::NE)
765 Result = ((CR_r == APFloat::cmpGreaterThan ||
766 CR_r == APFloat::cmpLessThan) &&
767 (CR_i == APFloat::cmpGreaterThan ||
768 CR_i == APFloat::cmpLessThan));
769 else
770 assert(0 && "Invalid complex compartison.");
771 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
772 return true;
773 } else {
774 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
775 if (E->getOpcode() == BinaryOperator::EQ)
776 Result = (LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
777 LHS.getComplexIntImag() == RHS.getComplexIntImag());
778 else if (E->getOpcode() == BinaryOperator::NE)
779 Result = (LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
780 LHS.getComplexIntImag() != RHS.getComplexIntImag());
781 else
782 assert(0 && "Invalid complex compartison.");
783 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
784 return true;
785 }
786 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000787
788 if (LHSTy->isRealFloatingType() &&
789 RHSTy->isRealFloatingType()) {
790 APFloat RHS(0.0), LHS(0.0);
791
792 if (!EvaluateFloat(E->getRHS(), RHS, Info))
793 return false;
794
795 if (!EvaluateFloat(E->getLHS(), LHS, Info))
796 return false;
797
798 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000799
800 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
801
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000802 switch (E->getOpcode()) {
803 default:
804 assert(0 && "Invalid binary operator!");
805 case BinaryOperator::LT:
806 Result = CR == APFloat::cmpLessThan;
807 break;
808 case BinaryOperator::GT:
809 Result = CR == APFloat::cmpGreaterThan;
810 break;
811 case BinaryOperator::LE:
812 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
813 break;
814 case BinaryOperator::GE:
815 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
816 break;
817 case BinaryOperator::EQ:
818 Result = CR == APFloat::cmpEqual;
819 break;
820 case BinaryOperator::NE:
821 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
822 break;
823 }
824
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000825 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
826 return true;
827 }
828
Anders Carlsson027f2882008-11-16 19:01:22 +0000829 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000830 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson027f2882008-11-16 19:01:22 +0000831 APValue LHSValue;
832 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
833 return false;
834
835 APValue RHSValue;
836 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
837 return false;
838
839 // FIXME: Is this correct? What if only one of the operands has a base?
840 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
841 return false;
842
843 const QualType Type = E->getLHS()->getType();
844 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
845
846 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
847 D /= Info.Ctx.getTypeSize(ElementType) / 8;
848
Anders Carlsson027f2882008-11-16 19:01:22 +0000849 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000850 Result = D;
Anders Carlsson027f2882008-11-16 19:01:22 +0000851 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
852
853 return true;
854 }
855 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000856 if (!LHSTy->isIntegralType() ||
857 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000858 // We can't continue from here for non-integral types, and they
859 // could potentially confuse the following operations.
860 // FIXME: Deal with EQ and friends.
861 return false;
862 }
863
Anders Carlssond1aa5812008-07-08 14:35:21 +0000864 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000865 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000866 if (!Visit(E->getLHS())) {
Chris Lattner82437da2008-07-12 00:14:42 +0000867 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000868 }
Eli Friedman3e64dd72008-07-27 05:46:18 +0000869
Eli Friedman3e64dd72008-07-27 05:46:18 +0000870
871 // FIXME Maybe we want to succeed even where we can't evaluate the
872 // right side of LAnd/LOr?
873 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000874 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000875 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000876
Anders Carlssond1aa5812008-07-08 14:35:21 +0000877 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000878 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000879 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner82437da2008-07-12 00:14:42 +0000880 case BinaryOperator::Mul: Result *= RHS; return true;
881 case BinaryOperator::Add: Result += RHS; return true;
882 case BinaryOperator::Sub: Result -= RHS; return true;
883 case BinaryOperator::And: Result &= RHS; return true;
884 case BinaryOperator::Xor: Result ^= RHS; return true;
885 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000886 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000887 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000888 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000889 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000890 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000891 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000892 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000893 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000894 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000895 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000896 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000897 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000898 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000899 break;
900 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000901 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000902 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000903
Chris Lattner045502c2008-07-11 19:29:32 +0000904 case BinaryOperator::LT:
905 Result = Result < RHS;
906 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
907 break;
908 case BinaryOperator::GT:
909 Result = Result > RHS;
910 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
911 break;
912 case BinaryOperator::LE:
913 Result = Result <= RHS;
914 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
915 break;
916 case BinaryOperator::GE:
917 Result = Result >= RHS;
918 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
919 break;
920 case BinaryOperator::EQ:
921 Result = Result == RHS;
922 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
923 break;
924 case BinaryOperator::NE:
925 Result = Result != RHS;
926 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
927 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000928 case BinaryOperator::LAnd:
929 Result = Result != 0 && RHS != 0;
930 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
931 break;
932 case BinaryOperator::LOr:
933 Result = Result != 0 || RHS != 0;
934 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
935 break;
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000936 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000937
938 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000939 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000940}
941
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000942bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes308de752008-11-16 22:06:39 +0000943 bool Cond;
944 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000945 return false;
946
Nuno Lopes308de752008-11-16 22:06:39 +0000947 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000948}
949
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000950unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
Chris Lattnere3f61e12009-01-24 21:09:06 +0000951 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
952
953 // __alignof__(void) = 1 as a gcc extension.
954 if (Ty->isVoidType())
955 return 1;
956
957 // GCC extension: alignof(function) = 4.
958 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the
959 // attribute(align) directive.
960 if (Ty->isFunctionType())
961 return 4;
962
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000963 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty))
964 return GetAlignOfType(QualType(EXTQT->getBaseType(), 0));
Chris Lattnere3f61e12009-01-24 21:09:06 +0000965
966 // alignof VLA/incomplete array.
967 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
968 return GetAlignOfType(VAT->getElementType());
969
970 // sizeof (objc class)?
971 if (isa<ObjCInterfaceType>(Ty))
972 return 1; // FIXME: This probably isn't right.
973
974 // Get information about the alignment.
975 unsigned CharSize = Info.Ctx.Target.getCharWidth();
976 return Info.Ctx.getTypeAlign(Ty) / CharSize;
977}
978
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000979unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
980 E = E->IgnoreParens();
981
982 // alignof decl is always accepted, even if it doesn't make sense: we default
983 // to 1 in those cases.
984 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000985 return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000986
987 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000988 return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000989
Chris Lattnere3f61e12009-01-24 21:09:06 +0000990 return GetAlignOfType(E->getType());
991}
992
993
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000994/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
995/// expression's type.
996bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
997 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000998 // Return the result in the right width.
999 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
1000 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
1001
Chris Lattnere3f61e12009-01-24 21:09:06 +00001002 // Handle alignof separately.
1003 if (!E->isSizeOf()) {
1004 if (E->isArgumentType())
1005 Result = GetAlignOfType(E->getArgumentType());
1006 else
1007 Result = GetAlignOfExpr(E->getArgumentExpr());
1008 return true;
1009 }
1010
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001011 QualType SrcTy = E->getTypeOfArgument();
1012
Chris Lattner265a0892008-07-11 21:24:13 +00001013 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +00001014 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +00001015 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +00001016 return true;
1017 }
Chris Lattner265a0892008-07-11 21:24:13 +00001018
1019 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere3f61e12009-01-24 21:09:06 +00001020 if (!SrcTy->isConstantSizeType())
Chris Lattner265a0892008-07-11 21:24:13 +00001021 return false;
Fariborz Jahanian2a032ec2009-01-16 01:42:12 +00001022
Chris Lattner265a0892008-07-11 21:24:13 +00001023 // GCC extension: sizeof(function) = 1.
1024 if (SrcTy->isFunctionType()) {
Chris Lattnere3f61e12009-01-24 21:09:06 +00001025 Result = 1;
Chris Lattner265a0892008-07-11 21:24:13 +00001026 return true;
1027 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +00001028
1029 if (SrcTy->isObjCInterfaceType()) {
1030 // Slightly unusual case: the size of an ObjC interface type is the
1031 // size of the class. This code intentionally falls through to the normal
1032 // case.
1033 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
1034 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
1035 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
1036 }
1037
Chris Lattnere3f61e12009-01-24 21:09:06 +00001038 // Get information about the size.
Chris Lattner422373c2008-07-11 22:52:41 +00001039 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnere3f61e12009-01-24 21:09:06 +00001040 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +00001041 return true;
1042}
1043
Chris Lattnera42f09a2008-07-11 19:10:17 +00001044bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +00001045 // Special case unary operators that do not need their subexpression
1046 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +00001047 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +00001048 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +00001049 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +00001050 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
1051 return true;
1052 }
Eli Friedman14cc7542008-11-13 06:09:17 +00001053
1054 if (E->getOpcode() == UnaryOperator::LNot) {
1055 // LNot's operand isn't necessarily an integer, so we handle it specially.
1056 bool bres;
1057 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1058 return false;
1059 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
1060 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
1061 Result = !bres;
1062 return true;
1063 }
1064
Chris Lattner422373c2008-07-11 22:52:41 +00001065 // Get the operand value into 'Result'.
1066 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +00001067 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001068
Chris Lattner400d7402008-07-11 22:15:16 +00001069 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +00001070 default:
Chris Lattner400d7402008-07-11 22:15:16 +00001071 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1072 // See C99 6.6p3.
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001073 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner400d7402008-07-11 22:15:16 +00001074 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +00001075 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1076 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +00001077 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +00001078 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +00001079 break;
1080 case UnaryOperator::Minus:
1081 Result = -Result;
1082 break;
1083 case UnaryOperator::Not:
1084 Result = ~Result;
1085 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001086 }
1087
1088 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +00001089 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001090}
1091
Chris Lattnerff579ff2008-07-12 01:15:53 +00001092/// HandleCast - This is used to evaluate implicit or explicit casts where the
1093/// result type is integer.
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001094bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlssonfa76d822008-11-30 18:14:57 +00001095 Expr *SubExpr = E->getSubExpr();
1096 QualType DestType = E->getType();
1097
Chris Lattner2c99c712008-07-11 19:24:49 +00001098 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +00001099
Eli Friedman7888b932008-11-12 09:44:48 +00001100 if (DestType->isBooleanType()) {
1101 bool BoolResult;
1102 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1103 return false;
1104 Result.zextOrTrunc(DestWidth);
1105 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1106 Result = BoolResult;
1107 return true;
1108 }
1109
Anders Carlssond1aa5812008-07-08 14:35:21 +00001110 // Handle simple integer->integer casts.
Eli Friedman14cc7542008-11-13 06:09:17 +00001111 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +00001112 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001113 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001114
1115 Result = HandleIntToIntCast(DestType, SubExpr->getType(), Result, Info.Ctx);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001116 return true;
1117 }
1118
1119 // FIXME: Clean this up!
1120 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +00001121 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +00001122 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001123 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001124
Anders Carlssond1aa5812008-07-08 14:35:21 +00001125 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +00001126 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001127
Anders Carlsson8ab15c82008-07-08 16:49:00 +00001128 Result.extOrTrunc(DestWidth);
1129 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +00001130 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1131 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +00001132 }
Eli Friedman7888b932008-11-12 09:44:48 +00001133
Chris Lattnerff579ff2008-07-12 01:15:53 +00001134 if (!SubExpr->getType()->isRealFloatingType())
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001135 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001136
Eli Friedman2f445492008-08-22 00:06:13 +00001137 APFloat F(0.0);
1138 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001139 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001140
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001141 Result = HandleFloatToIntCast(DestType, SubExpr->getType(), F, Info.Ctx);
Chris Lattnera42f09a2008-07-11 19:10:17 +00001142 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001143}
Anders Carlsson02a34c32008-07-08 14:30:00 +00001144
Chris Lattnera823ccf2008-07-11 18:11:29 +00001145//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +00001146// Float Evaluation
1147//===----------------------------------------------------------------------===//
1148
1149namespace {
1150class VISIBILITY_HIDDEN FloatExprEvaluator
1151 : public StmtVisitor<FloatExprEvaluator, bool> {
1152 EvalInfo &Info;
1153 APFloat &Result;
1154public:
1155 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1156 : Info(info), Result(result) {}
1157
1158 bool VisitStmt(Stmt *S) {
1159 return false;
1160 }
1161
1162 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +00001163 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001164
Daniel Dunbar804ead02008-10-16 03:51:50 +00001165 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001166 bool VisitBinaryOperator(const BinaryOperator *E);
1167 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +00001168 bool VisitCastExpr(CastExpr *E);
1169 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001170};
1171} // end anonymous namespace
1172
1173static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1174 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1175}
1176
Chris Lattner87293782008-10-06 05:28:25 +00001177bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +00001178 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner27cde262008-10-06 05:53:16 +00001179 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +00001180 case Builtin::BI__builtin_huge_val:
1181 case Builtin::BI__builtin_huge_valf:
1182 case Builtin::BI__builtin_huge_vall:
1183 case Builtin::BI__builtin_inf:
1184 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001185 case Builtin::BI__builtin_infl: {
1186 const llvm::fltSemantics &Sem =
1187 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +00001188 Result = llvm::APFloat::getInf(Sem);
1189 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001190 }
Chris Lattner667e1ee2008-10-06 06:31:58 +00001191
1192 case Builtin::BI__builtin_nan:
1193 case Builtin::BI__builtin_nanf:
1194 case Builtin::BI__builtin_nanl:
1195 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1196 // can't constant fold it.
1197 if (const StringLiteral *S =
1198 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1199 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001200 const llvm::fltSemantics &Sem =
1201 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +00001202 Result = llvm::APFloat::getNaN(Sem);
1203 return true;
1204 }
1205 }
1206 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +00001207
1208 case Builtin::BI__builtin_fabs:
1209 case Builtin::BI__builtin_fabsf:
1210 case Builtin::BI__builtin_fabsl:
1211 if (!EvaluateFloat(E->getArg(0), Result, Info))
1212 return false;
1213
1214 if (Result.isNegative())
1215 Result.changeSign();
1216 return true;
1217
1218 case Builtin::BI__builtin_copysign:
1219 case Builtin::BI__builtin_copysignf:
1220 case Builtin::BI__builtin_copysignl: {
1221 APFloat RHS(0.);
1222 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1223 !EvaluateFloat(E->getArg(1), RHS, Info))
1224 return false;
1225 Result.copySign(RHS);
1226 return true;
1227 }
Chris Lattner87293782008-10-06 05:28:25 +00001228 }
1229}
1230
Daniel Dunbar804ead02008-10-16 03:51:50 +00001231bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes1cea4f42008-11-19 17:44:31 +00001232 if (E->getOpcode() == UnaryOperator::Deref)
1233 return false;
1234
Daniel Dunbar804ead02008-10-16 03:51:50 +00001235 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1236 return false;
1237
1238 switch (E->getOpcode()) {
1239 default: return false;
1240 case UnaryOperator::Plus:
1241 return true;
1242 case UnaryOperator::Minus:
1243 Result.changeSign();
1244 return true;
1245 }
1246}
Chris Lattner87293782008-10-06 05:28:25 +00001247
Eli Friedman2f445492008-08-22 00:06:13 +00001248bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1249 // FIXME: Diagnostics? I really don't understand how the warnings
1250 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +00001251 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +00001252 if (!EvaluateFloat(E->getLHS(), Result, Info))
1253 return false;
1254 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1255 return false;
1256
1257 switch (E->getOpcode()) {
1258 default: return false;
1259 case BinaryOperator::Mul:
1260 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1261 return true;
1262 case BinaryOperator::Add:
1263 Result.add(RHS, APFloat::rmNearestTiesToEven);
1264 return true;
1265 case BinaryOperator::Sub:
1266 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1267 return true;
1268 case BinaryOperator::Div:
1269 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1270 return true;
1271 case BinaryOperator::Rem:
1272 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1273 return true;
1274 }
1275}
1276
1277bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1278 Result = E->getValue();
1279 return true;
1280}
1281
Eli Friedman7888b932008-11-12 09:44:48 +00001282bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1283 Expr* SubExpr = E->getSubExpr();
Nate Begemand6d2f772009-01-18 03:20:47 +00001284
Eli Friedman7888b932008-11-12 09:44:48 +00001285 if (SubExpr->getType()->isIntegralType()) {
1286 APSInt IntResult;
1287 if (!EvaluateInteger(E, IntResult, Info))
1288 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001289 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1290 IntResult, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001291 return true;
1292 }
1293 if (SubExpr->getType()->isRealFloatingType()) {
1294 if (!Visit(SubExpr))
1295 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001296 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1297 Result, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001298 return true;
1299 }
1300
1301 return false;
1302}
1303
1304bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1305 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1306 return true;
1307}
1308
Eli Friedman2f445492008-08-22 00:06:13 +00001309//===----------------------------------------------------------------------===//
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001310// Complex Evaluation (for float and integer)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001311//===----------------------------------------------------------------------===//
1312
1313namespace {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001314class VISIBILITY_HIDDEN ComplexExprEvaluator
1315 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001316 EvalInfo &Info;
1317
1318public:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001319 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001320
1321 //===--------------------------------------------------------------------===//
1322 // Visitor Methods
1323 //===--------------------------------------------------------------------===//
1324
1325 APValue VisitStmt(Stmt *S) {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001326 return APValue();
1327 }
1328
1329 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1330
1331 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001332 Expr* SubExpr = E->getSubExpr();
1333
1334 if (SubExpr->getType()->isRealFloatingType()) {
1335 APFloat Result(0.0);
1336
1337 if (!EvaluateFloat(SubExpr, Result, Info))
1338 return APValue();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001339
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001340 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001341 Result);
1342 } else {
1343 assert(SubExpr->getType()->isIntegerType() &&
1344 "Unexpected imaginary literal.");
1345
1346 llvm::APSInt Result;
1347 if (!EvaluateInteger(SubExpr, Result, Info))
1348 return APValue();
1349
1350 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1351 Zero = 0;
1352 return APValue(Zero, Result);
1353 }
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001354 }
1355
Anders Carlssonad2794c2008-11-16 21:51:21 +00001356 APValue VisitCastExpr(CastExpr *E) {
1357 Expr* SubExpr = E->getSubExpr();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001358 QualType EltType = E->getType()->getAsComplexType()->getElementType();
1359 QualType SubType = SubExpr->getType();
Anders Carlssonad2794c2008-11-16 21:51:21 +00001360
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001361 if (SubType->isRealFloatingType()) {
Anders Carlssonad2794c2008-11-16 21:51:21 +00001362 APFloat Result(0.0);
1363
1364 if (!EvaluateFloat(SubExpr, Result, Info))
1365 return APValue();
1366
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001367 // Apply float conversion if necessary.
1368 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbarf8abb942009-01-24 19:08:01 +00001369 return APValue(Result,
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001370 APFloat(Result.getSemantics(), APFloat::fcZero, false));
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001371 } else if (SubType->isIntegerType()) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001372 APSInt Result;
1373
1374 if (!EvaluateInteger(SubExpr, Result, Info))
1375 return APValue();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001376
1377 // Apply integer conversion if necessary.
1378 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001379 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1380 Zero = 0;
1381 return APValue(Result, Zero);
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001382 } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1383 APValue Src;
1384
1385 if (!EvaluateComplex(SubExpr, Src, Info))
1386 return APValue();
1387
1388 QualType SrcType = CT->getElementType();
1389
1390 if (Src.isComplexFloat()) {
1391 if (EltType->isRealFloatingType()) {
1392 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1393 Src.getComplexFloatReal(),
1394 Info.Ctx),
1395 HandleFloatToFloatCast(EltType, SrcType,
1396 Src.getComplexFloatImag(),
1397 Info.Ctx));
1398 } else {
1399 return APValue(HandleFloatToIntCast(EltType, SrcType,
1400 Src.getComplexFloatReal(),
1401 Info.Ctx),
1402 HandleFloatToIntCast(EltType, SrcType,
1403 Src.getComplexFloatImag(),
1404 Info.Ctx));
1405 }
1406 } else {
1407 assert(Src.isComplexInt() && "Invalid evaluate result.");
1408 if (EltType->isRealFloatingType()) {
1409 return APValue(HandleIntToFloatCast(EltType, SrcType,
1410 Src.getComplexIntReal(),
1411 Info.Ctx),
1412 HandleIntToFloatCast(EltType, SrcType,
1413 Src.getComplexIntImag(),
1414 Info.Ctx));
1415 } else {
1416 return APValue(HandleIntToIntCast(EltType, SrcType,
1417 Src.getComplexIntReal(),
1418 Info.Ctx),
1419 HandleIntToIntCast(EltType, SrcType,
1420 Src.getComplexIntImag(),
1421 Info.Ctx));
1422 }
1423 }
Anders Carlssonad2794c2008-11-16 21:51:21 +00001424 }
1425
1426 // FIXME: Handle more casts.
1427 return APValue();
1428 }
1429
1430 APValue VisitBinaryOperator(const BinaryOperator *E);
1431
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001432};
1433} // end anonymous namespace
1434
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001435static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001436{
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001437 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1438 assert((!Result.isComplexFloat() ||
1439 (&Result.getComplexFloatReal().getSemantics() ==
1440 &Result.getComplexFloatImag().getSemantics())) &&
1441 "Invalid complex evaluation.");
1442 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001443}
1444
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001445APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
Anders Carlssonad2794c2008-11-16 21:51:21 +00001446{
1447 APValue Result, RHS;
1448
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001449 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001450 return APValue();
1451
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001452 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001453 return APValue();
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001454
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001455 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1456 "Invalid operands to binary operator.");
Anders Carlssonad2794c2008-11-16 21:51:21 +00001457 switch (E->getOpcode()) {
1458 default: return APValue();
1459 case BinaryOperator::Add:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001460 if (Result.isComplexFloat()) {
1461 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1462 APFloat::rmNearestTiesToEven);
1463 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1464 APFloat::rmNearestTiesToEven);
1465 } else {
1466 Result.getComplexIntReal() += RHS.getComplexIntReal();
1467 Result.getComplexIntImag() += RHS.getComplexIntImag();
1468 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001469 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001470 case BinaryOperator::Sub:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001471 if (Result.isComplexFloat()) {
1472 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1473 APFloat::rmNearestTiesToEven);
1474 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1475 APFloat::rmNearestTiesToEven);
1476 } else {
1477 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1478 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1479 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001480 break;
1481 case BinaryOperator::Mul:
1482 if (Result.isComplexFloat()) {
1483 APValue LHS = Result;
1484 APFloat &LHS_r = LHS.getComplexFloatReal();
1485 APFloat &LHS_i = LHS.getComplexFloatImag();
1486 APFloat &RHS_r = RHS.getComplexFloatReal();
1487 APFloat &RHS_i = RHS.getComplexFloatImag();
1488
1489 APFloat Tmp = LHS_r;
1490 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1491 Result.getComplexFloatReal() = Tmp;
1492 Tmp = LHS_i;
1493 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1494 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1495
1496 Tmp = LHS_r;
1497 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1498 Result.getComplexFloatImag() = Tmp;
1499 Tmp = LHS_i;
1500 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1501 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1502 } else {
1503 APValue LHS = Result;
1504 Result.getComplexIntReal() =
1505 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1506 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1507 Result.getComplexIntImag() =
1508 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1509 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1510 }
1511 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001512 }
1513
1514 return Result;
1515}
1516
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001517//===----------------------------------------------------------------------===//
Chris Lattneref069662008-11-16 21:24:15 +00001518// Top level Expr::Evaluate method.
Chris Lattnera823ccf2008-07-11 18:11:29 +00001519//===----------------------------------------------------------------------===//
1520
Chris Lattneref069662008-11-16 21:24:15 +00001521/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner87293782008-10-06 05:28:25 +00001522/// any crazy technique (that has nothing to do with language standards) that
1523/// we want to. If this function returns true, it returns the folded constant
1524/// in Result.
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001525bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1526 EvalInfo Info(Ctx, Result);
Anders Carlssondd8d41f2008-11-30 16:38:33 +00001527
Nate Begemand6d2f772009-01-18 03:20:47 +00001528 if (getType()->isVectorType()) {
1529 if (!EvaluateVector(this, Result.Val, Info))
1530 return false;
1531 } else if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +00001532 llvm::APSInt sInt(32);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001533 if (!EvaluateInteger(this, sInt, Info))
1534 return false;
1535
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001536 Result.Val = APValue(sInt);
Mike Stump5b601ff2009-02-18 21:44:49 +00001537 } else if (getType()->isPointerType()
1538 || getType()->isBlockPointerType()) {
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001539 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001540 return false;
Eli Friedman2f445492008-08-22 00:06:13 +00001541 } else if (getType()->isRealFloatingType()) {
1542 llvm::APFloat f(0.0);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001543 if (!EvaluateFloat(this, f, Info))
1544 return false;
1545
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001546 Result.Val = APValue(f);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001547 } else if (getType()->isAnyComplexType()) {
1548 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001549 return false;
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001550 } else
Anders Carlssoncb6a2e82008-11-22 22:56:32 +00001551 return false;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001552
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001553 return true;
1554}
1555
Chris Lattneref069662008-11-16 21:24:15 +00001556/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001557/// folded, but discard the result.
1558bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson197f6f72008-12-01 06:44:05 +00001559 EvalResult Result;
1560 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001561}
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001562
1563APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson8c3de802008-12-19 20:58:05 +00001564 EvalResult EvalResult;
1565 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarddebeca2009-01-15 18:32:35 +00001566 Result = Result;
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001567 assert(Result && "Could not evaluate expression");
Anders Carlsson8c3de802008-12-19 20:58:05 +00001568 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001569
Anders Carlsson8c3de802008-12-19 20:58:05 +00001570 return EvalResult.Val.getInt();
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001571}