blob: da251fcea9aa0920f5f75b97a5c19df7501c95fe [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-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 Friedman4efaa272008-11-12 09:44:48 +000016#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/AST/ASTDiagnostic.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssonc754aa62008-07-08 05:13:58 +000020#include "llvm/Support/Compiler.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000021using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000022using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000023using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000024
Chris Lattner87eae5e2008-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 Carlsson54da0492008-11-30 16:38:33 +000042 /// EvalResult - Contains information about the evaluation.
43 Expr::EvalResult &EvalResult;
Anders Carlssonf0c1e4b2008-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 Lattner87eae5e2008-07-11 22:52:41 +000048
Anders Carlsson54da0492008-11-30 16:38:33 +000049 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx),
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +000050 EvalResult(evalresult), ShortCircuit(0) {}
Chris Lattner87eae5e2008-07-11 22:52:41 +000051};
52
53
Eli Friedman4efaa272008-11-12 09:44:48 +000054static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-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 Friedmand8bfe7f2008-08-22 00:06:13 +000057static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +000058static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +000059
60//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-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 Dunbara2cfd342009-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 Friedman4efaa272008-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 Dunbar8a7b7c62008-11-12 21:52:46 +0000145#if 0
Eli Friedman4efaa272008-11-12 09:44:48 +0000146 // FIXME: Remove this when we support more expressions.
147 printf("Unhandled pointer statement\n");
148 S->dump();
Daniel Dunbar8a7b7c62008-11-12 21:52:46 +0000149#endif
Eli Friedman4efaa272008-11-12 09:44:48 +0000150 return APValue();
151 }
152
153 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson35873c42008-11-24 04:41:22 +0000154 APValue VisitDeclRefExpr(DeclRefExpr *E);
Eli Friedman4efaa272008-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 Carlsson3068d112008-11-16 19:01:22 +0000159 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman4efaa272008-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 Carlsson35873c42008-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 Friedman4efaa272008-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 Gregor86f19402008-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 Friedman4efaa272008-11-12 09:44:48 +0000202
203 // FIXME: This is linear time.
Douglas Gregor44b43212008-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 Friedman4efaa272008-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 Carlsson3068d112008-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 Friedman4efaa272008-11-12 09:44:48 +0000236
237//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000238// Pointer Evaluation
239//===----------------------------------------------------------------------===//
240
Anders Carlssonc754aa62008-07-08 05:13:58 +0000241namespace {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000242class VISIBILITY_HIDDEN PointerExprEvaluator
243 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000244 EvalInfo &Info;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000245public:
Anders Carlsson2bad1682008-07-08 14:30:00 +0000246
Chris Lattner87eae5e2008-07-11 22:52:41 +0000247 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000248
Anders Carlsson2bad1682008-07-08 14:30:00 +0000249 APValue VisitStmt(Stmt *S) {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000250 return APValue();
251 }
252
253 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
254
Anders Carlsson650c92f2008-07-08 15:34:11 +0000255 APValue VisitBinaryOperator(const BinaryOperator *E);
256 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000257 APValue VisitUnaryOperator(const UnaryOperator *E);
258 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
259 { return APValue(E, 0); }
Eli Friedmanf0115892009-01-25 01:21:06 +0000260 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
261 { return APValue(E, 0); }
Eli Friedman3941b182009-01-25 01:54:01 +0000262 APValue VisitCallExpr(CallExpr *E);
Mike Stumpbd65cac2009-02-19 01:01:04 +0000263 APValue VisitBlockExpr(BlockExpr *E) { return APValue(E, 0); }
Eli Friedman4efaa272008-11-12 09:44:48 +0000264 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlsson650c92f2008-07-08 15:34:11 +0000265};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000266} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000267
Chris Lattner87eae5e2008-07-11 22:52:41 +0000268static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Mike Stumpca2f3fd2009-02-18 21:44:49 +0000269 if (!E->getType()->isPointerType()
270 && !E->getType()->isBlockPointerType())
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000271 return false;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000272 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-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 Lattner87eae5e2008-07-11 22:52:41 +0000287 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000288 return APValue();
289
290 llvm::APSInt AdditionalOffset(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000291 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000292 return APValue();
293
Eli Friedman4efaa272008-11-12 09:44:48 +0000294 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000295 uint64_t SizeOfPointee;
296
297 // Explicitly handle GNU void* and function pointer arithmetic extensions.
298 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
299 SizeOfPointee = 1;
300 else
301 SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
Eli Friedman4efaa272008-11-12 09:44:48 +0000302
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000303 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman4efaa272008-11-12 09:44:48 +0000304
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000305 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman4efaa272008-11-12 09:44:48 +0000306 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000307 else
Eli Friedman4efaa272008-11-12 09:44:48 +0000308 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
309
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000310 return APValue(ResultLValue.getLValueBase(), Offset);
311}
Eli Friedman4efaa272008-11-12 09:44:48 +0000312
313APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
314 if (E->getOpcode() == UnaryOperator::Extension) {
315 // FIXME: Deal with warnings?
316 return Visit(E->getSubExpr());
317 }
318
319 if (E->getOpcode() == UnaryOperator::AddrOf) {
320 APValue result;
321 if (EvaluateLValue(E->getSubExpr(), result, Info))
322 return result;
323 }
324
325 return APValue();
326}
Anders Carlssond407a762008-12-05 05:24:13 +0000327
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000328
Chris Lattnerb542afe2008-07-11 19:10:17 +0000329APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000330 const Expr* SubExpr = E->getSubExpr();
331
332 // Check for pointer->pointer cast
333 if (SubExpr->getType()->isPointerType()) {
334 APValue Result;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000335 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000336 return Result;
337 return APValue();
338 }
339
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000340 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000341 llvm::APSInt Result(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000342 if (EvaluateInteger(SubExpr, Result, Info)) {
343 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000344 return APValue(0, Result.getZExtValue());
345 }
346 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000347
348 if (SubExpr->getType()->isFunctionType() ||
349 SubExpr->getType()->isArrayType()) {
350 APValue Result;
351 if (EvaluateLValue(SubExpr, Result, Info))
352 return Result;
353 return APValue();
354 }
355
356 //assert(0 && "Unhandled cast");
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000357 return APValue();
358}
359
Eli Friedman3941b182009-01-25 01:54:01 +0000360APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000361 if (E->isBuiltinCall(Info.Ctx) ==
362 Builtin::BI__builtin___CFStringMakeConstantString)
Eli Friedman3941b182009-01-25 01:54:01 +0000363 return APValue(E, 0);
364 return APValue();
365}
366
Eli Friedman4efaa272008-11-12 09:44:48 +0000367APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
368 bool BoolResult;
369 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
370 return APValue();
371
372 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
373
374 APValue Result;
375 if (EvaluatePointer(EvalExpr, Result, Info))
376 return Result;
377 return APValue();
378}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000379
380//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000381// Vector Evaluation
382//===----------------------------------------------------------------------===//
383
384namespace {
385 class VISIBILITY_HIDDEN VectorExprEvaluator
386 : public StmtVisitor<VectorExprEvaluator, APValue> {
387 EvalInfo &Info;
388 public:
389
390 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
391
392 APValue VisitStmt(Stmt *S) {
393 return APValue();
394 }
395
396 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
397 APValue VisitCastExpr(const CastExpr* E);
398 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
399 APValue VisitInitListExpr(const InitListExpr *E);
400 };
401} // end anonymous namespace
402
403static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
404 if (!E->getType()->isVectorType())
405 return false;
406 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
407 return !Result.isUninit();
408}
409
410APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
411 const Expr* SE = E->getSubExpr();
412
413 // Check for vector->vector bitcast.
414 if (SE->getType()->isVectorType())
415 return this->Visit(const_cast<Expr*>(SE));
416
417 return APValue();
418}
419
420APValue
421VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
422 return this->Visit(const_cast<Expr*>(E->getInitializer()));
423}
424
425APValue
426VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
427 const VectorType *VT = E->getType()->getAsVectorType();
428 unsigned NumInits = E->getNumInits();
429
430 if (!VT || VT->getNumElements() != NumInits)
431 return APValue();
432
433 QualType EltTy = VT->getElementType();
434 llvm::SmallVector<APValue, 4> Elements;
435
436 for (unsigned i = 0; i < NumInits; i++) {
437 if (EltTy->isIntegerType()) {
438 llvm::APSInt sInt(32);
439 if (!EvaluateInteger(E->getInit(i), sInt, Info))
440 return APValue();
441 Elements.push_back(APValue(sInt));
442 } else {
443 llvm::APFloat f(0.0);
444 if (!EvaluateFloat(E->getInit(i), f, Info))
445 return APValue();
446 Elements.push_back(APValue(f));
447 }
448 }
449 return APValue(&Elements[0], Elements.size());
450}
451
452//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000453// Integer Evaluation
454//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000455
456namespace {
Anders Carlssonc754aa62008-07-08 05:13:58 +0000457class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000458 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000459 EvalInfo &Info;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000460 APSInt &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000461public:
Chris Lattner87eae5e2008-07-11 22:52:41 +0000462 IntExprEvaluator(EvalInfo &info, APSInt &result)
463 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000464
Chris Lattner7a767782008-07-11 19:24:49 +0000465 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner54176fd2008-07-12 00:14:42 +0000466 return (unsigned)Info.Ctx.getIntWidth(T);
467 }
468
Anders Carlsson82206e22008-11-30 18:14:57 +0000469 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlsson54da0492008-11-30 16:38:33 +0000470 Info.EvalResult.DiagLoc = L;
471 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000472 Info.EvalResult.DiagExpr = E;
Chris Lattner54176fd2008-07-12 00:14:42 +0000473 return true; // still a constant.
474 }
475
Anders Carlsson82206e22008-11-30 18:14:57 +0000476 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000477 // If this is in an unevaluated portion of the subexpression, ignore the
478 // error.
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000479 if (Info.ShortCircuit) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000480 // If error is ignored because the value isn't evaluated, get the real
481 // type at least to prevent errors downstream.
Anders Carlsson82206e22008-11-30 18:14:57 +0000482 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
483 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000484 return true;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000485 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000486
Chris Lattner32fea9d2008-11-12 07:43:42 +0000487 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000488 if (Info.EvalResult.Diag == 0) {
489 Info.EvalResult.DiagLoc = L;
490 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000491 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000492 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000493 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000494 }
495
Anders Carlssonc754aa62008-07-08 05:13:58 +0000496 //===--------------------------------------------------------------------===//
497 // Visitor Methods
498 //===--------------------------------------------------------------------===//
Chris Lattner32fea9d2008-11-12 07:43:42 +0000499
500 bool VisitStmt(Stmt *) {
501 assert(0 && "This should be called on integers, stmts are not integers");
502 return false;
503 }
Chris Lattner7a767782008-07-11 19:24:49 +0000504
Chris Lattner32fea9d2008-11-12 07:43:42 +0000505 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000506 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000507 }
508
Chris Lattnerb542afe2008-07-11 19:10:17 +0000509 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000510
Chris Lattner4c4867e2008-07-12 00:38:25 +0000511 bool VisitIntegerLiteral(const IntegerLiteral *E) {
512 Result = E->getValue();
513 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
514 return true;
515 }
516 bool VisitCharacterLiteral(const CharacterLiteral *E) {
517 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
518 Result = E->getValue();
519 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
520 return true;
521 }
522 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
523 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarac620de2008-10-24 08:07:57 +0000524 // Per gcc docs "this built-in function ignores top level
525 // qualifiers". We need to use the canonical version to properly
526 // be able to strip CRV qualifiers from the type.
527 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
528 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
529 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
530 T1.getUnqualifiedType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000531 return true;
532 }
533 bool VisitDeclRefExpr(const DeclRefExpr *E);
534 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000535 bool VisitBinaryOperator(const BinaryOperator *E);
536 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000537 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000538
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000539 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000540 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
541
Anders Carlsson3068d112008-11-16 19:01:22 +0000542 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Anders Carlsson529569e2008-11-16 22:46:56 +0000543 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson3068d112008-11-16 19:01:22 +0000544 Result = E->getValue();
545 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
546 return true;
547 }
548
Anders Carlsson3f704562008-12-21 22:39:40 +0000549 bool VisitGNUNullExpr(const GNUNullExpr *E) {
550 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
551 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
552 return true;
553 }
554
Anders Carlsson3068d112008-11-16 19:01:22 +0000555 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
556 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
557 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
558 return true;
559 }
560
Sebastian Redl64b45f72009-01-05 20:52:13 +0000561 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
562 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarc87a2822009-02-17 23:20:26 +0000563 Result = E->EvaluateTrait();
Sebastian Redl64b45f72009-01-05 20:52:13 +0000564 return true;
565 }
566
Chris Lattnerfcee0012008-07-11 21:24:13 +0000567private:
Chris Lattneraf707ab2009-01-24 21:53:27 +0000568 unsigned GetAlignOfExpr(const Expr *E);
569 unsigned GetAlignOfType(QualType T);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000570};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000571} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000572
Chris Lattner87eae5e2008-07-11 22:52:41 +0000573static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
574 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson650c92f2008-07-08 15:34:11 +0000575}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000576
Chris Lattner4c4867e2008-07-12 00:38:25 +0000577bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
578 // Enums are integer constant exprs.
579 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
580 Result = D->getInitVal();
Eli Friedmane9a0f432008-12-08 02:21:03 +0000581 // FIXME: This is an ugly hack around the fact that enums don't set their
582 // signedness consistently; see PR3173
583 Result.setIsUnsigned(!E->getType()->isSignedIntegerType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000584 return true;
585 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +0000586
587 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
588 if (Info.Ctx.getLangOptions().CPlusPlus &&
589 E->getType().getCVRQualifiers() == QualType::Const) {
590 if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
591 if (const Expr *Init = D->getInit())
592 return Visit(const_cast<Expr*>(Init));
593 }
594 }
595
Chris Lattner4c4867e2008-07-12 00:38:25 +0000596 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000597 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000598}
599
Chris Lattnera4d55d82008-10-06 06:40:35 +0000600/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
601/// as GCC.
602static int EvaluateBuiltinClassifyType(const CallExpr *E) {
603 // The following enum mimics the values returned by GCC.
604 enum gcc_type_class {
605 no_type_class = -1,
606 void_type_class, integer_type_class, char_type_class,
607 enumeral_type_class, boolean_type_class,
608 pointer_type_class, reference_type_class, offset_type_class,
609 real_type_class, complex_type_class,
610 function_type_class, method_type_class,
611 record_type_class, union_type_class,
612 array_type_class, string_type_class,
613 lang_type_class
614 };
615
616 // If no argument was supplied, default to "no_type_class". This isn't
617 // ideal, however it is what gcc does.
618 if (E->getNumArgs() == 0)
619 return no_type_class;
620
621 QualType ArgTy = E->getArg(0)->getType();
622 if (ArgTy->isVoidType())
623 return void_type_class;
624 else if (ArgTy->isEnumeralType())
625 return enumeral_type_class;
626 else if (ArgTy->isBooleanType())
627 return boolean_type_class;
628 else if (ArgTy->isCharType())
629 return string_type_class; // gcc doesn't appear to use char_type_class
630 else if (ArgTy->isIntegerType())
631 return integer_type_class;
632 else if (ArgTy->isPointerType())
633 return pointer_type_class;
634 else if (ArgTy->isReferenceType())
635 return reference_type_class;
636 else if (ArgTy->isRealType())
637 return real_type_class;
638 else if (ArgTy->isComplexType())
639 return complex_type_class;
640 else if (ArgTy->isFunctionType())
641 return function_type_class;
642 else if (ArgTy->isStructureType())
643 return record_type_class;
644 else if (ArgTy->isUnionType())
645 return union_type_class;
646 else if (ArgTy->isArrayType())
647 return array_type_class;
648 else if (ArgTy->isUnionType())
649 return union_type_class;
650 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
651 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
652 return -1;
653}
654
Chris Lattner4c4867e2008-07-12 00:38:25 +0000655bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
656 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner4c4867e2008-07-12 00:38:25 +0000657
Douglas Gregor3c385e52009-02-14 18:57:46 +0000658 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +0000659 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000660 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000661 case Builtin::BI__builtin_classify_type:
Chris Lattnera4d55d82008-10-06 06:40:35 +0000662 Result.setIsSigned(true);
663 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000664 return true;
665
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000666 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +0000667 // __builtin_constant_p always has one operand: it returns true if that
668 // operand can be folded, false otherwise.
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000669 Result = E->getArg(0)->isEvaluatable(Info.Ctx);
Chris Lattner019f4e82008-10-06 05:28:25 +0000670 return true;
671 }
Chris Lattner4c4867e2008-07-12 00:38:25 +0000672}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000673
Chris Lattnerb542afe2008-07-11 19:10:17 +0000674bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000675 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +0000676 if (!Visit(E->getRHS()))
677 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +0000678
679 if (!Info.ShortCircuit) {
680 // If we can't evaluate the LHS, it must be because it has
681 // side effects.
682 if (!E->getLHS()->isEvaluatable(Info.Ctx))
683 Info.EvalResult.HasSideEffects = true;
684
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000685 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson4fdfb092008-12-01 06:44:05 +0000686 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000687
Anders Carlsson027f62e2008-12-01 02:07:06 +0000688 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +0000689 }
690
691 if (E->isLogicalOp()) {
692 // These need to be handled specially because the operands aren't
693 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000694 bool lhsResult, rhsResult;
Anders Carlsson51fe9962008-11-22 21:04:56 +0000695
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000696 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +0000697 // We were able to evaluate the LHS, see if we can get away with not
698 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000699 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
700 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000701 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
702 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000703 Result = lhsResult;
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000704
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000705 Info.ShortCircuit++;
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000706 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000707 Info.ShortCircuit--;
708
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000709 if (rhsEvaluated)
710 return true;
711
712 // FIXME: Return an extension warning saying that the RHS could not be
713 // evaluated.
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000714 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +0000715 }
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000716
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000717 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000718 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
719 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
720 if (E->getOpcode() == BinaryOperator::LOr)
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000721 Result = lhsResult || rhsResult;
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000722 else
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000723 Result = lhsResult && rhsResult;
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000724 return true;
725 }
726 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000727 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000728 // We can't evaluate the LHS; however, sometimes the result
729 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000730 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
731 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000732 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
733 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000734 Result = rhsResult;
735
736 // Since we werent able to evaluate the left hand side, it
737 // must have had side effects.
738 Info.EvalResult.HasSideEffects = true;
739
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000740 return true;
741 }
742 }
Anders Carlsson51fe9962008-11-22 21:04:56 +0000743 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000744
Eli Friedmana6afa762008-11-13 06:09:17 +0000745 return false;
746 }
747
Anders Carlsson286f85e2008-11-16 07:17:21 +0000748 QualType LHSTy = E->getLHS()->getType();
749 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +0000750
751 if (LHSTy->isAnyComplexType()) {
752 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
753 APValue LHS, RHS;
754
755 if (!EvaluateComplex(E->getLHS(), LHS, Info))
756 return false;
757
758 if (!EvaluateComplex(E->getRHS(), RHS, Info))
759 return false;
760
761 if (LHS.isComplexFloat()) {
762 APFloat::cmpResult CR_r =
763 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
764 APFloat::cmpResult CR_i =
765 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
766
767 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
768 if (E->getOpcode() == BinaryOperator::EQ)
769 Result = (CR_r == APFloat::cmpEqual &&
770 CR_i == APFloat::cmpEqual);
771 else if (E->getOpcode() == BinaryOperator::NE)
772 Result = ((CR_r == APFloat::cmpGreaterThan ||
773 CR_r == APFloat::cmpLessThan) &&
774 (CR_i == APFloat::cmpGreaterThan ||
775 CR_i == APFloat::cmpLessThan));
776 else
777 assert(0 && "Invalid complex compartison.");
778 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
779 return true;
780 } else {
781 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
782 if (E->getOpcode() == BinaryOperator::EQ)
783 Result = (LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
784 LHS.getComplexIntImag() == RHS.getComplexIntImag());
785 else if (E->getOpcode() == BinaryOperator::NE)
786 Result = (LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
787 LHS.getComplexIntImag() != RHS.getComplexIntImag());
788 else
789 assert(0 && "Invalid complex compartison.");
790 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
791 return true;
792 }
793 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000794
795 if (LHSTy->isRealFloatingType() &&
796 RHSTy->isRealFloatingType()) {
797 APFloat RHS(0.0), LHS(0.0);
798
799 if (!EvaluateFloat(E->getRHS(), RHS, Info))
800 return false;
801
802 if (!EvaluateFloat(E->getLHS(), LHS, Info))
803 return false;
804
805 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +0000806
807 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
808
Anders Carlsson286f85e2008-11-16 07:17:21 +0000809 switch (E->getOpcode()) {
810 default:
811 assert(0 && "Invalid binary operator!");
812 case BinaryOperator::LT:
813 Result = CR == APFloat::cmpLessThan;
814 break;
815 case BinaryOperator::GT:
816 Result = CR == APFloat::cmpGreaterThan;
817 break;
818 case BinaryOperator::LE:
819 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
820 break;
821 case BinaryOperator::GE:
822 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
823 break;
824 case BinaryOperator::EQ:
825 Result = CR == APFloat::cmpEqual;
826 break;
827 case BinaryOperator::NE:
828 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
829 break;
830 }
831
Anders Carlsson286f85e2008-11-16 07:17:21 +0000832 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
833 return true;
834 }
835
Anders Carlsson3068d112008-11-16 19:01:22 +0000836 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson529569e2008-11-16 22:46:56 +0000837 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000838 APValue LHSValue;
839 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
840 return false;
841
842 APValue RHSValue;
843 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
844 return false;
845
846 // FIXME: Is this correct? What if only one of the operands has a base?
847 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
848 return false;
849
850 const QualType Type = E->getLHS()->getType();
851 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
852
853 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
854 D /= Info.Ctx.getTypeSize(ElementType) / 8;
855
Anders Carlsson3068d112008-11-16 19:01:22 +0000856 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson529569e2008-11-16 22:46:56 +0000857 Result = D;
Anders Carlsson3068d112008-11-16 19:01:22 +0000858 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
859
860 return true;
861 }
862 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000863 if (!LHSTy->isIntegralType() ||
864 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000865 // We can't continue from here for non-integral types, and they
866 // could potentially confuse the following operations.
867 // FIXME: Deal with EQ and friends.
868 return false;
869 }
870
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000871 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000872 llvm::APSInt RHS(32);
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000873 if (!Visit(E->getLHS())) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000874 return false; // error in subexpression.
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000875 }
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000876
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000877
878 // FIXME Maybe we want to succeed even where we can't evaluate the
879 // right side of LAnd/LOr?
880 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner54176fd2008-07-12 00:14:42 +0000881 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000882 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000883
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000884 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000885 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000886 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner54176fd2008-07-12 00:14:42 +0000887 case BinaryOperator::Mul: Result *= RHS; return true;
888 case BinaryOperator::Add: Result += RHS; return true;
889 case BinaryOperator::Sub: Result -= RHS; return true;
890 case BinaryOperator::And: Result &= RHS; return true;
891 case BinaryOperator::Xor: Result ^= RHS; return true;
892 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner75a48812008-07-11 22:15:16 +0000893 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +0000894 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000895 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner75a48812008-07-11 22:15:16 +0000896 Result /= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000897 break;
Chris Lattner75a48812008-07-11 22:15:16 +0000898 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +0000899 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000900 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner75a48812008-07-11 22:15:16 +0000901 Result %= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000902 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000903 case BinaryOperator::Shl:
Chris Lattner54176fd2008-07-12 00:14:42 +0000904 // FIXME: Warn about out of range shift amounts!
Chris Lattnerb542afe2008-07-11 19:10:17 +0000905 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000906 break;
907 case BinaryOperator::Shr:
Chris Lattnerb542afe2008-07-11 19:10:17 +0000908 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000909 break;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000910
Chris Lattnerac7cb602008-07-11 19:29:32 +0000911 case BinaryOperator::LT:
912 Result = Result < RHS;
913 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
914 break;
915 case BinaryOperator::GT:
916 Result = Result > RHS;
917 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
918 break;
919 case BinaryOperator::LE:
920 Result = Result <= RHS;
921 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
922 break;
923 case BinaryOperator::GE:
924 Result = Result >= RHS;
925 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
926 break;
927 case BinaryOperator::EQ:
928 Result = Result == RHS;
929 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
930 break;
931 case BinaryOperator::NE:
932 Result = Result != RHS;
933 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
934 break;
Chris Lattner54176fd2008-07-12 00:14:42 +0000935 case BinaryOperator::LAnd:
936 Result = Result != 0 && RHS != 0;
937 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
938 break;
939 case BinaryOperator::LOr:
940 Result = Result != 0 || RHS != 0;
941 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
942 break;
Eli Friedmanb11e7782008-11-13 02:13:11 +0000943 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000944
945 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000946 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000947}
948
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000949bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +0000950 bool Cond;
951 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000952 return false;
953
Nuno Lopesa25bd552008-11-16 22:06:39 +0000954 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000955}
956
Chris Lattneraf707ab2009-01-24 21:53:27 +0000957unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
Chris Lattnere9feb472009-01-24 21:09:06 +0000958 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
959
960 // __alignof__(void) = 1 as a gcc extension.
961 if (Ty->isVoidType())
962 return 1;
963
964 // GCC extension: alignof(function) = 4.
965 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the
966 // attribute(align) directive.
967 if (Ty->isFunctionType())
968 return 4;
969
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000970 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty))
971 return GetAlignOfType(QualType(EXTQT->getBaseType(), 0));
Chris Lattnere9feb472009-01-24 21:09:06 +0000972
973 // alignof VLA/incomplete array.
974 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
975 return GetAlignOfType(VAT->getElementType());
976
977 // sizeof (objc class)?
978 if (isa<ObjCInterfaceType>(Ty))
979 return 1; // FIXME: This probably isn't right.
980
981 // Get information about the alignment.
982 unsigned CharSize = Info.Ctx.Target.getCharWidth();
983 return Info.Ctx.getTypeAlign(Ty) / CharSize;
984}
985
Chris Lattneraf707ab2009-01-24 21:53:27 +0000986unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
987 E = E->IgnoreParens();
988
989 // alignof decl is always accepted, even if it doesn't make sense: we default
990 // to 1 in those cases.
991 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000992 return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000993
994 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000995 return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000996
Chris Lattnere9feb472009-01-24 21:09:06 +0000997 return GetAlignOfType(E->getType());
998}
999
1000
Sebastian Redl05189992008-11-11 17:56:53 +00001001/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1002/// expression's type.
1003bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1004 QualType DstTy = E->getType();
Chris Lattnerfcee0012008-07-11 21:24:13 +00001005 // Return the result in the right width.
1006 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
1007 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
1008
Chris Lattnere9feb472009-01-24 21:09:06 +00001009 // Handle alignof separately.
1010 if (!E->isSizeOf()) {
1011 if (E->isArgumentType())
1012 Result = GetAlignOfType(E->getArgumentType());
1013 else
1014 Result = GetAlignOfExpr(E->getArgumentExpr());
1015 return true;
1016 }
1017
Sebastian Redl05189992008-11-11 17:56:53 +00001018 QualType SrcTy = E->getTypeOfArgument();
1019
Chris Lattnerfcee0012008-07-11 21:24:13 +00001020 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman4efaa272008-11-12 09:44:48 +00001021 if (SrcTy->isVoidType()) {
Chris Lattnerfcee0012008-07-11 21:24:13 +00001022 Result = 1;
Eli Friedman4efaa272008-11-12 09:44:48 +00001023 return true;
1024 }
Chris Lattnerfcee0012008-07-11 21:24:13 +00001025
1026 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001027 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001028 return false;
Fariborz Jahanian67303c12009-01-16 01:42:12 +00001029
Chris Lattnerfcee0012008-07-11 21:24:13 +00001030 // GCC extension: sizeof(function) = 1.
1031 if (SrcTy->isFunctionType()) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001032 Result = 1;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001033 return true;
1034 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001035
1036 if (SrcTy->isObjCInterfaceType()) {
1037 // Slightly unusual case: the size of an ObjC interface type is the
1038 // size of the class. This code intentionally falls through to the normal
1039 // case.
1040 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
1041 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
1042 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
1043 }
1044
Chris Lattnere9feb472009-01-24 21:09:06 +00001045 // Get information about the size.
Chris Lattner87eae5e2008-07-11 22:52:41 +00001046 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnere9feb472009-01-24 21:09:06 +00001047 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001048 return true;
1049}
1050
Chris Lattnerb542afe2008-07-11 19:10:17 +00001051bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001052 // Special case unary operators that do not need their subexpression
1053 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner75a48812008-07-11 22:15:16 +00001054 if (E->isOffsetOfOp()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001055 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner87eae5e2008-07-11 22:52:41 +00001056 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner75a48812008-07-11 22:15:16 +00001057 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
1058 return true;
1059 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001060
1061 if (E->getOpcode() == UnaryOperator::LNot) {
1062 // LNot's operand isn't necessarily an integer, so we handle it specially.
1063 bool bres;
1064 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1065 return false;
1066 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
1067 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
1068 Result = !bres;
1069 return true;
1070 }
1071
Chris Lattner87eae5e2008-07-11 22:52:41 +00001072 // Get the operand value into 'Result'.
1073 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001074 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001075
Chris Lattner75a48812008-07-11 22:15:16 +00001076 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001077 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001078 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1079 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001080 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001081 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001082 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1083 // If so, we could clear the diagnostic ID.
Chris Lattner75a48812008-07-11 22:15:16 +00001084 case UnaryOperator::Plus:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001085 // The result is always just the subexpr.
Chris Lattner75a48812008-07-11 22:15:16 +00001086 break;
1087 case UnaryOperator::Minus:
1088 Result = -Result;
1089 break;
1090 case UnaryOperator::Not:
1091 Result = ~Result;
1092 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001093 }
1094
1095 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +00001096 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001097}
1098
Chris Lattner732b2232008-07-12 01:15:53 +00001099/// HandleCast - This is used to evaluate implicit or explicit casts where the
1100/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001101bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001102 Expr *SubExpr = E->getSubExpr();
1103 QualType DestType = E->getType();
1104
Chris Lattner7a767782008-07-11 19:24:49 +00001105 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001106
Eli Friedman4efaa272008-11-12 09:44:48 +00001107 if (DestType->isBooleanType()) {
1108 bool BoolResult;
1109 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1110 return false;
1111 Result.zextOrTrunc(DestWidth);
1112 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1113 Result = BoolResult;
1114 return true;
1115 }
1116
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001117 // Handle simple integer->integer casts.
Eli Friedmana6afa762008-11-13 06:09:17 +00001118 if (SubExpr->getType()->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001119 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001120 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001121
1122 Result = HandleIntToIntCast(DestType, SubExpr->getType(), Result, Info.Ctx);
Chris Lattner732b2232008-07-12 01:15:53 +00001123 return true;
1124 }
1125
1126 // FIXME: Clean this up!
1127 if (SubExpr->getType()->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001128 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001129 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001130 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001131
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001132 if (LV.getLValueBase())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001133 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001134
Anders Carlsson559e56b2008-07-08 16:49:00 +00001135 Result.extOrTrunc(DestWidth);
1136 Result = LV.getLValueOffset();
Chris Lattner732b2232008-07-12 01:15:53 +00001137 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1138 return true;
Anders Carlsson2bad1682008-07-08 14:30:00 +00001139 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001140
Chris Lattner732b2232008-07-12 01:15:53 +00001141 if (!SubExpr->getType()->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001142 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001143
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001144 APFloat F(0.0);
1145 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001146 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001147
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001148 Result = HandleFloatToIntCast(DestType, SubExpr->getType(), F, Info.Ctx);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001149 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001150}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001151
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001152//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001153// Float Evaluation
1154//===----------------------------------------------------------------------===//
1155
1156namespace {
1157class VISIBILITY_HIDDEN FloatExprEvaluator
1158 : public StmtVisitor<FloatExprEvaluator, bool> {
1159 EvalInfo &Info;
1160 APFloat &Result;
1161public:
1162 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1163 : Info(info), Result(result) {}
1164
1165 bool VisitStmt(Stmt *S) {
1166 return false;
1167 }
1168
1169 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001170 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001171
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001172 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001173 bool VisitBinaryOperator(const BinaryOperator *E);
1174 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001175 bool VisitCastExpr(CastExpr *E);
1176 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001177};
1178} // end anonymous namespace
1179
1180static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1181 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1182}
1183
Chris Lattner019f4e82008-10-06 05:28:25 +00001184bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001185 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001186 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001187 case Builtin::BI__builtin_huge_val:
1188 case Builtin::BI__builtin_huge_valf:
1189 case Builtin::BI__builtin_huge_vall:
1190 case Builtin::BI__builtin_inf:
1191 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001192 case Builtin::BI__builtin_infl: {
1193 const llvm::fltSemantics &Sem =
1194 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001195 Result = llvm::APFloat::getInf(Sem);
1196 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001197 }
Chris Lattner9e621712008-10-06 06:31:58 +00001198
1199 case Builtin::BI__builtin_nan:
1200 case Builtin::BI__builtin_nanf:
1201 case Builtin::BI__builtin_nanl:
1202 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1203 // can't constant fold it.
1204 if (const StringLiteral *S =
1205 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1206 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001207 const llvm::fltSemantics &Sem =
1208 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner9e621712008-10-06 06:31:58 +00001209 Result = llvm::APFloat::getNaN(Sem);
1210 return true;
1211 }
1212 }
1213 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001214
1215 case Builtin::BI__builtin_fabs:
1216 case Builtin::BI__builtin_fabsf:
1217 case Builtin::BI__builtin_fabsl:
1218 if (!EvaluateFloat(E->getArg(0), Result, Info))
1219 return false;
1220
1221 if (Result.isNegative())
1222 Result.changeSign();
1223 return true;
1224
1225 case Builtin::BI__builtin_copysign:
1226 case Builtin::BI__builtin_copysignf:
1227 case Builtin::BI__builtin_copysignl: {
1228 APFloat RHS(0.);
1229 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1230 !EvaluateFloat(E->getArg(1), RHS, Info))
1231 return false;
1232 Result.copySign(RHS);
1233 return true;
1234 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001235 }
1236}
1237
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001238bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopesa468d342008-11-19 17:44:31 +00001239 if (E->getOpcode() == UnaryOperator::Deref)
1240 return false;
1241
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001242 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1243 return false;
1244
1245 switch (E->getOpcode()) {
1246 default: return false;
1247 case UnaryOperator::Plus:
1248 return true;
1249 case UnaryOperator::Minus:
1250 Result.changeSign();
1251 return true;
1252 }
1253}
Chris Lattner019f4e82008-10-06 05:28:25 +00001254
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001255bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1256 // FIXME: Diagnostics? I really don't understand how the warnings
1257 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001258 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001259 if (!EvaluateFloat(E->getLHS(), Result, Info))
1260 return false;
1261 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1262 return false;
1263
1264 switch (E->getOpcode()) {
1265 default: return false;
1266 case BinaryOperator::Mul:
1267 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1268 return true;
1269 case BinaryOperator::Add:
1270 Result.add(RHS, APFloat::rmNearestTiesToEven);
1271 return true;
1272 case BinaryOperator::Sub:
1273 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1274 return true;
1275 case BinaryOperator::Div:
1276 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1277 return true;
1278 case BinaryOperator::Rem:
1279 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1280 return true;
1281 }
1282}
1283
1284bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1285 Result = E->getValue();
1286 return true;
1287}
1288
Eli Friedman4efaa272008-11-12 09:44:48 +00001289bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1290 Expr* SubExpr = E->getSubExpr();
Nate Begeman59b5da62009-01-18 03:20:47 +00001291
Eli Friedman4efaa272008-11-12 09:44:48 +00001292 if (SubExpr->getType()->isIntegralType()) {
1293 APSInt IntResult;
1294 if (!EvaluateInteger(E, IntResult, Info))
1295 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001296 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1297 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001298 return true;
1299 }
1300 if (SubExpr->getType()->isRealFloatingType()) {
1301 if (!Visit(SubExpr))
1302 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001303 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1304 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001305 return true;
1306 }
1307
1308 return false;
1309}
1310
1311bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1312 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1313 return true;
1314}
1315
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001316//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001317// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001318//===----------------------------------------------------------------------===//
1319
1320namespace {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001321class VISIBILITY_HIDDEN ComplexExprEvaluator
1322 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001323 EvalInfo &Info;
1324
1325public:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001326 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001327
1328 //===--------------------------------------------------------------------===//
1329 // Visitor Methods
1330 //===--------------------------------------------------------------------===//
1331
1332 APValue VisitStmt(Stmt *S) {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001333 return APValue();
1334 }
1335
1336 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1337
1338 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001339 Expr* SubExpr = E->getSubExpr();
1340
1341 if (SubExpr->getType()->isRealFloatingType()) {
1342 APFloat Result(0.0);
1343
1344 if (!EvaluateFloat(SubExpr, Result, Info))
1345 return APValue();
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001346
Daniel Dunbar3f279872009-01-29 01:32:56 +00001347 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001348 Result);
1349 } else {
1350 assert(SubExpr->getType()->isIntegerType() &&
1351 "Unexpected imaginary literal.");
1352
1353 llvm::APSInt Result;
1354 if (!EvaluateInteger(SubExpr, Result, Info))
1355 return APValue();
1356
1357 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1358 Zero = 0;
1359 return APValue(Zero, Result);
1360 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001361 }
1362
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001363 APValue VisitCastExpr(CastExpr *E) {
1364 Expr* SubExpr = E->getSubExpr();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001365 QualType EltType = E->getType()->getAsComplexType()->getElementType();
1366 QualType SubType = SubExpr->getType();
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001367
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001368 if (SubType->isRealFloatingType()) {
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001369 APFloat Result(0.0);
1370
1371 if (!EvaluateFloat(SubExpr, Result, Info))
1372 return APValue();
1373
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001374 // Apply float conversion if necessary.
1375 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbar8f826f02009-01-24 19:08:01 +00001376 return APValue(Result,
Daniel Dunbar3f279872009-01-29 01:32:56 +00001377 APFloat(Result.getSemantics(), APFloat::fcZero, false));
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001378 } else if (SubType->isIntegerType()) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001379 APSInt Result;
1380
1381 if (!EvaluateInteger(SubExpr, Result, Info))
1382 return APValue();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001383
1384 // Apply integer conversion if necessary.
1385 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001386 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1387 Zero = 0;
1388 return APValue(Result, Zero);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001389 } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1390 APValue Src;
1391
1392 if (!EvaluateComplex(SubExpr, Src, Info))
1393 return APValue();
1394
1395 QualType SrcType = CT->getElementType();
1396
1397 if (Src.isComplexFloat()) {
1398 if (EltType->isRealFloatingType()) {
1399 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1400 Src.getComplexFloatReal(),
1401 Info.Ctx),
1402 HandleFloatToFloatCast(EltType, SrcType,
1403 Src.getComplexFloatImag(),
1404 Info.Ctx));
1405 } else {
1406 return APValue(HandleFloatToIntCast(EltType, SrcType,
1407 Src.getComplexFloatReal(),
1408 Info.Ctx),
1409 HandleFloatToIntCast(EltType, SrcType,
1410 Src.getComplexFloatImag(),
1411 Info.Ctx));
1412 }
1413 } else {
1414 assert(Src.isComplexInt() && "Invalid evaluate result.");
1415 if (EltType->isRealFloatingType()) {
1416 return APValue(HandleIntToFloatCast(EltType, SrcType,
1417 Src.getComplexIntReal(),
1418 Info.Ctx),
1419 HandleIntToFloatCast(EltType, SrcType,
1420 Src.getComplexIntImag(),
1421 Info.Ctx));
1422 } else {
1423 return APValue(HandleIntToIntCast(EltType, SrcType,
1424 Src.getComplexIntReal(),
1425 Info.Ctx),
1426 HandleIntToIntCast(EltType, SrcType,
1427 Src.getComplexIntImag(),
1428 Info.Ctx));
1429 }
1430 }
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001431 }
1432
1433 // FIXME: Handle more casts.
1434 return APValue();
1435 }
1436
1437 APValue VisitBinaryOperator(const BinaryOperator *E);
1438
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001439};
1440} // end anonymous namespace
1441
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001442static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001443{
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001444 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1445 assert((!Result.isComplexFloat() ||
1446 (&Result.getComplexFloatReal().getSemantics() ==
1447 &Result.getComplexFloatImag().getSemantics())) &&
1448 "Invalid complex evaluation.");
1449 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001450}
1451
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001452APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001453{
1454 APValue Result, RHS;
1455
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001456 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001457 return APValue();
1458
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001459 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001460 return APValue();
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001461
Daniel Dunbar3f279872009-01-29 01:32:56 +00001462 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1463 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001464 switch (E->getOpcode()) {
1465 default: return APValue();
1466 case BinaryOperator::Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001467 if (Result.isComplexFloat()) {
1468 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1469 APFloat::rmNearestTiesToEven);
1470 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1471 APFloat::rmNearestTiesToEven);
1472 } else {
1473 Result.getComplexIntReal() += RHS.getComplexIntReal();
1474 Result.getComplexIntImag() += RHS.getComplexIntImag();
1475 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00001476 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001477 case BinaryOperator::Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001478 if (Result.isComplexFloat()) {
1479 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1480 APFloat::rmNearestTiesToEven);
1481 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1482 APFloat::rmNearestTiesToEven);
1483 } else {
1484 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1485 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1486 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00001487 break;
1488 case BinaryOperator::Mul:
1489 if (Result.isComplexFloat()) {
1490 APValue LHS = Result;
1491 APFloat &LHS_r = LHS.getComplexFloatReal();
1492 APFloat &LHS_i = LHS.getComplexFloatImag();
1493 APFloat &RHS_r = RHS.getComplexFloatReal();
1494 APFloat &RHS_i = RHS.getComplexFloatImag();
1495
1496 APFloat Tmp = LHS_r;
1497 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1498 Result.getComplexFloatReal() = Tmp;
1499 Tmp = LHS_i;
1500 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1501 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1502
1503 Tmp = LHS_r;
1504 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1505 Result.getComplexFloatImag() = Tmp;
1506 Tmp = LHS_i;
1507 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1508 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1509 } else {
1510 APValue LHS = Result;
1511 Result.getComplexIntReal() =
1512 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1513 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1514 Result.getComplexIntImag() =
1515 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1516 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1517 }
1518 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001519 }
1520
1521 return Result;
1522}
1523
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001524//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001525// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001526//===----------------------------------------------------------------------===//
1527
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001528/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner019f4e82008-10-06 05:28:25 +00001529/// any crazy technique (that has nothing to do with language standards) that
1530/// we want to. If this function returns true, it returns the folded constant
1531/// in Result.
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001532bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1533 EvalInfo Info(Ctx, Result);
Anders Carlsson54da0492008-11-30 16:38:33 +00001534
Nate Begeman59b5da62009-01-18 03:20:47 +00001535 if (getType()->isVectorType()) {
1536 if (!EvaluateVector(this, Result.Val, Info))
1537 return false;
1538 } else if (getType()->isIntegerType()) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001539 llvm::APSInt sInt(32);
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001540 if (!EvaluateInteger(this, sInt, Info))
1541 return false;
1542
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001543 Result.Val = APValue(sInt);
Mike Stumpca2f3fd2009-02-18 21:44:49 +00001544 } else if (getType()->isPointerType()
1545 || getType()->isBlockPointerType()) {
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001546 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001547 return false;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001548 } else if (getType()->isRealFloatingType()) {
1549 llvm::APFloat f(0.0);
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001550 if (!EvaluateFloat(this, f, Info))
1551 return false;
1552
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001553 Result.Val = APValue(f);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001554 } else if (getType()->isAnyComplexType()) {
1555 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001556 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001557 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00001558 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001559
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001560 return true;
1561}
1562
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001563/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001564/// folded, but discard the result.
1565bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001566 EvalResult Result;
1567 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001568}
Anders Carlsson51fe9962008-11-22 21:04:56 +00001569
1570APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001571 EvalResult EvalResult;
1572 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarf1853192009-01-15 18:32:35 +00001573 Result = Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00001574 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001575 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00001576
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001577 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00001578}