blob: 103bc37f4fe88fdf1e3362e675b6d10e5cd6f1c3 [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);
Daniel Dunbar56611002009-02-20 18:22:23 +000057static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Eli Friedman2f445492008-08-22 00:06:13 +000058static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +000059static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnera823ccf2008-07-11 18:11:29 +000060
61//===----------------------------------------------------------------------===//
Eli Friedman7888b932008-11-12 09:44:48 +000062// Misc utilities
63//===----------------------------------------------------------------------===//
64
65static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
66 if (E->getType()->isIntegralType()) {
67 APSInt IntResult;
68 if (!EvaluateInteger(E, IntResult, Info))
69 return false;
70 Result = IntResult != 0;
71 return true;
72 } else if (E->getType()->isRealFloatingType()) {
73 APFloat FloatResult(0.0);
74 if (!EvaluateFloat(E, FloatResult, Info))
75 return false;
76 Result = !FloatResult.isZero();
77 return true;
78 } else if (E->getType()->isPointerType()) {
79 APValue PointerResult;
80 if (!EvaluatePointer(E, PointerResult, Info))
81 return false;
82 // FIXME: Is this accurate for all kinds of bases? If not, what would
83 // the check look like?
84 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
85 return true;
86 }
87
88 return false;
89}
90
Daniel Dunbaraffa0e32009-01-29 06:16:07 +000091static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
92 APFloat &Value, ASTContext &Ctx) {
93 unsigned DestWidth = Ctx.getIntWidth(DestType);
94 // Determine whether we are converting to unsigned or signed.
95 bool DestSigned = DestType->isSignedIntegerType();
96
97 // FIXME: Warning for overflow.
98 uint64_t Space[4];
99 bool ignored;
100 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
101 llvm::APFloat::rmTowardZero, &ignored);
102 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
103}
104
105static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
106 APFloat &Value, ASTContext &Ctx) {
107 bool ignored;
108 APFloat Result = Value;
109 Result.convert(Ctx.getFloatTypeSemantics(DestType),
110 APFloat::rmNearestTiesToEven, &ignored);
111 return Result;
112}
113
114static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
115 APSInt &Value, ASTContext &Ctx) {
116 unsigned DestWidth = Ctx.getIntWidth(DestType);
117 APSInt Result = Value;
118 // Figure out if this is a truncate, extend or noop cast.
119 // If the input is signed, do a sign extend, noop, or truncate.
120 Result.extOrTrunc(DestWidth);
121 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
122 return Result;
123}
124
125static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
126 APSInt &Value, ASTContext &Ctx) {
127
128 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
129 Result.convertFromAPInt(Value, Value.isSigned(),
130 APFloat::rmNearestTiesToEven);
131 return Result;
132}
133
Eli Friedman7888b932008-11-12 09:44:48 +0000134//===----------------------------------------------------------------------===//
135// LValue Evaluation
136//===----------------------------------------------------------------------===//
137namespace {
138class VISIBILITY_HIDDEN LValueExprEvaluator
139 : public StmtVisitor<LValueExprEvaluator, APValue> {
140 EvalInfo &Info;
141public:
142
143 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
144
145 APValue VisitStmt(Stmt *S) {
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000146#if 0
Eli Friedman7888b932008-11-12 09:44:48 +0000147 // FIXME: Remove this when we support more expressions.
148 printf("Unhandled pointer statement\n");
149 S->dump();
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000150#endif
Eli Friedman7888b932008-11-12 09:44:48 +0000151 return APValue();
152 }
153
154 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssone284ebe2008-11-24 04:41:22 +0000155 APValue VisitDeclRefExpr(DeclRefExpr *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000156 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
157 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
158 APValue VisitMemberExpr(MemberExpr *E);
159 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
Anders Carlsson027f2882008-11-16 19:01:22 +0000160 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmandbd0a9b2009-02-20 01:57:15 +0000161 APValue VisitUnaryDeref(UnaryOperator *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000162};
163} // end anonymous namespace
164
165static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
166 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
167 return Result.isLValue();
168}
169
Anders Carlssone284ebe2008-11-24 04:41:22 +0000170APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
171{
172 if (!E->hasGlobalStorage())
173 return APValue();
174
175 return APValue(E, 0);
176}
177
Eli Friedman7888b932008-11-12 09:44:48 +0000178APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
179 if (E->isFileScope())
180 return APValue(E, 0);
181 return APValue();
182}
183
184APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
185 APValue result;
186 QualType Ty;
187 if (E->isArrow()) {
188 if (!EvaluatePointer(E->getBase(), result, Info))
189 return APValue();
190 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
191 } else {
192 result = Visit(E->getBase());
193 if (result.isUninit())
194 return APValue();
195 Ty = E->getBase()->getType();
196 }
197
198 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
199 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor82d44772008-12-20 23:49:58 +0000200
201 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
202 if (!FD) // FIXME: deal with other kinds of member expressions
203 return APValue();
Eli Friedman7888b932008-11-12 09:44:48 +0000204
205 // FIXME: This is linear time.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000206 unsigned i = 0;
207 for (RecordDecl::field_iterator Field = RD->field_begin(),
208 FieldEnd = RD->field_end();
209 Field != FieldEnd; (void)++Field, ++i) {
210 if (*Field == FD)
Eli Friedman7888b932008-11-12 09:44:48 +0000211 break;
212 }
213
214 result.setLValue(result.getLValueBase(),
215 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
216
217 return result;
218}
219
Anders Carlsson027f2882008-11-16 19:01:22 +0000220APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
221{
222 APValue Result;
223
224 if (!EvaluatePointer(E->getBase(), Result, Info))
225 return APValue();
226
227 APSInt Index;
228 if (!EvaluateInteger(E->getIdx(), Index, Info))
229 return APValue();
230
231 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
232
233 uint64_t Offset = Index.getSExtValue() * ElementSize;
234 Result.setLValue(Result.getLValueBase(),
235 Result.getLValueOffset() + Offset);
236 return Result;
237}
Eli Friedman7888b932008-11-12 09:44:48 +0000238
Eli Friedmandbd0a9b2009-02-20 01:57:15 +0000239APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E)
240{
241 APValue Result;
242 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
243 return APValue();
244 return Result;
245}
246
Eli Friedman7888b932008-11-12 09:44:48 +0000247//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000248// Pointer Evaluation
249//===----------------------------------------------------------------------===//
250
Anders Carlssoncad17b52008-07-08 05:13:58 +0000251namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000252class VISIBILITY_HIDDEN PointerExprEvaluator
253 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000254 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000255public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000256
Chris Lattner422373c2008-07-11 22:52:41 +0000257 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000258
Anders Carlsson02a34c32008-07-08 14:30:00 +0000259 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000260 return APValue();
261 }
262
263 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
264
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000265 APValue VisitBinaryOperator(const BinaryOperator *E);
266 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-11-12 09:44:48 +0000267 APValue VisitUnaryOperator(const UnaryOperator *E);
268 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
269 { return APValue(E, 0); }
Eli Friedmanf1941132009-01-25 01:21:06 +0000270 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
271 { return APValue(E, 0); }
Eli Friedman67f4ac52009-01-25 01:54:01 +0000272 APValue VisitCallExpr(CallExpr *E);
Mike Stumpae93d652009-02-19 22:01:56 +0000273 APValue VisitBlockExpr(BlockExpr *E) {
274 if (!E->hasBlockDeclRefExprs())
275 return APValue(E, 0);
276 return APValue();
277 }
Eli Friedman7888b932008-11-12 09:44:48 +0000278 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000279};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000280} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000281
Chris Lattner422373c2008-07-11 22:52:41 +0000282static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Mike Stump5b601ff2009-02-18 21:44:49 +0000283 if (!E->getType()->isPointerType()
284 && !E->getType()->isBlockPointerType())
Chris Lattnera823ccf2008-07-11 18:11:29 +0000285 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000286 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000287 return Result.isLValue();
288}
289
290APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
291 if (E->getOpcode() != BinaryOperator::Add &&
292 E->getOpcode() != BinaryOperator::Sub)
293 return APValue();
294
295 const Expr *PExp = E->getLHS();
296 const Expr *IExp = E->getRHS();
297 if (IExp->getType()->isPointerType())
298 std::swap(PExp, IExp);
299
300 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000301 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000302 return APValue();
303
304 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000305 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000306 return APValue();
307
Eli Friedman7888b932008-11-12 09:44:48 +0000308 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
Anders Carlsson4fbb52c2009-02-19 04:55:58 +0000309 uint64_t SizeOfPointee;
310
311 // Explicitly handle GNU void* and function pointer arithmetic extensions.
312 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
313 SizeOfPointee = 1;
314 else
315 SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
Eli Friedman7888b932008-11-12 09:44:48 +0000316
Chris Lattnera823ccf2008-07-11 18:11:29 +0000317 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000318
Chris Lattnera823ccf2008-07-11 18:11:29 +0000319 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000320 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000321 else
Eli Friedman7888b932008-11-12 09:44:48 +0000322 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
323
Chris Lattnera823ccf2008-07-11 18:11:29 +0000324 return APValue(ResultLValue.getLValueBase(), Offset);
325}
Eli Friedman7888b932008-11-12 09:44:48 +0000326
327APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
328 if (E->getOpcode() == UnaryOperator::Extension) {
329 // FIXME: Deal with warnings?
330 return Visit(E->getSubExpr());
331 }
332
333 if (E->getOpcode() == UnaryOperator::AddrOf) {
334 APValue result;
335 if (EvaluateLValue(E->getSubExpr(), result, Info))
336 return result;
337 }
338
339 return APValue();
340}
Anders Carlsson4ab88da2008-12-05 05:24:13 +0000341
Chris Lattnera823ccf2008-07-11 18:11:29 +0000342
Chris Lattnera42f09a2008-07-11 19:10:17 +0000343APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000344 const Expr* SubExpr = E->getSubExpr();
345
346 // Check for pointer->pointer cast
347 if (SubExpr->getType()->isPointerType()) {
348 APValue Result;
Chris Lattner422373c2008-07-11 22:52:41 +0000349 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000350 return Result;
351 return APValue();
352 }
353
Eli Friedman3e64dd72008-07-27 05:46:18 +0000354 if (SubExpr->getType()->isIntegralType()) {
Daniel Dunbar56611002009-02-20 18:22:23 +0000355 APValue Result;
356 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
357 return APValue();
358
359 if (Result.isInt()) {
360 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
361 return APValue(0, Result.getInt().getZExtValue());
Chris Lattnera823ccf2008-07-11 18:11:29 +0000362 }
Daniel Dunbar56611002009-02-20 18:22:23 +0000363
364 // Cast is of an lvalue, no need to change value.
365 return Result;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000366 }
Eli Friedman7888b932008-11-12 09:44:48 +0000367
368 if (SubExpr->getType()->isFunctionType() ||
369 SubExpr->getType()->isArrayType()) {
370 APValue Result;
371 if (EvaluateLValue(SubExpr, Result, Info))
372 return Result;
373 return APValue();
374 }
375
376 //assert(0 && "Unhandled cast");
Chris Lattnera823ccf2008-07-11 18:11:29 +0000377 return APValue();
378}
379
Eli Friedman67f4ac52009-01-25 01:54:01 +0000380APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000381 if (E->isBuiltinCall(Info.Ctx) ==
382 Builtin::BI__builtin___CFStringMakeConstantString)
Eli Friedman67f4ac52009-01-25 01:54:01 +0000383 return APValue(E, 0);
384 return APValue();
385}
386
Eli Friedman7888b932008-11-12 09:44:48 +0000387APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
388 bool BoolResult;
389 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
390 return APValue();
391
392 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
393
394 APValue Result;
395 if (EvaluatePointer(EvalExpr, Result, Info))
396 return Result;
397 return APValue();
398}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000399
400//===----------------------------------------------------------------------===//
Nate Begemand6d2f772009-01-18 03:20:47 +0000401// Vector Evaluation
402//===----------------------------------------------------------------------===//
403
404namespace {
405 class VISIBILITY_HIDDEN VectorExprEvaluator
406 : public StmtVisitor<VectorExprEvaluator, APValue> {
407 EvalInfo &Info;
408 public:
409
410 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
411
412 APValue VisitStmt(Stmt *S) {
413 return APValue();
414 }
415
416 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
417 APValue VisitCastExpr(const CastExpr* E);
418 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
419 APValue VisitInitListExpr(const InitListExpr *E);
420 };
421} // end anonymous namespace
422
423static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
424 if (!E->getType()->isVectorType())
425 return false;
426 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
427 return !Result.isUninit();
428}
429
430APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
431 const Expr* SE = E->getSubExpr();
432
433 // Check for vector->vector bitcast.
434 if (SE->getType()->isVectorType())
435 return this->Visit(const_cast<Expr*>(SE));
436
437 return APValue();
438}
439
440APValue
441VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
442 return this->Visit(const_cast<Expr*>(E->getInitializer()));
443}
444
445APValue
446VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
447 const VectorType *VT = E->getType()->getAsVectorType();
448 unsigned NumInits = E->getNumInits();
449
450 if (!VT || VT->getNumElements() != NumInits)
451 return APValue();
452
453 QualType EltTy = VT->getElementType();
454 llvm::SmallVector<APValue, 4> Elements;
455
456 for (unsigned i = 0; i < NumInits; i++) {
457 if (EltTy->isIntegerType()) {
458 llvm::APSInt sInt(32);
459 if (!EvaluateInteger(E->getInit(i), sInt, Info))
460 return APValue();
461 Elements.push_back(APValue(sInt));
462 } else {
463 llvm::APFloat f(0.0);
464 if (!EvaluateFloat(E->getInit(i), f, Info))
465 return APValue();
466 Elements.push_back(APValue(f));
467 }
468 }
469 return APValue(&Elements[0], Elements.size());
470}
471
472//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000473// Integer Evaluation
474//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000475
476namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000477class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000478 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000479 EvalInfo &Info;
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000480 APValue &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000481public:
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000482 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner422373c2008-07-11 22:52:41 +0000483 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000484
Anders Carlssonfa76d822008-11-30 18:14:57 +0000485 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000486 Info.EvalResult.DiagLoc = L;
487 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000488 Info.EvalResult.DiagExpr = E;
Chris Lattner82437da2008-07-12 00:14:42 +0000489 return true; // still a constant.
490 }
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000491
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000492 bool Success(const llvm::APSInt &SI, const Expr *E) {
Daniel Dunbarb5c66db2009-02-21 18:14:20 +0000493 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000494 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000495 "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000496 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000497 "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000498 Result = APValue(SI);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000499 return true;
500 }
501
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000502 bool Success(const llvm::APInt &I, const Expr *E) {
Daniel Dunbarb5c66db2009-02-21 18:14:20 +0000503 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000504 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000505 "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000506 Result = APValue(APSInt(I));
507 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000508 return true;
509 }
510
511 bool Success(uint64_t Value, const Expr *E) {
Daniel Dunbarb5c66db2009-02-21 18:14:20 +0000512 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000513 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000514 return true;
515 }
516
Anders Carlssonfa76d822008-11-30 18:14:57 +0000517 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner82437da2008-07-12 00:14:42 +0000518 // If this is in an unevaluated portion of the subexpression, ignore the
519 // error.
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000520 if (Info.ShortCircuit) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000521 // If error is ignored because the value isn't evaluated, get the real
522 // type at least to prevent errors downstream.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000523 return Success(0, E);
Chris Lattner438f3b12008-11-12 07:43:42 +0000524 }
Chris Lattner82437da2008-07-12 00:14:42 +0000525
Chris Lattner438f3b12008-11-12 07:43:42 +0000526 // Take the first error.
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000527
528 // FIXME: This is wrong if we happen to have already emitted an
529 // extension diagnostic; in that case we should report this error.
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000530 if (Info.EvalResult.Diag == 0) {
531 Info.EvalResult.DiagLoc = L;
532 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000533 Info.EvalResult.DiagExpr = E;
Chris Lattner438f3b12008-11-12 07:43:42 +0000534 }
Chris Lattner82437da2008-07-12 00:14:42 +0000535 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000536 }
537
Anders Carlssoncad17b52008-07-08 05:13:58 +0000538 //===--------------------------------------------------------------------===//
539 // Visitor Methods
540 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000541
542 bool VisitStmt(Stmt *) {
543 assert(0 && "This should be called on integers, stmts are not integers");
544 return false;
545 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000546
Chris Lattner438f3b12008-11-12 07:43:42 +0000547 bool VisitExpr(Expr *E) {
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000548 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssoncad17b52008-07-08 05:13:58 +0000549 }
550
Chris Lattnera42f09a2008-07-11 19:10:17 +0000551 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000552
Chris Lattner15e59112008-07-12 00:38:25 +0000553 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000554 return Success(E->getValue(), E);
Chris Lattner15e59112008-07-12 00:38:25 +0000555 }
556 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000557 return Success(E->getValue(), E);
Chris Lattner15e59112008-07-12 00:38:25 +0000558 }
559 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000560 // Per gcc docs "this built-in function ignores top level
561 // qualifiers". We need to use the canonical version to properly
562 // be able to strip CRV qualifiers from the type.
563 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
564 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000565 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
566 T1.getUnqualifiedType()),
567 E);
Chris Lattner15e59112008-07-12 00:38:25 +0000568 }
569 bool VisitDeclRefExpr(const DeclRefExpr *E);
570 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000571 bool VisitBinaryOperator(const BinaryOperator *E);
572 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000573 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000574
Daniel Dunbaraffa0e32009-01-29 06:16:07 +0000575 bool VisitCastExpr(CastExpr* E);
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000576 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
577
Anders Carlsson027f2882008-11-16 19:01:22 +0000578 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000579 return Success(E->getValue(), E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000580 }
581
Anders Carlsson774f9c72008-12-21 22:39:40 +0000582 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000583 return Success(0, E);
Anders Carlsson774f9c72008-12-21 22:39:40 +0000584 }
585
Anders Carlsson027f2882008-11-16 19:01:22 +0000586 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000587 return Success(0, E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000588 }
589
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000590 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000591 return Success(E->EvaluateTrait(), E);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000592 }
593
Chris Lattner265a0892008-07-11 21:24:13 +0000594private:
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000595 unsigned GetAlignOfExpr(const Expr *E);
596 unsigned GetAlignOfType(QualType T);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000597};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000598} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000599
Daniel Dunbar56611002009-02-20 18:22:23 +0000600static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000601 if (!E->getType()->isIntegralType())
602 return false;
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000603
Daniel Dunbar56611002009-02-20 18:22:23 +0000604 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
605}
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000606
Daniel Dunbar56611002009-02-20 18:22:23 +0000607static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
608 APValue Val;
609 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
610 return false;
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000611 Result = Val.getInt();
612 return true;
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000613}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000614
Chris Lattner15e59112008-07-12 00:38:25 +0000615bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
616 // Enums are integer constant exprs.
617 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
Eli Friedman8b10a232008-12-08 02:21:03 +0000618 // FIXME: This is an ugly hack around the fact that enums don't set their
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000619 // signedness consistently; see PR3173.
620 APSInt SI = D->getInitVal();
621 SI.setIsUnsigned(!E->getType()->isSignedIntegerType());
622 // FIXME: This is an ugly hack around the fact that enums don't
623 // set their width (!?!) consistently; see PR3173.
624 SI.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
625 return Success(SI, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000626 }
Sebastian Redl410dd872009-02-08 15:51:17 +0000627
628 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
629 if (Info.Ctx.getLangOptions().CPlusPlus &&
630 E->getType().getCVRQualifiers() == QualType::Const) {
631 if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
632 if (const Expr *Init = D->getInit())
633 return Visit(const_cast<Expr*>(Init));
634 }
635 }
636
Chris Lattner15e59112008-07-12 00:38:25 +0000637 // Otherwise, random variable references are not constants.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000638 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000639}
640
Chris Lattner1eee9402008-10-06 06:40:35 +0000641/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
642/// as GCC.
643static int EvaluateBuiltinClassifyType(const CallExpr *E) {
644 // The following enum mimics the values returned by GCC.
645 enum gcc_type_class {
646 no_type_class = -1,
647 void_type_class, integer_type_class, char_type_class,
648 enumeral_type_class, boolean_type_class,
649 pointer_type_class, reference_type_class, offset_type_class,
650 real_type_class, complex_type_class,
651 function_type_class, method_type_class,
652 record_type_class, union_type_class,
653 array_type_class, string_type_class,
654 lang_type_class
655 };
656
657 // If no argument was supplied, default to "no_type_class". This isn't
658 // ideal, however it is what gcc does.
659 if (E->getNumArgs() == 0)
660 return no_type_class;
661
662 QualType ArgTy = E->getArg(0)->getType();
663 if (ArgTy->isVoidType())
664 return void_type_class;
665 else if (ArgTy->isEnumeralType())
666 return enumeral_type_class;
667 else if (ArgTy->isBooleanType())
668 return boolean_type_class;
669 else if (ArgTy->isCharType())
670 return string_type_class; // gcc doesn't appear to use char_type_class
671 else if (ArgTy->isIntegerType())
672 return integer_type_class;
673 else if (ArgTy->isPointerType())
674 return pointer_type_class;
675 else if (ArgTy->isReferenceType())
676 return reference_type_class;
677 else if (ArgTy->isRealType())
678 return real_type_class;
679 else if (ArgTy->isComplexType())
680 return complex_type_class;
681 else if (ArgTy->isFunctionType())
682 return function_type_class;
683 else if (ArgTy->isStructureType())
684 return record_type_class;
685 else if (ArgTy->isUnionType())
686 return union_type_class;
687 else if (ArgTy->isArrayType())
688 return array_type_class;
689 else if (ArgTy->isUnionType())
690 return union_type_class;
691 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
692 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
693 return -1;
694}
695
Chris Lattner15e59112008-07-12 00:38:25 +0000696bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000697 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner87293782008-10-06 05:28:25 +0000698 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000699 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner87293782008-10-06 05:28:25 +0000700 case Builtin::BI__builtin_classify_type:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000701 return Success(EvaluateBuiltinClassifyType(E), E);
Chris Lattner87293782008-10-06 05:28:25 +0000702
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000703 case Builtin::BI__builtin_constant_p:
Chris Lattner87293782008-10-06 05:28:25 +0000704 // __builtin_constant_p always has one operand: it returns true if that
705 // operand can be folded, false otherwise.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000706 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner87293782008-10-06 05:28:25 +0000707 }
Chris Lattner15e59112008-07-12 00:38:25 +0000708}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000709
Chris Lattnera42f09a2008-07-11 19:10:17 +0000710bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000711 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000712 if (!Visit(E->getRHS()))
713 return false;
Anders Carlsson197f6f72008-12-01 06:44:05 +0000714
715 if (!Info.ShortCircuit) {
716 // If we can't evaluate the LHS, it must be because it has
717 // side effects.
718 if (!E->getLHS()->isEvaluatable(Info.Ctx))
719 Info.EvalResult.HasSideEffects = true;
720
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000721 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson197f6f72008-12-01 06:44:05 +0000722 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000723
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000724 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000725 }
726
727 if (E->isLogicalOp()) {
728 // These need to be handled specially because the operands aren't
729 // necessarily integral
Anders Carlsson501da1f2008-11-30 16:51:17 +0000730 bool lhsResult, rhsResult;
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000731
Anders Carlsson501da1f2008-11-30 16:51:17 +0000732 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000733 // We were able to evaluate the LHS, see if we can get away with not
734 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlsson501da1f2008-11-30 16:51:17 +0000735 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
736 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000737 Info.ShortCircuit++;
Anders Carlsson501da1f2008-11-30 16:51:17 +0000738 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000739 Info.ShortCircuit--;
740
Anders Carlsson501da1f2008-11-30 16:51:17 +0000741 // FIXME: Return an extension warning saying that the RHS could not be
742 // evaluated.
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000743 // if (!rhsEvaluated) ...
744 (void) rhsEvaluated;
745
746 return Success(lhsResult, E);
Eli Friedman14cc7542008-11-13 06:09:17 +0000747 }
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000748
Anders Carlsson501da1f2008-11-30 16:51:17 +0000749 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000750 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000751 return Success(lhsResult || rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000752 else
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000753 return Success(lhsResult && rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000754 }
755 } else {
Anders Carlsson501da1f2008-11-30 16:51:17 +0000756 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000757 // We can't evaluate the LHS; however, sometimes the result
758 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlsson501da1f2008-11-30 16:51:17 +0000759 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
760 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000761 // Since we weren't able to evaluate the left hand side, it
Anders Carlsson501da1f2008-11-30 16:51:17 +0000762 // must have had side effects.
763 Info.EvalResult.HasSideEffects = true;
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000764
765 return Success(rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000766 }
767 }
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000768 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000769
Eli Friedman14cc7542008-11-13 06:09:17 +0000770 return false;
771 }
772
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000773 QualType LHSTy = E->getLHS()->getType();
774 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000775
776 if (LHSTy->isAnyComplexType()) {
777 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
778 APValue LHS, RHS;
779
780 if (!EvaluateComplex(E->getLHS(), LHS, Info))
781 return false;
782
783 if (!EvaluateComplex(E->getRHS(), RHS, Info))
784 return false;
785
786 if (LHS.isComplexFloat()) {
787 APFloat::cmpResult CR_r =
788 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
789 APFloat::cmpResult CR_i =
790 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
791
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000792 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000793 return Success((CR_r == APFloat::cmpEqual &&
794 CR_i == APFloat::cmpEqual), E);
795 else {
796 assert(E->getOpcode() == BinaryOperator::NE &&
797 "Invalid complex comparison.");
798 return Success(((CR_r == APFloat::cmpGreaterThan ||
799 CR_r == APFloat::cmpLessThan) &&
800 (CR_i == APFloat::cmpGreaterThan ||
801 CR_i == APFloat::cmpLessThan)), E);
802 }
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000803 } else {
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000804 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000805 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
806 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
807 else {
808 assert(E->getOpcode() == BinaryOperator::NE &&
809 "Invalid compex comparison.");
810 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
811 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
812 }
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000813 }
814 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000815
816 if (LHSTy->isRealFloatingType() &&
817 RHSTy->isRealFloatingType()) {
818 APFloat RHS(0.0), LHS(0.0);
819
820 if (!EvaluateFloat(E->getRHS(), RHS, Info))
821 return false;
822
823 if (!EvaluateFloat(E->getLHS(), LHS, Info))
824 return false;
825
826 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000827
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000828 switch (E->getOpcode()) {
829 default:
830 assert(0 && "Invalid binary operator!");
831 case BinaryOperator::LT:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000832 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000833 case BinaryOperator::GT:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000834 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000835 case BinaryOperator::LE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000836 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000837 case BinaryOperator::GE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000838 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
839 E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000840 case BinaryOperator::EQ:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000841 return Success(CR == APFloat::cmpEqual, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000842 case BinaryOperator::NE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000843 return Success(CR == APFloat::cmpGreaterThan
844 || CR == APFloat::cmpLessThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000845 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000846 }
847
Anders Carlsson027f2882008-11-16 19:01:22 +0000848 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000849 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson027f2882008-11-16 19:01:22 +0000850 APValue LHSValue;
851 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
852 return false;
853
854 APValue RHSValue;
855 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
856 return false;
857
858 // FIXME: Is this correct? What if only one of the operands has a base?
859 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
860 return false;
861
862 const QualType Type = E->getLHS()->getType();
863 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
864
865 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
866 D /= Info.Ctx.getTypeSize(ElementType) / 8;
867
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000868 return Success(D, E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000869 }
870 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000871 if (!LHSTy->isIntegralType() ||
872 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000873 // We can't continue from here for non-integral types, and they
874 // could potentially confuse the following operations.
875 // FIXME: Deal with EQ and friends.
876 return false;
877 }
878
Anders Carlssond1aa5812008-07-08 14:35:21 +0000879 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000880 if (!Visit(E->getLHS()))
Chris Lattner82437da2008-07-12 00:14:42 +0000881 return false; // error in subexpression.
Eli Friedman3e64dd72008-07-27 05:46:18 +0000882
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000883 // Only support arithmetic on integers for now.
884 if (!Result.isInt())
885 return false;
886
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000887 llvm::APSInt RHS;
Chris Lattner82437da2008-07-12 00:14:42 +0000888 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000889 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000890
Anders Carlssond1aa5812008-07-08 14:35:21 +0000891 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000892 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000893 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000894 case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
895 case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
896 case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
897 case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
898 case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
899 case BinaryOperator::Or: return Success(Result.getInt() | RHS, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000900 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000901 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000902 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000903 return Success(Result.getInt() / RHS, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000904 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000905 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000906 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000907 return Success(Result.getInt() % RHS, E);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000908 case BinaryOperator::Shl: {
Chris Lattner82437da2008-07-12 00:14:42 +0000909 // FIXME: Warn about out of range shift amounts!
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000910 unsigned SA =
911 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
912 return Success(Result.getInt() << SA, E);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000913 }
914 case BinaryOperator::Shr: {
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000915 unsigned SA =
916 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
917 return Success(Result.getInt() >> SA, E);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000918 }
Chris Lattnera42f09a2008-07-11 19:10:17 +0000919
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000920 case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
921 case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
922 case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
923 case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
924 case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
925 case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000926 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000927}
928
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000929bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes308de752008-11-16 22:06:39 +0000930 bool Cond;
931 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000932 return false;
933
Nuno Lopes308de752008-11-16 22:06:39 +0000934 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000935}
936
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000937unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
Chris Lattnere3f61e12009-01-24 21:09:06 +0000938 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
939
940 // __alignof__(void) = 1 as a gcc extension.
941 if (Ty->isVoidType())
942 return 1;
943
944 // GCC extension: alignof(function) = 4.
945 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the
946 // attribute(align) directive.
947 if (Ty->isFunctionType())
948 return 4;
949
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000950 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty))
951 return GetAlignOfType(QualType(EXTQT->getBaseType(), 0));
Chris Lattnere3f61e12009-01-24 21:09:06 +0000952
953 // alignof VLA/incomplete array.
954 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
955 return GetAlignOfType(VAT->getElementType());
956
957 // sizeof (objc class)?
958 if (isa<ObjCInterfaceType>(Ty))
959 return 1; // FIXME: This probably isn't right.
960
961 // Get information about the alignment.
962 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Eli Friedmanb1c0b542009-02-22 03:31:23 +0000963 return Info.Ctx.getPreferredTypeAlign(Ty) / CharSize;
Chris Lattnere3f61e12009-01-24 21:09:06 +0000964}
965
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000966unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
967 E = E->IgnoreParens();
968
969 // alignof decl is always accepted, even if it doesn't make sense: we default
970 // to 1 in those cases.
971 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000972 return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000973
974 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000975 return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000976
Chris Lattnere3f61e12009-01-24 21:09:06 +0000977 return GetAlignOfType(E->getType());
978}
979
980
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000981/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
982/// expression's type.
983bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
984 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000985
Chris Lattnere3f61e12009-01-24 21:09:06 +0000986 // Handle alignof separately.
987 if (!E->isSizeOf()) {
988 if (E->isArgumentType())
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000989 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere3f61e12009-01-24 21:09:06 +0000990 else
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000991 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere3f61e12009-01-24 21:09:06 +0000992 }
993
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000994 QualType SrcTy = E->getTypeOfArgument();
995
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000996 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
997 // extension.
998 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
999 return Success(1, E);
Chris Lattner265a0892008-07-11 21:24:13 +00001000
1001 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere3f61e12009-01-24 21:09:06 +00001002 if (!SrcTy->isConstantSizeType())
Chris Lattner265a0892008-07-11 21:24:13 +00001003 return false;
Eli Friedman5a2c38f2009-01-24 22:19:05 +00001004
1005 if (SrcTy->isObjCInterfaceType()) {
1006 // Slightly unusual case: the size of an ObjC interface type is the
1007 // size of the class. This code intentionally falls through to the normal
1008 // case.
1009 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
1010 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
1011 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
1012 }
1013
Chris Lattnere3f61e12009-01-24 21:09:06 +00001014 // Get information about the size.
Chris Lattner422373c2008-07-11 22:52:41 +00001015 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001016 return Success(Info.Ctx.getTypeSize(SrcTy) / CharSize, E);
Chris Lattner265a0892008-07-11 21:24:13 +00001017}
1018
Chris Lattnera42f09a2008-07-11 19:10:17 +00001019bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +00001020 // Special case unary operators that do not need their subexpression
1021 // evaluated. offsetof/sizeof/alignof are all special.
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001022 if (E->isOffsetOfOp())
1023 return Success(E->evaluateOffsetOf(Info.Ctx), E);
Eli Friedman14cc7542008-11-13 06:09:17 +00001024
1025 if (E->getOpcode() == UnaryOperator::LNot) {
1026 // LNot's operand isn't necessarily an integer, so we handle it specially.
1027 bool bres;
1028 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1029 return false;
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001030 return Success(!bres, E);
Eli Friedman14cc7542008-11-13 06:09:17 +00001031 }
1032
Daniel Dunbarb5c66db2009-02-21 18:14:20 +00001033 // Only handle integral operations...
1034 if (!E->getSubExpr()->getType()->isIntegralType())
1035 return false;
1036
Chris Lattner422373c2008-07-11 22:52:41 +00001037 // Get the operand value into 'Result'.
1038 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +00001039 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001040
Chris Lattner400d7402008-07-11 22:15:16 +00001041 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +00001042 default:
Chris Lattner400d7402008-07-11 22:15:16 +00001043 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1044 // See C99 6.6p3.
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001045 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner400d7402008-07-11 22:15:16 +00001046 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +00001047 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1048 // If so, we could clear the diagnostic ID.
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001049 return true;
Chris Lattner400d7402008-07-11 22:15:16 +00001050 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +00001051 // The result is always just the subexpr.
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001052 return true;
Chris Lattner400d7402008-07-11 22:15:16 +00001053 case UnaryOperator::Minus:
Daniel Dunbarf2dc6752009-02-19 20:17:33 +00001054 if (!Result.isInt()) return false;
1055 return Success(-Result.getInt(), E);
Chris Lattner400d7402008-07-11 22:15:16 +00001056 case UnaryOperator::Not:
Daniel Dunbarf2dc6752009-02-19 20:17:33 +00001057 if (!Result.isInt()) return false;
1058 return Success(~Result.getInt(), E);
Anders Carlssond1aa5812008-07-08 14:35:21 +00001059 }
Anders Carlssond1aa5812008-07-08 14:35:21 +00001060}
1061
Chris Lattnerff579ff2008-07-12 01:15:53 +00001062/// HandleCast - This is used to evaluate implicit or explicit casts where the
1063/// result type is integer.
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001064bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlssonfa76d822008-11-30 18:14:57 +00001065 Expr *SubExpr = E->getSubExpr();
1066 QualType DestType = E->getType();
Daniel Dunbar6dda4ba2009-02-19 22:16:29 +00001067 QualType SrcType = SubExpr->getType();
Anders Carlssonfa76d822008-11-30 18:14:57 +00001068
Eli Friedman7888b932008-11-12 09:44:48 +00001069 if (DestType->isBooleanType()) {
1070 bool BoolResult;
1071 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1072 return false;
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001073 return Success(BoolResult, E);
Eli Friedman7888b932008-11-12 09:44:48 +00001074 }
1075
Anders Carlssond1aa5812008-07-08 14:35:21 +00001076 // Handle simple integer->integer casts.
Daniel Dunbar6dda4ba2009-02-19 22:16:29 +00001077 if (SrcType->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +00001078 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001079 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001080
Eli Friedman0366a812009-02-20 01:15:07 +00001081 if (!Result.isInt()) {
1082 // Only allow casts of lvalues if they are lossless.
1083 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1084 }
Daniel Dunbarf2dc6752009-02-19 20:17:33 +00001085
Daniel Dunbarc9967f92009-02-19 22:24:01 +00001086 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarf2dc6752009-02-19 20:17:33 +00001087 Result.getInt(), Info.Ctx), E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001088 }
1089
1090 // FIXME: Clean this up!
Daniel Dunbar6dda4ba2009-02-19 22:16:29 +00001091 if (SrcType->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +00001092 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +00001093 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001094 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001095
Daniel Dunbarc9967f92009-02-19 22:24:01 +00001096 if (LV.getLValueBase()) {
1097 // Only allow based lvalue casts if they are lossless.
1098 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1099 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001100
Daniel Dunbarc9967f92009-02-19 22:24:01 +00001101 Result = LV;
1102 return true;
1103 }
1104
1105 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset(), SrcType);
1106 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson02a34c32008-07-08 14:30:00 +00001107 }
Eli Friedman7888b932008-11-12 09:44:48 +00001108
Eli Friedman0366a812009-02-20 01:15:07 +00001109 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1110 // This handles double-conversion cases, where there's both
1111 // an l-value promotion and an implicit conversion to int.
1112 APValue LV;
1113 if (!EvaluateLValue(SubExpr, LV, Info))
1114 return false;
1115
1116 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1117 return false;
1118
1119 Result = LV;
1120 return true;
1121 }
1122
Daniel Dunbar6dda4ba2009-02-19 22:16:29 +00001123 if (!SrcType->isRealFloatingType())
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001124 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001125
Eli Friedman2f445492008-08-22 00:06:13 +00001126 APFloat F(0.0);
1127 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001128 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001129
Daniel Dunbar6dda4ba2009-02-19 22:16:29 +00001130 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssond1aa5812008-07-08 14:35:21 +00001131}
Anders Carlsson02a34c32008-07-08 14:30:00 +00001132
Chris Lattnera823ccf2008-07-11 18:11:29 +00001133//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +00001134// Float Evaluation
1135//===----------------------------------------------------------------------===//
1136
1137namespace {
1138class VISIBILITY_HIDDEN FloatExprEvaluator
1139 : public StmtVisitor<FloatExprEvaluator, bool> {
1140 EvalInfo &Info;
1141 APFloat &Result;
1142public:
1143 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1144 : Info(info), Result(result) {}
1145
1146 bool VisitStmt(Stmt *S) {
1147 return false;
1148 }
1149
1150 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +00001151 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001152
Daniel Dunbar804ead02008-10-16 03:51:50 +00001153 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001154 bool VisitBinaryOperator(const BinaryOperator *E);
1155 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +00001156 bool VisitCastExpr(CastExpr *E);
1157 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001158};
1159} // end anonymous namespace
1160
1161static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1162 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1163}
1164
Chris Lattner87293782008-10-06 05:28:25 +00001165bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +00001166 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner27cde262008-10-06 05:53:16 +00001167 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +00001168 case Builtin::BI__builtin_huge_val:
1169 case Builtin::BI__builtin_huge_valf:
1170 case Builtin::BI__builtin_huge_vall:
1171 case Builtin::BI__builtin_inf:
1172 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001173 case Builtin::BI__builtin_infl: {
1174 const llvm::fltSemantics &Sem =
1175 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +00001176 Result = llvm::APFloat::getInf(Sem);
1177 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001178 }
Chris Lattner667e1ee2008-10-06 06:31:58 +00001179
1180 case Builtin::BI__builtin_nan:
1181 case Builtin::BI__builtin_nanf:
1182 case Builtin::BI__builtin_nanl:
1183 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1184 // can't constant fold it.
1185 if (const StringLiteral *S =
1186 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1187 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001188 const llvm::fltSemantics &Sem =
1189 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +00001190 Result = llvm::APFloat::getNaN(Sem);
1191 return true;
1192 }
1193 }
1194 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +00001195
1196 case Builtin::BI__builtin_fabs:
1197 case Builtin::BI__builtin_fabsf:
1198 case Builtin::BI__builtin_fabsl:
1199 if (!EvaluateFloat(E->getArg(0), Result, Info))
1200 return false;
1201
1202 if (Result.isNegative())
1203 Result.changeSign();
1204 return true;
1205
1206 case Builtin::BI__builtin_copysign:
1207 case Builtin::BI__builtin_copysignf:
1208 case Builtin::BI__builtin_copysignl: {
1209 APFloat RHS(0.);
1210 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1211 !EvaluateFloat(E->getArg(1), RHS, Info))
1212 return false;
1213 Result.copySign(RHS);
1214 return true;
1215 }
Chris Lattner87293782008-10-06 05:28:25 +00001216 }
1217}
1218
Daniel Dunbar804ead02008-10-16 03:51:50 +00001219bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes1cea4f42008-11-19 17:44:31 +00001220 if (E->getOpcode() == UnaryOperator::Deref)
1221 return false;
1222
Daniel Dunbar804ead02008-10-16 03:51:50 +00001223 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1224 return false;
1225
1226 switch (E->getOpcode()) {
1227 default: return false;
1228 case UnaryOperator::Plus:
1229 return true;
1230 case UnaryOperator::Minus:
1231 Result.changeSign();
1232 return true;
1233 }
1234}
Chris Lattner87293782008-10-06 05:28:25 +00001235
Eli Friedman2f445492008-08-22 00:06:13 +00001236bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1237 // FIXME: Diagnostics? I really don't understand how the warnings
1238 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +00001239 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +00001240 if (!EvaluateFloat(E->getLHS(), Result, Info))
1241 return false;
1242 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1243 return false;
1244
1245 switch (E->getOpcode()) {
1246 default: return false;
1247 case BinaryOperator::Mul:
1248 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1249 return true;
1250 case BinaryOperator::Add:
1251 Result.add(RHS, APFloat::rmNearestTiesToEven);
1252 return true;
1253 case BinaryOperator::Sub:
1254 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1255 return true;
1256 case BinaryOperator::Div:
1257 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1258 return true;
1259 case BinaryOperator::Rem:
1260 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1261 return true;
1262 }
1263}
1264
1265bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1266 Result = E->getValue();
1267 return true;
1268}
1269
Eli Friedman7888b932008-11-12 09:44:48 +00001270bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1271 Expr* SubExpr = E->getSubExpr();
Nate Begemand6d2f772009-01-18 03:20:47 +00001272
Eli Friedman7888b932008-11-12 09:44:48 +00001273 if (SubExpr->getType()->isIntegralType()) {
1274 APSInt IntResult;
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001275 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman7888b932008-11-12 09:44:48 +00001276 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001277 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1278 IntResult, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001279 return true;
1280 }
1281 if (SubExpr->getType()->isRealFloatingType()) {
1282 if (!Visit(SubExpr))
1283 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001284 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1285 Result, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001286 return true;
1287 }
1288
1289 return false;
1290}
1291
1292bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1293 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1294 return true;
1295}
1296
Eli Friedman2f445492008-08-22 00:06:13 +00001297//===----------------------------------------------------------------------===//
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001298// Complex Evaluation (for float and integer)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001299//===----------------------------------------------------------------------===//
1300
1301namespace {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001302class VISIBILITY_HIDDEN ComplexExprEvaluator
1303 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001304 EvalInfo &Info;
1305
1306public:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001307 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001308
1309 //===--------------------------------------------------------------------===//
1310 // Visitor Methods
1311 //===--------------------------------------------------------------------===//
1312
1313 APValue VisitStmt(Stmt *S) {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001314 return APValue();
1315 }
1316
1317 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1318
1319 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001320 Expr* SubExpr = E->getSubExpr();
1321
1322 if (SubExpr->getType()->isRealFloatingType()) {
1323 APFloat Result(0.0);
1324
1325 if (!EvaluateFloat(SubExpr, Result, Info))
1326 return APValue();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001327
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001328 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001329 Result);
1330 } else {
1331 assert(SubExpr->getType()->isIntegerType() &&
1332 "Unexpected imaginary literal.");
1333
1334 llvm::APSInt Result;
1335 if (!EvaluateInteger(SubExpr, Result, Info))
1336 return APValue();
1337
1338 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1339 Zero = 0;
1340 return APValue(Zero, Result);
1341 }
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001342 }
1343
Anders Carlssonad2794c2008-11-16 21:51:21 +00001344 APValue VisitCastExpr(CastExpr *E) {
1345 Expr* SubExpr = E->getSubExpr();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001346 QualType EltType = E->getType()->getAsComplexType()->getElementType();
1347 QualType SubType = SubExpr->getType();
Anders Carlssonad2794c2008-11-16 21:51:21 +00001348
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001349 if (SubType->isRealFloatingType()) {
Anders Carlssonad2794c2008-11-16 21:51:21 +00001350 APFloat Result(0.0);
1351
1352 if (!EvaluateFloat(SubExpr, Result, Info))
1353 return APValue();
1354
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001355 // Apply float conversion if necessary.
1356 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbarf8abb942009-01-24 19:08:01 +00001357 return APValue(Result,
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001358 APFloat(Result.getSemantics(), APFloat::fcZero, false));
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001359 } else if (SubType->isIntegerType()) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001360 APSInt Result;
1361
1362 if (!EvaluateInteger(SubExpr, Result, Info))
1363 return APValue();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001364
1365 // Apply integer conversion if necessary.
1366 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001367 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1368 Zero = 0;
1369 return APValue(Result, Zero);
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001370 } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1371 APValue Src;
1372
1373 if (!EvaluateComplex(SubExpr, Src, Info))
1374 return APValue();
1375
1376 QualType SrcType = CT->getElementType();
1377
1378 if (Src.isComplexFloat()) {
1379 if (EltType->isRealFloatingType()) {
1380 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1381 Src.getComplexFloatReal(),
1382 Info.Ctx),
1383 HandleFloatToFloatCast(EltType, SrcType,
1384 Src.getComplexFloatImag(),
1385 Info.Ctx));
1386 } else {
1387 return APValue(HandleFloatToIntCast(EltType, SrcType,
1388 Src.getComplexFloatReal(),
1389 Info.Ctx),
1390 HandleFloatToIntCast(EltType, SrcType,
1391 Src.getComplexFloatImag(),
1392 Info.Ctx));
1393 }
1394 } else {
1395 assert(Src.isComplexInt() && "Invalid evaluate result.");
1396 if (EltType->isRealFloatingType()) {
1397 return APValue(HandleIntToFloatCast(EltType, SrcType,
1398 Src.getComplexIntReal(),
1399 Info.Ctx),
1400 HandleIntToFloatCast(EltType, SrcType,
1401 Src.getComplexIntImag(),
1402 Info.Ctx));
1403 } else {
1404 return APValue(HandleIntToIntCast(EltType, SrcType,
1405 Src.getComplexIntReal(),
1406 Info.Ctx),
1407 HandleIntToIntCast(EltType, SrcType,
1408 Src.getComplexIntImag(),
1409 Info.Ctx));
1410 }
1411 }
Anders Carlssonad2794c2008-11-16 21:51:21 +00001412 }
1413
1414 // FIXME: Handle more casts.
1415 return APValue();
1416 }
1417
1418 APValue VisitBinaryOperator(const BinaryOperator *E);
1419
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001420};
1421} // end anonymous namespace
1422
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001423static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001424{
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001425 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1426 assert((!Result.isComplexFloat() ||
1427 (&Result.getComplexFloatReal().getSemantics() ==
1428 &Result.getComplexFloatImag().getSemantics())) &&
1429 "Invalid complex evaluation.");
1430 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001431}
1432
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001433APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
Anders Carlssonad2794c2008-11-16 21:51:21 +00001434{
1435 APValue Result, RHS;
1436
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001437 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001438 return APValue();
1439
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001440 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001441 return APValue();
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001442
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001443 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1444 "Invalid operands to binary operator.");
Anders Carlssonad2794c2008-11-16 21:51:21 +00001445 switch (E->getOpcode()) {
1446 default: return APValue();
1447 case BinaryOperator::Add:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001448 if (Result.isComplexFloat()) {
1449 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1450 APFloat::rmNearestTiesToEven);
1451 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1452 APFloat::rmNearestTiesToEven);
1453 } else {
1454 Result.getComplexIntReal() += RHS.getComplexIntReal();
1455 Result.getComplexIntImag() += RHS.getComplexIntImag();
1456 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001457 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001458 case BinaryOperator::Sub:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001459 if (Result.isComplexFloat()) {
1460 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1461 APFloat::rmNearestTiesToEven);
1462 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1463 APFloat::rmNearestTiesToEven);
1464 } else {
1465 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1466 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1467 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001468 break;
1469 case BinaryOperator::Mul:
1470 if (Result.isComplexFloat()) {
1471 APValue LHS = Result;
1472 APFloat &LHS_r = LHS.getComplexFloatReal();
1473 APFloat &LHS_i = LHS.getComplexFloatImag();
1474 APFloat &RHS_r = RHS.getComplexFloatReal();
1475 APFloat &RHS_i = RHS.getComplexFloatImag();
1476
1477 APFloat Tmp = LHS_r;
1478 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1479 Result.getComplexFloatReal() = Tmp;
1480 Tmp = LHS_i;
1481 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1482 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1483
1484 Tmp = LHS_r;
1485 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1486 Result.getComplexFloatImag() = Tmp;
1487 Tmp = LHS_i;
1488 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1489 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1490 } else {
1491 APValue LHS = Result;
1492 Result.getComplexIntReal() =
1493 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1494 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1495 Result.getComplexIntImag() =
1496 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1497 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1498 }
1499 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001500 }
1501
1502 return Result;
1503}
1504
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001505//===----------------------------------------------------------------------===//
Chris Lattneref069662008-11-16 21:24:15 +00001506// Top level Expr::Evaluate method.
Chris Lattnera823ccf2008-07-11 18:11:29 +00001507//===----------------------------------------------------------------------===//
1508
Chris Lattneref069662008-11-16 21:24:15 +00001509/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner87293782008-10-06 05:28:25 +00001510/// any crazy technique (that has nothing to do with language standards) that
1511/// we want to. If this function returns true, it returns the folded constant
1512/// in Result.
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001513bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1514 EvalInfo Info(Ctx, Result);
Anders Carlssondd8d41f2008-11-30 16:38:33 +00001515
Nate Begemand6d2f772009-01-18 03:20:47 +00001516 if (getType()->isVectorType()) {
1517 if (!EvaluateVector(this, Result.Val, Info))
1518 return false;
1519 } else if (getType()->isIntegerType()) {
Daniel Dunbarf2dc6752009-02-19 20:17:33 +00001520 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001521 return false;
Mike Stump5b601ff2009-02-18 21:44:49 +00001522 } else if (getType()->isPointerType()
1523 || getType()->isBlockPointerType()) {
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001524 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001525 return false;
Eli Friedman2f445492008-08-22 00:06:13 +00001526 } else if (getType()->isRealFloatingType()) {
1527 llvm::APFloat f(0.0);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001528 if (!EvaluateFloat(this, f, Info))
1529 return false;
1530
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001531 Result.Val = APValue(f);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001532 } else if (getType()->isAnyComplexType()) {
1533 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001534 return false;
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001535 } else
Anders Carlssoncb6a2e82008-11-22 22:56:32 +00001536 return false;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001537
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001538 return true;
1539}
1540
Chris Lattneref069662008-11-16 21:24:15 +00001541/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001542/// folded, but discard the result.
1543bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson197f6f72008-12-01 06:44:05 +00001544 EvalResult Result;
1545 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001546}
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001547
1548APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson8c3de802008-12-19 20:58:05 +00001549 EvalResult EvalResult;
1550 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarddebeca2009-01-15 18:32:35 +00001551 Result = Result;
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001552 assert(Result && "Could not evaluate expression");
Anders Carlsson8c3de802008-12-19 20:58:05 +00001553 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001554
Anders Carlsson8c3de802008-12-19 20:58:05 +00001555 return EvalResult.Val.getInt();
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001556}