blob: 5d9fa4a1cabb73df1faa2a38022233af1369ec7c [file] [log] [blame]
Chris Lattnera42f09a2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc7436af2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Eli Friedman7888b932008-11-12 09:44:48 +000016#include "clang/AST/RecordLayout.h"
Seo Sanghyeonefddb9c2008-07-08 07:23:12 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner545f39e2009-01-29 05:15:15 +000018#include "clang/AST/ASTDiagnostic.h"
Anders Carlssonc0328012008-07-08 05:49:43 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssoncad17b52008-07-08 05:13:58 +000020#include "llvm/Support/Compiler.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000021using namespace clang;
Chris Lattnera823ccf2008-07-11 18:11:29 +000022using llvm::APSInt;
Eli Friedman2f445492008-08-22 00:06:13 +000023using llvm::APFloat;
Anders Carlssonc7436af2008-07-03 04:20:39 +000024
Chris Lattner422373c2008-07-11 22:52:41 +000025/// EvalInfo - This is a private struct used by the evaluator to capture
26/// information about a subexpression as it is folded. It retains information
27/// about the AST context, but also maintains information about the folded
28/// expression.
29///
30/// If an expression could be evaluated, it is still possible it is not a C
31/// "integer constant expression" or constant expression. If not, this struct
32/// captures information about how and why not.
33///
34/// One bit of information passed *into* the request for constant folding
35/// indicates whether the subexpression is "evaluated" or not according to C
36/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
37/// evaluate the expression regardless of what the RHS is, but C only allows
38/// certain things in certain situations.
39struct EvalInfo {
40 ASTContext &Ctx;
41
Anders Carlssondd8d41f2008-11-30 16:38:33 +000042 /// EvalResult - Contains information about the evaluation.
43 Expr::EvalResult &EvalResult;
Anders Carlsson6c1a9e22008-11-30 18:26:25 +000044
45 /// ShortCircuit - will be greater than zero if the current subexpression has
46 /// will not be evaluated because it's short-circuited (according to C rules).
47 unsigned ShortCircuit;
Chris Lattner422373c2008-07-11 22:52:41 +000048
Anders Carlssondd8d41f2008-11-30 16:38:33 +000049 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx),
Anders Carlsson6c1a9e22008-11-30 18:26:25 +000050 EvalResult(evalresult), ShortCircuit(0) {}
Chris Lattner422373c2008-07-11 22:52:41 +000051};
52
53
Eli Friedman7888b932008-11-12 09:44:48 +000054static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner422373c2008-07-11 22:52:41 +000055static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
56static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Eli Friedman2f445492008-08-22 00:06:13 +000057static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +000058static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnera823ccf2008-07-11 18:11:29 +000059
60//===----------------------------------------------------------------------===//
Eli Friedman7888b932008-11-12 09:44:48 +000061// Misc utilities
62//===----------------------------------------------------------------------===//
63
64static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
65 if (E->getType()->isIntegralType()) {
66 APSInt IntResult;
67 if (!EvaluateInteger(E, IntResult, Info))
68 return false;
69 Result = IntResult != 0;
70 return true;
71 } else if (E->getType()->isRealFloatingType()) {
72 APFloat FloatResult(0.0);
73 if (!EvaluateFloat(E, FloatResult, Info))
74 return false;
75 Result = !FloatResult.isZero();
76 return true;
77 } else if (E->getType()->isPointerType()) {
78 APValue PointerResult;
79 if (!EvaluatePointer(E, PointerResult, Info))
80 return false;
81 // FIXME: Is this accurate for all kinds of bases? If not, what would
82 // the check look like?
83 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
84 return true;
85 }
86
87 return false;
88}
89
Daniel Dunbaraffa0e32009-01-29 06:16:07 +000090static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
91 APFloat &Value, ASTContext &Ctx) {
92 unsigned DestWidth = Ctx.getIntWidth(DestType);
93 // Determine whether we are converting to unsigned or signed.
94 bool DestSigned = DestType->isSignedIntegerType();
95
96 // FIXME: Warning for overflow.
97 uint64_t Space[4];
98 bool ignored;
99 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
100 llvm::APFloat::rmTowardZero, &ignored);
101 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
102}
103
104static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
105 APFloat &Value, ASTContext &Ctx) {
106 bool ignored;
107 APFloat Result = Value;
108 Result.convert(Ctx.getFloatTypeSemantics(DestType),
109 APFloat::rmNearestTiesToEven, &ignored);
110 return Result;
111}
112
113static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
114 APSInt &Value, ASTContext &Ctx) {
115 unsigned DestWidth = Ctx.getIntWidth(DestType);
116 APSInt Result = Value;
117 // Figure out if this is a truncate, extend or noop cast.
118 // If the input is signed, do a sign extend, noop, or truncate.
119 Result.extOrTrunc(DestWidth);
120 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
121 return Result;
122}
123
124static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
125 APSInt &Value, ASTContext &Ctx) {
126
127 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
128 Result.convertFromAPInt(Value, Value.isSigned(),
129 APFloat::rmNearestTiesToEven);
130 return Result;
131}
132
Eli Friedman7888b932008-11-12 09:44:48 +0000133//===----------------------------------------------------------------------===//
134// LValue Evaluation
135//===----------------------------------------------------------------------===//
136namespace {
137class VISIBILITY_HIDDEN LValueExprEvaluator
138 : public StmtVisitor<LValueExprEvaluator, APValue> {
139 EvalInfo &Info;
140public:
141
142 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
143
144 APValue VisitStmt(Stmt *S) {
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000145#if 0
Eli Friedman7888b932008-11-12 09:44:48 +0000146 // FIXME: Remove this when we support more expressions.
147 printf("Unhandled pointer statement\n");
148 S->dump();
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000149#endif
Eli Friedman7888b932008-11-12 09:44:48 +0000150 return APValue();
151 }
152
153 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssone284ebe2008-11-24 04:41:22 +0000154 APValue VisitDeclRefExpr(DeclRefExpr *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000155 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
156 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
157 APValue VisitMemberExpr(MemberExpr *E);
158 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
Anders Carlsson027f2882008-11-16 19:01:22 +0000159 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000160};
161} // end anonymous namespace
162
163static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
164 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
165 return Result.isLValue();
166}
167
Anders Carlssone284ebe2008-11-24 04:41:22 +0000168APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
169{
170 if (!E->hasGlobalStorage())
171 return APValue();
172
173 return APValue(E, 0);
174}
175
Eli Friedman7888b932008-11-12 09:44:48 +0000176APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
177 if (E->isFileScope())
178 return APValue(E, 0);
179 return APValue();
180}
181
182APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
183 APValue result;
184 QualType Ty;
185 if (E->isArrow()) {
186 if (!EvaluatePointer(E->getBase(), result, Info))
187 return APValue();
188 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
189 } else {
190 result = Visit(E->getBase());
191 if (result.isUninit())
192 return APValue();
193 Ty = E->getBase()->getType();
194 }
195
196 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
197 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor82d44772008-12-20 23:49:58 +0000198
199 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
200 if (!FD) // FIXME: deal with other kinds of member expressions
201 return APValue();
Eli Friedman7888b932008-11-12 09:44:48 +0000202
203 // FIXME: This is linear time.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000204 unsigned i = 0;
205 for (RecordDecl::field_iterator Field = RD->field_begin(),
206 FieldEnd = RD->field_end();
207 Field != FieldEnd; (void)++Field, ++i) {
208 if (*Field == FD)
Eli Friedman7888b932008-11-12 09:44:48 +0000209 break;
210 }
211
212 result.setLValue(result.getLValueBase(),
213 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
214
215 return result;
216}
217
Anders Carlsson027f2882008-11-16 19:01:22 +0000218APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
219{
220 APValue Result;
221
222 if (!EvaluatePointer(E->getBase(), Result, Info))
223 return APValue();
224
225 APSInt Index;
226 if (!EvaluateInteger(E->getIdx(), Index, Info))
227 return APValue();
228
229 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
230
231 uint64_t Offset = Index.getSExtValue() * ElementSize;
232 Result.setLValue(Result.getLValueBase(),
233 Result.getLValueOffset() + Offset);
234 return Result;
235}
Eli Friedman7888b932008-11-12 09:44:48 +0000236
237//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000238// Pointer Evaluation
239//===----------------------------------------------------------------------===//
240
Anders Carlssoncad17b52008-07-08 05:13:58 +0000241namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000242class VISIBILITY_HIDDEN PointerExprEvaluator
243 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000244 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000245public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000246
Chris Lattner422373c2008-07-11 22:52:41 +0000247 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000248
Anders Carlsson02a34c32008-07-08 14:30:00 +0000249 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000250 return APValue();
251 }
252
253 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
254
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000255 APValue VisitBinaryOperator(const BinaryOperator *E);
256 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-11-12 09:44:48 +0000257 APValue VisitUnaryOperator(const UnaryOperator *E);
258 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
259 { return APValue(E, 0); }
Eli Friedmanf1941132009-01-25 01:21:06 +0000260 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
261 { return APValue(E, 0); }
Eli Friedman67f4ac52009-01-25 01:54:01 +0000262 APValue VisitCallExpr(CallExpr *E);
Mike Stumpd55240e2009-02-19 01:01:04 +0000263 APValue VisitBlockExpr(BlockExpr *E) { return APValue(E, 0); }
Eli Friedman7888b932008-11-12 09:44:48 +0000264 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000265};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000266} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000267
Chris Lattner422373c2008-07-11 22:52:41 +0000268static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Mike Stump5b601ff2009-02-18 21:44:49 +0000269 if (!E->getType()->isPointerType()
270 && !E->getType()->isBlockPointerType())
Chris Lattnera823ccf2008-07-11 18:11:29 +0000271 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000272 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000273 return Result.isLValue();
274}
275
276APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
277 if (E->getOpcode() != BinaryOperator::Add &&
278 E->getOpcode() != BinaryOperator::Sub)
279 return APValue();
280
281 const Expr *PExp = E->getLHS();
282 const Expr *IExp = E->getRHS();
283 if (IExp->getType()->isPointerType())
284 std::swap(PExp, IExp);
285
286 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000287 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000288 return APValue();
289
290 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000291 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000292 return APValue();
293
Eli Friedman7888b932008-11-12 09:44:48 +0000294 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
Anders Carlsson4fbb52c2009-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 Friedman7888b932008-11-12 09:44:48 +0000302
Chris Lattnera823ccf2008-07-11 18:11:29 +0000303 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000304
Chris Lattnera823ccf2008-07-11 18:11:29 +0000305 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000306 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000307 else
Eli Friedman7888b932008-11-12 09:44:48 +0000308 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
309
Chris Lattnera823ccf2008-07-11 18:11:29 +0000310 return APValue(ResultLValue.getLValueBase(), Offset);
311}
Eli Friedman7888b932008-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 Carlsson4ab88da2008-12-05 05:24:13 +0000327
Chris Lattnera823ccf2008-07-11 18:11:29 +0000328
Chris Lattnera42f09a2008-07-11 19:10:17 +0000329APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-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 Lattner422373c2008-07-11 22:52:41 +0000335 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000336 return Result;
337 return APValue();
338 }
339
Eli Friedman3e64dd72008-07-27 05:46:18 +0000340 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000341 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000342 if (EvaluateInteger(SubExpr, Result, Info)) {
343 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000344 return APValue(0, Result.getZExtValue());
345 }
346 }
Eli Friedman7888b932008-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 Lattnera823ccf2008-07-11 18:11:29 +0000357 return APValue();
358}
359
Eli Friedman67f4ac52009-01-25 01:54:01 +0000360APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000361 if (E->isBuiltinCall(Info.Ctx) ==
362 Builtin::BI__builtin___CFStringMakeConstantString)
Eli Friedman67f4ac52009-01-25 01:54:01 +0000363 return APValue(E, 0);
364 return APValue();
365}
366
Eli Friedman7888b932008-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 Lattnera823ccf2008-07-11 18:11:29 +0000379
380//===----------------------------------------------------------------------===//
Nate Begemand6d2f772009-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 Lattnera823ccf2008-07-11 18:11:29 +0000453// Integer Evaluation
454//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000455
456namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000457class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000458 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000459 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000460 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000461public:
Chris Lattner422373c2008-07-11 22:52:41 +0000462 IntExprEvaluator(EvalInfo &info, APSInt &result)
463 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000464
Anders Carlssonfa76d822008-11-30 18:14:57 +0000465 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000466 Info.EvalResult.DiagLoc = L;
467 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000468 Info.EvalResult.DiagExpr = E;
Chris Lattner82437da2008-07-12 00:14:42 +0000469 return true; // still a constant.
470 }
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000471
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000472 bool Success(const llvm::APSInt &SI, const Expr *E) {
473 Result = SI;
474 assert(Result.isSigned() == E->getType()->isSignedIntegerType() &&
475 "Invalid evaluation result.");
476 assert(Result.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
477 "Invalid evaluation result.");
478 return true;
479 }
480
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000481 bool Success(const llvm::APInt &I, const Expr *E) {
482 Result = I;
483 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000484 assert(Result.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
485 "Invalid evaluation result.");
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000486 return true;
487 }
488
489 bool Success(uint64_t Value, const Expr *E) {
490 Result = Info.Ctx.MakeIntValue(Value, E->getType());
491 return true;
492 }
493
Anders Carlssonfa76d822008-11-30 18:14:57 +0000494 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner82437da2008-07-12 00:14:42 +0000495 // If this is in an unevaluated portion of the subexpression, ignore the
496 // error.
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000497 if (Info.ShortCircuit) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000498 // If error is ignored because the value isn't evaluated, get the real
499 // type at least to prevent errors downstream.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000500 return Success(0, E);
Chris Lattner438f3b12008-11-12 07:43:42 +0000501 }
Chris Lattner82437da2008-07-12 00:14:42 +0000502
Chris Lattner438f3b12008-11-12 07:43:42 +0000503 // Take the first error.
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000504 if (Info.EvalResult.Diag == 0) {
505 Info.EvalResult.DiagLoc = L;
506 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000507 Info.EvalResult.DiagExpr = E;
Chris Lattner438f3b12008-11-12 07:43:42 +0000508 }
Chris Lattner82437da2008-07-12 00:14:42 +0000509 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000510 }
511
Anders Carlssoncad17b52008-07-08 05:13:58 +0000512 //===--------------------------------------------------------------------===//
513 // Visitor Methods
514 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000515
516 bool VisitStmt(Stmt *) {
517 assert(0 && "This should be called on integers, stmts are not integers");
518 return false;
519 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000520
Chris Lattner438f3b12008-11-12 07:43:42 +0000521 bool VisitExpr(Expr *E) {
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000522 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssoncad17b52008-07-08 05:13:58 +0000523 }
524
Chris Lattnera42f09a2008-07-11 19:10:17 +0000525 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000526
Chris Lattner15e59112008-07-12 00:38:25 +0000527 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000528 return Success(E->getValue(), E);
Chris Lattner15e59112008-07-12 00:38:25 +0000529 }
530 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000531 return Success(E->getValue(), E);
Chris Lattner15e59112008-07-12 00:38:25 +0000532 }
533 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000534 // Per gcc docs "this built-in function ignores top level
535 // qualifiers". We need to use the canonical version to properly
536 // be able to strip CRV qualifiers from the type.
537 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
538 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000539 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
540 T1.getUnqualifiedType()),
541 E);
Chris Lattner15e59112008-07-12 00:38:25 +0000542 }
543 bool VisitDeclRefExpr(const DeclRefExpr *E);
544 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000545 bool VisitBinaryOperator(const BinaryOperator *E);
546 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000547 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000548
Daniel Dunbaraffa0e32009-01-29 06:16:07 +0000549 bool VisitCastExpr(CastExpr* E);
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000550 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
551
Anders Carlsson027f2882008-11-16 19:01:22 +0000552 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000553 return Success(E->getValue(), E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000554 }
555
Anders Carlsson774f9c72008-12-21 22:39:40 +0000556 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000557 return Success(0, E);
Anders Carlsson774f9c72008-12-21 22:39:40 +0000558 }
559
Anders Carlsson027f2882008-11-16 19:01:22 +0000560 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000561 return Success(0, E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000562 }
563
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000564 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000565 return Success(E->EvaluateTrait(), E);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000566 }
567
Chris Lattner265a0892008-07-11 21:24:13 +0000568private:
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000569 unsigned GetAlignOfExpr(const Expr *E);
570 unsigned GetAlignOfType(QualType T);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000571};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000572} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000573
Chris Lattner422373c2008-07-11 22:52:41 +0000574static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000575 if (!E->getType()->isIntegralType())
576 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000577 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000578}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000579
Chris Lattner15e59112008-07-12 00:38:25 +0000580bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
581 // Enums are integer constant exprs.
582 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
Eli Friedman8b10a232008-12-08 02:21:03 +0000583 // FIXME: This is an ugly hack around the fact that enums don't set their
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000584 // signedness consistently; see PR3173.
585 APSInt SI = D->getInitVal();
586 SI.setIsUnsigned(!E->getType()->isSignedIntegerType());
587 // FIXME: This is an ugly hack around the fact that enums don't
588 // set their width (!?!) consistently; see PR3173.
589 SI.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
590 return Success(SI, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000591 }
Sebastian Redl410dd872009-02-08 15:51:17 +0000592
593 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
594 if (Info.Ctx.getLangOptions().CPlusPlus &&
595 E->getType().getCVRQualifiers() == QualType::Const) {
596 if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
597 if (const Expr *Init = D->getInit())
598 return Visit(const_cast<Expr*>(Init));
599 }
600 }
601
Chris Lattner15e59112008-07-12 00:38:25 +0000602 // Otherwise, random variable references are not constants.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000603 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000604}
605
Chris Lattner1eee9402008-10-06 06:40:35 +0000606/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
607/// as GCC.
608static int EvaluateBuiltinClassifyType(const CallExpr *E) {
609 // The following enum mimics the values returned by GCC.
610 enum gcc_type_class {
611 no_type_class = -1,
612 void_type_class, integer_type_class, char_type_class,
613 enumeral_type_class, boolean_type_class,
614 pointer_type_class, reference_type_class, offset_type_class,
615 real_type_class, complex_type_class,
616 function_type_class, method_type_class,
617 record_type_class, union_type_class,
618 array_type_class, string_type_class,
619 lang_type_class
620 };
621
622 // If no argument was supplied, default to "no_type_class". This isn't
623 // ideal, however it is what gcc does.
624 if (E->getNumArgs() == 0)
625 return no_type_class;
626
627 QualType ArgTy = E->getArg(0)->getType();
628 if (ArgTy->isVoidType())
629 return void_type_class;
630 else if (ArgTy->isEnumeralType())
631 return enumeral_type_class;
632 else if (ArgTy->isBooleanType())
633 return boolean_type_class;
634 else if (ArgTy->isCharType())
635 return string_type_class; // gcc doesn't appear to use char_type_class
636 else if (ArgTy->isIntegerType())
637 return integer_type_class;
638 else if (ArgTy->isPointerType())
639 return pointer_type_class;
640 else if (ArgTy->isReferenceType())
641 return reference_type_class;
642 else if (ArgTy->isRealType())
643 return real_type_class;
644 else if (ArgTy->isComplexType())
645 return complex_type_class;
646 else if (ArgTy->isFunctionType())
647 return function_type_class;
648 else if (ArgTy->isStructureType())
649 return record_type_class;
650 else if (ArgTy->isUnionType())
651 return union_type_class;
652 else if (ArgTy->isArrayType())
653 return array_type_class;
654 else if (ArgTy->isUnionType())
655 return union_type_class;
656 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
657 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
658 return -1;
659}
660
Chris Lattner15e59112008-07-12 00:38:25 +0000661bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000662 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner87293782008-10-06 05:28:25 +0000663 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000664 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner87293782008-10-06 05:28:25 +0000665 case Builtin::BI__builtin_classify_type:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000666 return Success(EvaluateBuiltinClassifyType(E), E);
Chris Lattner87293782008-10-06 05:28:25 +0000667
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000668 case Builtin::BI__builtin_constant_p:
Chris Lattner87293782008-10-06 05:28:25 +0000669 // __builtin_constant_p always has one operand: it returns true if that
670 // operand can be folded, false otherwise.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000671 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner87293782008-10-06 05:28:25 +0000672 }
Chris Lattner15e59112008-07-12 00:38:25 +0000673}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000674
Chris Lattnera42f09a2008-07-11 19:10:17 +0000675bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000676 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000677 if (!Visit(E->getRHS()))
678 return false;
Anders Carlsson197f6f72008-12-01 06:44:05 +0000679
680 if (!Info.ShortCircuit) {
681 // If we can't evaluate the LHS, it must be because it has
682 // side effects.
683 if (!E->getLHS()->isEvaluatable(Info.Ctx))
684 Info.EvalResult.HasSideEffects = true;
685
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000686 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson197f6f72008-12-01 06:44:05 +0000687 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000688
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000689 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000690 }
691
692 if (E->isLogicalOp()) {
693 // These need to be handled specially because the operands aren't
694 // necessarily integral
Anders Carlsson501da1f2008-11-30 16:51:17 +0000695 bool lhsResult, rhsResult;
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000696
Anders Carlsson501da1f2008-11-30 16:51:17 +0000697 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000698 // We were able to evaluate the LHS, see if we can get away with not
699 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlsson501da1f2008-11-30 16:51:17 +0000700 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
701 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000702 Info.ShortCircuit++;
Anders Carlsson501da1f2008-11-30 16:51:17 +0000703 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000704 Info.ShortCircuit--;
705
Anders Carlsson501da1f2008-11-30 16:51:17 +0000706 // FIXME: Return an extension warning saying that the RHS could not be
707 // evaluated.
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000708 // if (!rhsEvaluated) ...
709 (void) rhsEvaluated;
710
711 return Success(lhsResult, E);
Eli Friedman14cc7542008-11-13 06:09:17 +0000712 }
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000713
Anders Carlsson501da1f2008-11-30 16:51:17 +0000714 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000715 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000716 return Success(lhsResult || rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000717 else
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000718 return Success(lhsResult && rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000719 }
720 } else {
Anders Carlsson501da1f2008-11-30 16:51:17 +0000721 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000722 // We can't evaluate the LHS; however, sometimes the result
723 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlsson501da1f2008-11-30 16:51:17 +0000724 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
725 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000726 // Since we weren't able to evaluate the left hand side, it
Anders Carlsson501da1f2008-11-30 16:51:17 +0000727 // must have had side effects.
728 Info.EvalResult.HasSideEffects = true;
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000729
730 return Success(rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000731 }
732 }
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000733 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000734
Eli Friedman14cc7542008-11-13 06:09:17 +0000735 return false;
736 }
737
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000738 QualType LHSTy = E->getLHS()->getType();
739 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000740
741 if (LHSTy->isAnyComplexType()) {
742 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
743 APValue LHS, RHS;
744
745 if (!EvaluateComplex(E->getLHS(), LHS, Info))
746 return false;
747
748 if (!EvaluateComplex(E->getRHS(), RHS, Info))
749 return false;
750
751 if (LHS.isComplexFloat()) {
752 APFloat::cmpResult CR_r =
753 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
754 APFloat::cmpResult CR_i =
755 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
756
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000757 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000758 return Success((CR_r == APFloat::cmpEqual &&
759 CR_i == APFloat::cmpEqual), E);
760 else {
761 assert(E->getOpcode() == BinaryOperator::NE &&
762 "Invalid complex comparison.");
763 return Success(((CR_r == APFloat::cmpGreaterThan ||
764 CR_r == APFloat::cmpLessThan) &&
765 (CR_i == APFloat::cmpGreaterThan ||
766 CR_i == APFloat::cmpLessThan)), E);
767 }
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000768 } else {
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000769 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000770 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
771 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
772 else {
773 assert(E->getOpcode() == BinaryOperator::NE &&
774 "Invalid compex comparison.");
775 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
776 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
777 }
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000778 }
779 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000780
781 if (LHSTy->isRealFloatingType() &&
782 RHSTy->isRealFloatingType()) {
783 APFloat RHS(0.0), LHS(0.0);
784
785 if (!EvaluateFloat(E->getRHS(), RHS, Info))
786 return false;
787
788 if (!EvaluateFloat(E->getLHS(), LHS, Info))
789 return false;
790
791 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000792
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000793 switch (E->getOpcode()) {
794 default:
795 assert(0 && "Invalid binary operator!");
796 case BinaryOperator::LT:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000797 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000798 case BinaryOperator::GT:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000799 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000800 case BinaryOperator::LE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000801 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000802 case BinaryOperator::GE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000803 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
804 E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000805 case BinaryOperator::EQ:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000806 return Success(CR == APFloat::cmpEqual, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000807 case BinaryOperator::NE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000808 return Success(CR == APFloat::cmpGreaterThan
809 || CR == APFloat::cmpLessThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000810 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000811 }
812
Anders Carlsson027f2882008-11-16 19:01:22 +0000813 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000814 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson027f2882008-11-16 19:01:22 +0000815 APValue LHSValue;
816 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
817 return false;
818
819 APValue RHSValue;
820 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
821 return false;
822
823 // FIXME: Is this correct? What if only one of the operands has a base?
824 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
825 return false;
826
827 const QualType Type = E->getLHS()->getType();
828 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
829
830 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
831 D /= Info.Ctx.getTypeSize(ElementType) / 8;
832
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000833 return Success(D, E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000834 }
835 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000836 if (!LHSTy->isIntegralType() ||
837 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000838 // We can't continue from here for non-integral types, and they
839 // could potentially confuse the following operations.
840 // FIXME: Deal with EQ and friends.
841 return false;
842 }
843
Anders Carlssond1aa5812008-07-08 14:35:21 +0000844 // The LHS of a constant expr is always evaluated and needed.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000845 if (!Visit(E->getLHS())) {
Chris Lattner82437da2008-07-12 00:14:42 +0000846 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000847 }
Eli Friedman3e64dd72008-07-27 05:46:18 +0000848
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000849 llvm::APSInt RHS;
Chris Lattner82437da2008-07-12 00:14:42 +0000850 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000851 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000852
Anders Carlssond1aa5812008-07-08 14:35:21 +0000853 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000854 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000855 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000856 case BinaryOperator::Mul: return Success(Result * RHS, E);
857 case BinaryOperator::Add: return Success(Result + RHS, E);
858 case BinaryOperator::Sub: return Success(Result - RHS, E);
859 case BinaryOperator::And: return Success(Result & RHS, E);
860 case BinaryOperator::Xor: return Success(Result ^ RHS, E);
861 case BinaryOperator::Or: return Success(Result | RHS, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000862 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000863 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000864 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000865 return Success(Result / RHS, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000866 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000867 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000868 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000869 return Success(Result % RHS, E);
870 case BinaryOperator::Shl: {
Chris Lattner82437da2008-07-12 00:14:42 +0000871 // FIXME: Warn about out of range shift amounts!
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000872 unsigned SA = (unsigned) RHS.getLimitedValue(Result.getBitWidth()-1);
873 return Success(Result << SA, E);
874 }
875 case BinaryOperator::Shr: {
876 unsigned SA = (unsigned) RHS.getLimitedValue(Result.getBitWidth()-1);
877 return Success(Result >> SA, E);
878 }
Chris Lattnera42f09a2008-07-11 19:10:17 +0000879
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000880 case BinaryOperator::LT: return Success(Result < RHS, E);
881 case BinaryOperator::GT: return Success(Result > RHS, E);
882 case BinaryOperator::LE: return Success(Result <= RHS, E);
883 case BinaryOperator::GE: return Success(Result >= RHS, E);
884 case BinaryOperator::EQ: return Success(Result == RHS, E);
885 case BinaryOperator::NE: return Success(Result != RHS, E);
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000886 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000887}
888
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000889bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes308de752008-11-16 22:06:39 +0000890 bool Cond;
891 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000892 return false;
893
Nuno Lopes308de752008-11-16 22:06:39 +0000894 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000895}
896
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000897unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
Chris Lattnere3f61e12009-01-24 21:09:06 +0000898 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
899
900 // __alignof__(void) = 1 as a gcc extension.
901 if (Ty->isVoidType())
902 return 1;
903
904 // GCC extension: alignof(function) = 4.
905 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the
906 // attribute(align) directive.
907 if (Ty->isFunctionType())
908 return 4;
909
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000910 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty))
911 return GetAlignOfType(QualType(EXTQT->getBaseType(), 0));
Chris Lattnere3f61e12009-01-24 21:09:06 +0000912
913 // alignof VLA/incomplete array.
914 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
915 return GetAlignOfType(VAT->getElementType());
916
917 // sizeof (objc class)?
918 if (isa<ObjCInterfaceType>(Ty))
919 return 1; // FIXME: This probably isn't right.
920
921 // Get information about the alignment.
922 unsigned CharSize = Info.Ctx.Target.getCharWidth();
923 return Info.Ctx.getTypeAlign(Ty) / CharSize;
924}
925
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000926unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
927 E = E->IgnoreParens();
928
929 // alignof decl is always accepted, even if it doesn't make sense: we default
930 // to 1 in those cases.
931 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000932 return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000933
934 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000935 return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000936
Chris Lattnere3f61e12009-01-24 21:09:06 +0000937 return GetAlignOfType(E->getType());
938}
939
940
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000941/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
942/// expression's type.
943bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
944 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000945
Chris Lattnere3f61e12009-01-24 21:09:06 +0000946 // Handle alignof separately.
947 if (!E->isSizeOf()) {
948 if (E->isArgumentType())
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000949 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere3f61e12009-01-24 21:09:06 +0000950 else
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000951 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere3f61e12009-01-24 21:09:06 +0000952 }
953
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000954 QualType SrcTy = E->getTypeOfArgument();
955
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000956 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
957 // extension.
958 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
959 return Success(1, E);
Chris Lattner265a0892008-07-11 21:24:13 +0000960
961 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere3f61e12009-01-24 21:09:06 +0000962 if (!SrcTy->isConstantSizeType())
Chris Lattner265a0892008-07-11 21:24:13 +0000963 return false;
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000964
965 if (SrcTy->isObjCInterfaceType()) {
966 // Slightly unusual case: the size of an ObjC interface type is the
967 // size of the class. This code intentionally falls through to the normal
968 // case.
969 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
970 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
971 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
972 }
973
Chris Lattnere3f61e12009-01-24 21:09:06 +0000974 // Get information about the size.
Chris Lattner422373c2008-07-11 22:52:41 +0000975 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000976 return Success(Info.Ctx.getTypeSize(SrcTy) / CharSize, E);
Chris Lattner265a0892008-07-11 21:24:13 +0000977}
978
Chris Lattnera42f09a2008-07-11 19:10:17 +0000979bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000980 // Special case unary operators that do not need their subexpression
981 // evaluated. offsetof/sizeof/alignof are all special.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000982 if (E->isOffsetOfOp())
983 return Success(E->evaluateOffsetOf(Info.Ctx), E);
Eli Friedman14cc7542008-11-13 06:09:17 +0000984
985 if (E->getOpcode() == UnaryOperator::LNot) {
986 // LNot's operand isn't necessarily an integer, so we handle it specially.
987 bool bres;
988 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
989 return false;
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000990 return Success(!bres, E);
Eli Friedman14cc7542008-11-13 06:09:17 +0000991 }
992
Chris Lattner422373c2008-07-11 22:52:41 +0000993 // Get the operand value into 'Result'.
994 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000995 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000996
Chris Lattner400d7402008-07-11 22:15:16 +0000997 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000998 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000999 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1000 // See C99 6.6p3.
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001001 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner400d7402008-07-11 22:15:16 +00001002 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +00001003 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1004 // If so, we could clear the diagnostic ID.
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001005 return true;
Chris Lattner400d7402008-07-11 22:15:16 +00001006 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +00001007 // The result is always just the subexpr.
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001008 return true;
Chris Lattner400d7402008-07-11 22:15:16 +00001009 case UnaryOperator::Minus:
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001010 return Success(-Result, E);
Chris Lattner400d7402008-07-11 22:15:16 +00001011 case UnaryOperator::Not:
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001012 return Success(~Result, E);
Anders Carlssond1aa5812008-07-08 14:35:21 +00001013 }
Anders Carlssond1aa5812008-07-08 14:35:21 +00001014}
1015
Chris Lattnerff579ff2008-07-12 01:15:53 +00001016/// HandleCast - This is used to evaluate implicit or explicit casts where the
1017/// result type is integer.
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001018bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlssonfa76d822008-11-30 18:14:57 +00001019 Expr *SubExpr = E->getSubExpr();
1020 QualType DestType = E->getType();
1021
Eli Friedman7888b932008-11-12 09:44:48 +00001022 if (DestType->isBooleanType()) {
1023 bool BoolResult;
1024 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1025 return false;
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001026 return Success(BoolResult, E);
Eli Friedman7888b932008-11-12 09:44:48 +00001027 }
1028
Anders Carlssond1aa5812008-07-08 14:35:21 +00001029 // Handle simple integer->integer casts.
Eli Friedman14cc7542008-11-13 06:09:17 +00001030 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +00001031 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001032 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001033
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001034 return Success(HandleIntToIntCast(DestType, SubExpr->getType(),
1035 Result, Info.Ctx), E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001036 }
1037
1038 // FIXME: Clean this up!
1039 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +00001040 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +00001041 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001042 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001043
Anders Carlssond1aa5812008-07-08 14:35:21 +00001044 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +00001045 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001046
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001047 return Success(LV.getLValueOffset(), E);
Anders Carlsson02a34c32008-07-08 14:30:00 +00001048 }
Eli Friedman7888b932008-11-12 09:44:48 +00001049
Chris Lattnerff579ff2008-07-12 01:15:53 +00001050 if (!SubExpr->getType()->isRealFloatingType())
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001051 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001052
Eli Friedman2f445492008-08-22 00:06:13 +00001053 APFloat F(0.0);
1054 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001055 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001056
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001057 return Success(HandleFloatToIntCast(DestType, SubExpr->getType(),
1058 F, Info.Ctx), E);
Anders Carlssond1aa5812008-07-08 14:35:21 +00001059}
Anders Carlsson02a34c32008-07-08 14:30:00 +00001060
Chris Lattnera823ccf2008-07-11 18:11:29 +00001061//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +00001062// Float Evaluation
1063//===----------------------------------------------------------------------===//
1064
1065namespace {
1066class VISIBILITY_HIDDEN FloatExprEvaluator
1067 : public StmtVisitor<FloatExprEvaluator, bool> {
1068 EvalInfo &Info;
1069 APFloat &Result;
1070public:
1071 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1072 : Info(info), Result(result) {}
1073
1074 bool VisitStmt(Stmt *S) {
1075 return false;
1076 }
1077
1078 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +00001079 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001080
Daniel Dunbar804ead02008-10-16 03:51:50 +00001081 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001082 bool VisitBinaryOperator(const BinaryOperator *E);
1083 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +00001084 bool VisitCastExpr(CastExpr *E);
1085 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001086};
1087} // end anonymous namespace
1088
1089static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1090 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1091}
1092
Chris Lattner87293782008-10-06 05:28:25 +00001093bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +00001094 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner27cde262008-10-06 05:53:16 +00001095 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +00001096 case Builtin::BI__builtin_huge_val:
1097 case Builtin::BI__builtin_huge_valf:
1098 case Builtin::BI__builtin_huge_vall:
1099 case Builtin::BI__builtin_inf:
1100 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001101 case Builtin::BI__builtin_infl: {
1102 const llvm::fltSemantics &Sem =
1103 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +00001104 Result = llvm::APFloat::getInf(Sem);
1105 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001106 }
Chris Lattner667e1ee2008-10-06 06:31:58 +00001107
1108 case Builtin::BI__builtin_nan:
1109 case Builtin::BI__builtin_nanf:
1110 case Builtin::BI__builtin_nanl:
1111 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1112 // can't constant fold it.
1113 if (const StringLiteral *S =
1114 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1115 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001116 const llvm::fltSemantics &Sem =
1117 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +00001118 Result = llvm::APFloat::getNaN(Sem);
1119 return true;
1120 }
1121 }
1122 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +00001123
1124 case Builtin::BI__builtin_fabs:
1125 case Builtin::BI__builtin_fabsf:
1126 case Builtin::BI__builtin_fabsl:
1127 if (!EvaluateFloat(E->getArg(0), Result, Info))
1128 return false;
1129
1130 if (Result.isNegative())
1131 Result.changeSign();
1132 return true;
1133
1134 case Builtin::BI__builtin_copysign:
1135 case Builtin::BI__builtin_copysignf:
1136 case Builtin::BI__builtin_copysignl: {
1137 APFloat RHS(0.);
1138 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1139 !EvaluateFloat(E->getArg(1), RHS, Info))
1140 return false;
1141 Result.copySign(RHS);
1142 return true;
1143 }
Chris Lattner87293782008-10-06 05:28:25 +00001144 }
1145}
1146
Daniel Dunbar804ead02008-10-16 03:51:50 +00001147bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes1cea4f42008-11-19 17:44:31 +00001148 if (E->getOpcode() == UnaryOperator::Deref)
1149 return false;
1150
Daniel Dunbar804ead02008-10-16 03:51:50 +00001151 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1152 return false;
1153
1154 switch (E->getOpcode()) {
1155 default: return false;
1156 case UnaryOperator::Plus:
1157 return true;
1158 case UnaryOperator::Minus:
1159 Result.changeSign();
1160 return true;
1161 }
1162}
Chris Lattner87293782008-10-06 05:28:25 +00001163
Eli Friedman2f445492008-08-22 00:06:13 +00001164bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1165 // FIXME: Diagnostics? I really don't understand how the warnings
1166 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +00001167 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +00001168 if (!EvaluateFloat(E->getLHS(), Result, Info))
1169 return false;
1170 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1171 return false;
1172
1173 switch (E->getOpcode()) {
1174 default: return false;
1175 case BinaryOperator::Mul:
1176 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1177 return true;
1178 case BinaryOperator::Add:
1179 Result.add(RHS, APFloat::rmNearestTiesToEven);
1180 return true;
1181 case BinaryOperator::Sub:
1182 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1183 return true;
1184 case BinaryOperator::Div:
1185 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1186 return true;
1187 case BinaryOperator::Rem:
1188 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1189 return true;
1190 }
1191}
1192
1193bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1194 Result = E->getValue();
1195 return true;
1196}
1197
Eli Friedman7888b932008-11-12 09:44:48 +00001198bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1199 Expr* SubExpr = E->getSubExpr();
Nate Begemand6d2f772009-01-18 03:20:47 +00001200
Eli Friedman7888b932008-11-12 09:44:48 +00001201 if (SubExpr->getType()->isIntegralType()) {
1202 APSInt IntResult;
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001203 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman7888b932008-11-12 09:44:48 +00001204 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001205 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1206 IntResult, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001207 return true;
1208 }
1209 if (SubExpr->getType()->isRealFloatingType()) {
1210 if (!Visit(SubExpr))
1211 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001212 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1213 Result, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001214 return true;
1215 }
1216
1217 return false;
1218}
1219
1220bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1221 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1222 return true;
1223}
1224
Eli Friedman2f445492008-08-22 00:06:13 +00001225//===----------------------------------------------------------------------===//
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001226// Complex Evaluation (for float and integer)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001227//===----------------------------------------------------------------------===//
1228
1229namespace {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001230class VISIBILITY_HIDDEN ComplexExprEvaluator
1231 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001232 EvalInfo &Info;
1233
1234public:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001235 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001236
1237 //===--------------------------------------------------------------------===//
1238 // Visitor Methods
1239 //===--------------------------------------------------------------------===//
1240
1241 APValue VisitStmt(Stmt *S) {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001242 return APValue();
1243 }
1244
1245 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1246
1247 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001248 Expr* SubExpr = E->getSubExpr();
1249
1250 if (SubExpr->getType()->isRealFloatingType()) {
1251 APFloat Result(0.0);
1252
1253 if (!EvaluateFloat(SubExpr, Result, Info))
1254 return APValue();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001255
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001256 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001257 Result);
1258 } else {
1259 assert(SubExpr->getType()->isIntegerType() &&
1260 "Unexpected imaginary literal.");
1261
1262 llvm::APSInt Result;
1263 if (!EvaluateInteger(SubExpr, Result, Info))
1264 return APValue();
1265
1266 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1267 Zero = 0;
1268 return APValue(Zero, Result);
1269 }
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001270 }
1271
Anders Carlssonad2794c2008-11-16 21:51:21 +00001272 APValue VisitCastExpr(CastExpr *E) {
1273 Expr* SubExpr = E->getSubExpr();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001274 QualType EltType = E->getType()->getAsComplexType()->getElementType();
1275 QualType SubType = SubExpr->getType();
Anders Carlssonad2794c2008-11-16 21:51:21 +00001276
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001277 if (SubType->isRealFloatingType()) {
Anders Carlssonad2794c2008-11-16 21:51:21 +00001278 APFloat Result(0.0);
1279
1280 if (!EvaluateFloat(SubExpr, Result, Info))
1281 return APValue();
1282
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001283 // Apply float conversion if necessary.
1284 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbarf8abb942009-01-24 19:08:01 +00001285 return APValue(Result,
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001286 APFloat(Result.getSemantics(), APFloat::fcZero, false));
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001287 } else if (SubType->isIntegerType()) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001288 APSInt Result;
1289
1290 if (!EvaluateInteger(SubExpr, Result, Info))
1291 return APValue();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001292
1293 // Apply integer conversion if necessary.
1294 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001295 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1296 Zero = 0;
1297 return APValue(Result, Zero);
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001298 } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1299 APValue Src;
1300
1301 if (!EvaluateComplex(SubExpr, Src, Info))
1302 return APValue();
1303
1304 QualType SrcType = CT->getElementType();
1305
1306 if (Src.isComplexFloat()) {
1307 if (EltType->isRealFloatingType()) {
1308 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1309 Src.getComplexFloatReal(),
1310 Info.Ctx),
1311 HandleFloatToFloatCast(EltType, SrcType,
1312 Src.getComplexFloatImag(),
1313 Info.Ctx));
1314 } else {
1315 return APValue(HandleFloatToIntCast(EltType, SrcType,
1316 Src.getComplexFloatReal(),
1317 Info.Ctx),
1318 HandleFloatToIntCast(EltType, SrcType,
1319 Src.getComplexFloatImag(),
1320 Info.Ctx));
1321 }
1322 } else {
1323 assert(Src.isComplexInt() && "Invalid evaluate result.");
1324 if (EltType->isRealFloatingType()) {
1325 return APValue(HandleIntToFloatCast(EltType, SrcType,
1326 Src.getComplexIntReal(),
1327 Info.Ctx),
1328 HandleIntToFloatCast(EltType, SrcType,
1329 Src.getComplexIntImag(),
1330 Info.Ctx));
1331 } else {
1332 return APValue(HandleIntToIntCast(EltType, SrcType,
1333 Src.getComplexIntReal(),
1334 Info.Ctx),
1335 HandleIntToIntCast(EltType, SrcType,
1336 Src.getComplexIntImag(),
1337 Info.Ctx));
1338 }
1339 }
Anders Carlssonad2794c2008-11-16 21:51:21 +00001340 }
1341
1342 // FIXME: Handle more casts.
1343 return APValue();
1344 }
1345
1346 APValue VisitBinaryOperator(const BinaryOperator *E);
1347
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001348};
1349} // end anonymous namespace
1350
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001351static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001352{
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001353 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1354 assert((!Result.isComplexFloat() ||
1355 (&Result.getComplexFloatReal().getSemantics() ==
1356 &Result.getComplexFloatImag().getSemantics())) &&
1357 "Invalid complex evaluation.");
1358 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001359}
1360
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001361APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
Anders Carlssonad2794c2008-11-16 21:51:21 +00001362{
1363 APValue Result, RHS;
1364
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001365 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001366 return APValue();
1367
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001368 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001369 return APValue();
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001370
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001371 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1372 "Invalid operands to binary operator.");
Anders Carlssonad2794c2008-11-16 21:51:21 +00001373 switch (E->getOpcode()) {
1374 default: return APValue();
1375 case BinaryOperator::Add:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001376 if (Result.isComplexFloat()) {
1377 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1378 APFloat::rmNearestTiesToEven);
1379 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1380 APFloat::rmNearestTiesToEven);
1381 } else {
1382 Result.getComplexIntReal() += RHS.getComplexIntReal();
1383 Result.getComplexIntImag() += RHS.getComplexIntImag();
1384 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001385 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001386 case BinaryOperator::Sub:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001387 if (Result.isComplexFloat()) {
1388 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1389 APFloat::rmNearestTiesToEven);
1390 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1391 APFloat::rmNearestTiesToEven);
1392 } else {
1393 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1394 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1395 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001396 break;
1397 case BinaryOperator::Mul:
1398 if (Result.isComplexFloat()) {
1399 APValue LHS = Result;
1400 APFloat &LHS_r = LHS.getComplexFloatReal();
1401 APFloat &LHS_i = LHS.getComplexFloatImag();
1402 APFloat &RHS_r = RHS.getComplexFloatReal();
1403 APFloat &RHS_i = RHS.getComplexFloatImag();
1404
1405 APFloat Tmp = LHS_r;
1406 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1407 Result.getComplexFloatReal() = Tmp;
1408 Tmp = LHS_i;
1409 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1410 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1411
1412 Tmp = LHS_r;
1413 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1414 Result.getComplexFloatImag() = Tmp;
1415 Tmp = LHS_i;
1416 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1417 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1418 } else {
1419 APValue LHS = Result;
1420 Result.getComplexIntReal() =
1421 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1422 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1423 Result.getComplexIntImag() =
1424 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1425 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1426 }
1427 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001428 }
1429
1430 return Result;
1431}
1432
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001433//===----------------------------------------------------------------------===//
Chris Lattneref069662008-11-16 21:24:15 +00001434// Top level Expr::Evaluate method.
Chris Lattnera823ccf2008-07-11 18:11:29 +00001435//===----------------------------------------------------------------------===//
1436
Chris Lattneref069662008-11-16 21:24:15 +00001437/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner87293782008-10-06 05:28:25 +00001438/// any crazy technique (that has nothing to do with language standards) that
1439/// we want to. If this function returns true, it returns the folded constant
1440/// in Result.
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001441bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1442 EvalInfo Info(Ctx, Result);
Anders Carlssondd8d41f2008-11-30 16:38:33 +00001443
Nate Begemand6d2f772009-01-18 03:20:47 +00001444 if (getType()->isVectorType()) {
1445 if (!EvaluateVector(this, Result.Val, Info))
1446 return false;
1447 } else if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +00001448 llvm::APSInt sInt(32);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001449 if (!EvaluateInteger(this, sInt, Info))
1450 return false;
1451
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001452 Result.Val = APValue(sInt);
Mike Stump5b601ff2009-02-18 21:44:49 +00001453 } else if (getType()->isPointerType()
1454 || getType()->isBlockPointerType()) {
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001455 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001456 return false;
Eli Friedman2f445492008-08-22 00:06:13 +00001457 } else if (getType()->isRealFloatingType()) {
1458 llvm::APFloat f(0.0);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001459 if (!EvaluateFloat(this, f, Info))
1460 return false;
1461
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001462 Result.Val = APValue(f);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001463 } else if (getType()->isAnyComplexType()) {
1464 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001465 return false;
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001466 } else
Anders Carlssoncb6a2e82008-11-22 22:56:32 +00001467 return false;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001468
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001469 return true;
1470}
1471
Chris Lattneref069662008-11-16 21:24:15 +00001472/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001473/// folded, but discard the result.
1474bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson197f6f72008-12-01 06:44:05 +00001475 EvalResult Result;
1476 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001477}
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001478
1479APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson8c3de802008-12-19 20:58:05 +00001480 EvalResult EvalResult;
1481 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarddebeca2009-01-15 18:32:35 +00001482 Result = Result;
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001483 assert(Result && "Could not evaluate expression");
Anders Carlsson8c3de802008-12-19 20:58:05 +00001484 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001485
Anders Carlsson8c3de802008-12-19 20:58:05 +00001486 return EvalResult.Val.getInt();
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001487}