ExprConstant.cpp revision 195099
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
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"
16#include "clang/AST/RecordLayout.h"
17#include "clang/AST/StmtVisitor.h"
18#include "clang/AST/ASTDiagnostic.h"
19#include "clang/Basic/Builtins.h"
20#include "clang/Basic/TargetInfo.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/Support/Compiler.h"
23#include <cstring>
24
25using namespace clang;
26using llvm::APSInt;
27using llvm::APFloat;
28
29/// EvalInfo - This is a private struct used by the evaluator to capture
30/// information about a subexpression as it is folded.  It retains information
31/// about the AST context, but also maintains information about the folded
32/// expression.
33///
34/// If an expression could be evaluated, it is still possible it is not a C
35/// "integer constant expression" or constant expression.  If not, this struct
36/// captures information about how and why not.
37///
38/// One bit of information passed *into* the request for constant folding
39/// indicates whether the subexpression is "evaluated" or not according to C
40/// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
41/// evaluate the expression regardless of what the RHS is, but C only allows
42/// certain things in certain situations.
43struct EvalInfo {
44  ASTContext &Ctx;
45
46  /// EvalResult - Contains information about the evaluation.
47  Expr::EvalResult &EvalResult;
48
49  EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx),
50           EvalResult(evalresult) {}
51};
52
53
54static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
55static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
56static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
57static bool EvaluateIntegerOrLValue(const Expr *E, APValue  &Result, EvalInfo &Info);
58static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
59static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
60
61//===----------------------------------------------------------------------===//
62// Misc utilities
63//===----------------------------------------------------------------------===//
64
65static bool EvalPointerValueAsBool(APValue& Value, bool& Result) {
66  // FIXME: Is this accurate for all kinds of bases?  If not, what would
67  // the check look like?
68  Result = Value.getLValueBase() || Value.getLValueOffset();
69  return true;
70}
71
72static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
73  if (E->getType()->isIntegralType()) {
74    APSInt IntResult;
75    if (!EvaluateInteger(E, IntResult, Info))
76      return false;
77    Result = IntResult != 0;
78    return true;
79  } else if (E->getType()->isRealFloatingType()) {
80    APFloat FloatResult(0.0);
81    if (!EvaluateFloat(E, FloatResult, Info))
82      return false;
83    Result = !FloatResult.isZero();
84    return true;
85  } else if (E->getType()->hasPointerRepresentation()) {
86    APValue PointerResult;
87    if (!EvaluatePointer(E, PointerResult, Info))
88      return false;
89    return EvalPointerValueAsBool(PointerResult, Result);
90  } else if (E->getType()->isAnyComplexType()) {
91    APValue ComplexResult;
92    if (!EvaluateComplex(E, ComplexResult, Info))
93      return false;
94    if (ComplexResult.isComplexFloat()) {
95      Result = !ComplexResult.getComplexFloatReal().isZero() ||
96               !ComplexResult.getComplexFloatImag().isZero();
97    } else {
98      Result = ComplexResult.getComplexIntReal().getBoolValue() ||
99               ComplexResult.getComplexIntImag().getBoolValue();
100    }
101    return true;
102  }
103
104  return false;
105}
106
107static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
108                                   APFloat &Value, ASTContext &Ctx) {
109  unsigned DestWidth = Ctx.getIntWidth(DestType);
110  // Determine whether we are converting to unsigned or signed.
111  bool DestSigned = DestType->isSignedIntegerType();
112
113  // FIXME: Warning for overflow.
114  uint64_t Space[4];
115  bool ignored;
116  (void)Value.convertToInteger(Space, DestWidth, DestSigned,
117                               llvm::APFloat::rmTowardZero, &ignored);
118  return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
119}
120
121static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
122                                      APFloat &Value, ASTContext &Ctx) {
123  bool ignored;
124  APFloat Result = Value;
125  Result.convert(Ctx.getFloatTypeSemantics(DestType),
126                 APFloat::rmNearestTiesToEven, &ignored);
127  return Result;
128}
129
130static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
131                                 APSInt &Value, ASTContext &Ctx) {
132  unsigned DestWidth = Ctx.getIntWidth(DestType);
133  APSInt Result = Value;
134  // Figure out if this is a truncate, extend or noop cast.
135  // If the input is signed, do a sign extend, noop, or truncate.
136  Result.extOrTrunc(DestWidth);
137  Result.setIsUnsigned(DestType->isUnsignedIntegerType());
138  return Result;
139}
140
141static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
142                                    APSInt &Value, ASTContext &Ctx) {
143
144  APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
145  Result.convertFromAPInt(Value, Value.isSigned(),
146                          APFloat::rmNearestTiesToEven);
147  return Result;
148}
149
150//===----------------------------------------------------------------------===//
151// LValue Evaluation
152//===----------------------------------------------------------------------===//
153namespace {
154class VISIBILITY_HIDDEN LValueExprEvaluator
155  : public StmtVisitor<LValueExprEvaluator, APValue> {
156  EvalInfo &Info;
157public:
158
159  LValueExprEvaluator(EvalInfo &info) : Info(info) {}
160
161  APValue VisitStmt(Stmt *S) {
162    return APValue();
163  }
164
165  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
166  APValue VisitDeclRefExpr(DeclRefExpr *E);
167  APValue VisitBlockExpr(BlockExpr *E);
168  APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
169  APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
170  APValue VisitMemberExpr(MemberExpr *E);
171  APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
172  APValue VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return APValue(E, 0); }
173  APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
174  APValue VisitUnaryDeref(UnaryOperator *E);
175  APValue VisitUnaryExtension(const UnaryOperator *E)
176    { return Visit(E->getSubExpr()); }
177  APValue VisitChooseExpr(const ChooseExpr *E)
178    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
179  // FIXME: Missing: __real__, __imag__
180};
181} // end anonymous namespace
182
183static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
184  Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
185  return Result.isLValue();
186}
187
188APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
189{
190  if (!E->hasGlobalStorage())
191    return APValue();
192
193  if (isa<FunctionDecl>(E->getDecl())) {
194    return APValue(E, 0);
195  } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
196    if (!VD->getType()->isReferenceType())
197      return APValue(E, 0);
198    if (VD->getInit())
199      return Visit(VD->getInit());
200  }
201
202  return APValue();
203}
204
205APValue LValueExprEvaluator::VisitBlockExpr(BlockExpr *E)
206{
207  if (E->hasBlockDeclRefExprs())
208    return APValue();
209
210  return APValue(E, 0);
211}
212
213APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
214  if (E->isFileScope())
215    return APValue(E, 0);
216  return APValue();
217}
218
219APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
220  APValue result;
221  QualType Ty;
222  if (E->isArrow()) {
223    if (!EvaluatePointer(E->getBase(), result, Info))
224      return APValue();
225    Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
226  } else {
227    result = Visit(E->getBase());
228    if (result.isUninit())
229      return APValue();
230    Ty = E->getBase()->getType();
231  }
232
233  RecordDecl *RD = Ty->getAsRecordType()->getDecl();
234  const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
235
236  FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
237  if (!FD) // FIXME: deal with other kinds of member expressions
238    return APValue();
239
240  if (FD->getType()->isReferenceType())
241    return APValue();
242
243  // FIXME: This is linear time.
244  unsigned i = 0;
245  for (RecordDecl::field_iterator Field = RD->field_begin(Info.Ctx),
246                               FieldEnd = RD->field_end(Info.Ctx);
247       Field != FieldEnd; (void)++Field, ++i) {
248    if (*Field == FD)
249      break;
250  }
251
252  result.setLValue(result.getLValueBase(),
253                   result.getLValueOffset() + RL.getFieldOffset(i) / 8);
254
255  return result;
256}
257
258APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
259{
260  APValue Result;
261
262  if (!EvaluatePointer(E->getBase(), Result, Info))
263    return APValue();
264
265  APSInt Index;
266  if (!EvaluateInteger(E->getIdx(), Index, Info))
267    return APValue();
268
269  uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
270
271  uint64_t Offset = Index.getSExtValue() * ElementSize;
272  Result.setLValue(Result.getLValueBase(),
273                   Result.getLValueOffset() + Offset);
274  return Result;
275}
276
277APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E)
278{
279  APValue Result;
280  if (!EvaluatePointer(E->getSubExpr(), Result, Info))
281    return APValue();
282  return Result;
283}
284
285//===----------------------------------------------------------------------===//
286// Pointer Evaluation
287//===----------------------------------------------------------------------===//
288
289namespace {
290class VISIBILITY_HIDDEN PointerExprEvaluator
291  : public StmtVisitor<PointerExprEvaluator, APValue> {
292  EvalInfo &Info;
293public:
294
295  PointerExprEvaluator(EvalInfo &info) : Info(info) {}
296
297  APValue VisitStmt(Stmt *S) {
298    return APValue();
299  }
300
301  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
302
303  APValue VisitBinaryOperator(const BinaryOperator *E);
304  APValue VisitCastExpr(const CastExpr* E);
305  APValue VisitUnaryExtension(const UnaryOperator *E)
306      { return Visit(E->getSubExpr()); }
307  APValue VisitUnaryAddrOf(const UnaryOperator *E);
308  APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
309      { return APValue(E, 0); }
310  APValue VisitAddrLabelExpr(AddrLabelExpr *E)
311      { return APValue(E, 0); }
312  APValue VisitCallExpr(CallExpr *E);
313  APValue VisitBlockExpr(BlockExpr *E) {
314    if (!E->hasBlockDeclRefExprs())
315      return APValue(E, 0);
316    return APValue();
317  }
318  APValue VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
319      { return APValue((Expr*)0, 0); }
320  APValue VisitConditionalOperator(ConditionalOperator *E);
321  APValue VisitChooseExpr(ChooseExpr *E)
322      { return Visit(E->getChosenSubExpr(Info.Ctx)); }
323  APValue VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
324      { return APValue((Expr*)0, 0); }
325  // FIXME: Missing: @protocol, @selector
326};
327} // end anonymous namespace
328
329static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
330  if (!E->getType()->hasPointerRepresentation())
331    return false;
332  Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
333  return Result.isLValue();
334}
335
336APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
337  if (E->getOpcode() != BinaryOperator::Add &&
338      E->getOpcode() != BinaryOperator::Sub)
339    return APValue();
340
341  const Expr *PExp = E->getLHS();
342  const Expr *IExp = E->getRHS();
343  if (IExp->getType()->isPointerType())
344    std::swap(PExp, IExp);
345
346  APValue ResultLValue;
347  if (!EvaluatePointer(PExp, ResultLValue, Info))
348    return APValue();
349
350  llvm::APSInt AdditionalOffset(32);
351  if (!EvaluateInteger(IExp, AdditionalOffset, Info))
352    return APValue();
353
354  QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
355  uint64_t SizeOfPointee;
356
357  // Explicitly handle GNU void* and function pointer arithmetic extensions.
358  if (PointeeType->isVoidType() || PointeeType->isFunctionType())
359    SizeOfPointee = 1;
360  else
361    SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
362
363  uint64_t Offset = ResultLValue.getLValueOffset();
364
365  if (E->getOpcode() == BinaryOperator::Add)
366    Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
367  else
368    Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
369
370  return APValue(ResultLValue.getLValueBase(), Offset);
371}
372
373APValue PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
374  APValue result;
375  if (EvaluateLValue(E->getSubExpr(), result, Info))
376    return result;
377  return APValue();
378}
379
380
381APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
382  const Expr* SubExpr = E->getSubExpr();
383
384   // Check for pointer->pointer cast
385  if (SubExpr->getType()->isPointerType()) {
386    APValue Result;
387    if (EvaluatePointer(SubExpr, Result, Info))
388      return Result;
389    return APValue();
390  }
391
392  if (SubExpr->getType()->isIntegralType()) {
393    APValue Result;
394    if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
395      return APValue();
396
397    if (Result.isInt()) {
398      Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
399      return APValue(0, Result.getInt().getZExtValue());
400    }
401
402    // Cast is of an lvalue, no need to change value.
403    return Result;
404  }
405
406  if (SubExpr->getType()->isFunctionType() ||
407      SubExpr->getType()->isBlockPointerType() ||
408      SubExpr->getType()->isArrayType()) {
409    APValue Result;
410    if (EvaluateLValue(SubExpr, Result, Info))
411      return Result;
412    return APValue();
413  }
414
415  return APValue();
416}
417
418APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
419  if (E->isBuiltinCall(Info.Ctx) ==
420        Builtin::BI__builtin___CFStringMakeConstantString)
421    return APValue(E, 0);
422  return APValue();
423}
424
425APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
426  bool BoolResult;
427  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
428    return APValue();
429
430  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
431
432  APValue Result;
433  if (EvaluatePointer(EvalExpr, Result, Info))
434    return Result;
435  return APValue();
436}
437
438//===----------------------------------------------------------------------===//
439// Vector Evaluation
440//===----------------------------------------------------------------------===//
441
442namespace {
443  class VISIBILITY_HIDDEN VectorExprEvaluator
444  : public StmtVisitor<VectorExprEvaluator, APValue> {
445    EvalInfo &Info;
446    APValue GetZeroVector(QualType VecType);
447  public:
448
449    VectorExprEvaluator(EvalInfo &info) : Info(info) {}
450
451    APValue VisitStmt(Stmt *S) {
452      return APValue();
453    }
454
455    APValue VisitParenExpr(ParenExpr *E)
456        { return Visit(E->getSubExpr()); }
457    APValue VisitUnaryExtension(const UnaryOperator *E)
458      { return Visit(E->getSubExpr()); }
459    APValue VisitUnaryPlus(const UnaryOperator *E)
460      { return Visit(E->getSubExpr()); }
461    APValue VisitUnaryReal(const UnaryOperator *E)
462      { return Visit(E->getSubExpr()); }
463    APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
464      { return GetZeroVector(E->getType()); }
465    APValue VisitCastExpr(const CastExpr* E);
466    APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
467    APValue VisitInitListExpr(const InitListExpr *E);
468    APValue VisitConditionalOperator(const ConditionalOperator *E);
469    APValue VisitChooseExpr(const ChooseExpr *E)
470      { return Visit(E->getChosenSubExpr(Info.Ctx)); }
471    APValue VisitUnaryImag(const UnaryOperator *E);
472    // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
473    //                 binary comparisons, binary and/or/xor,
474    //                 shufflevector, ExtVectorElementExpr
475    //        (Note that these require implementing conversions
476    //         between vector types.)
477  };
478} // end anonymous namespace
479
480static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
481  if (!E->getType()->isVectorType())
482    return false;
483  Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
484  return !Result.isUninit();
485}
486
487APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
488  const Expr* SE = E->getSubExpr();
489  QualType SETy = SE->getType();
490  APValue Result = APValue();
491
492  // Check for vector->vector bitcast and scalar->vector splat.
493  if (SETy->isVectorType()) {
494    return this->Visit(const_cast<Expr*>(SE));
495  } else if (SETy->isIntegerType()) {
496    APSInt IntResult;
497    if (EvaluateInteger(SE, IntResult, Info))
498      Result = APValue(IntResult);
499  } else if (SETy->isRealFloatingType()) {
500    APFloat F(0.0);
501    if (EvaluateFloat(SE, F, Info))
502      Result = APValue(F);
503  }
504
505  if (Result.isInt() || Result.isFloat()) {
506    unsigned NumElts = E->getType()->getAsVectorType()->getNumElements();
507    llvm::SmallVector<APValue, 4> Elts(NumElts, Result);
508    Result = APValue(&Elts[0], Elts.size());
509  }
510  return Result;
511}
512
513APValue
514VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
515  return this->Visit(const_cast<Expr*>(E->getInitializer()));
516}
517
518APValue
519VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
520  const VectorType *VT = E->getType()->getAsVectorType();
521  unsigned NumInits = E->getNumInits();
522  unsigned NumElements = VT->getNumElements();
523
524  QualType EltTy = VT->getElementType();
525  llvm::SmallVector<APValue, 4> Elements;
526
527  for (unsigned i = 0; i < NumElements; i++) {
528    if (EltTy->isIntegerType()) {
529      llvm::APSInt sInt(32);
530      if (i < NumInits) {
531        if (!EvaluateInteger(E->getInit(i), sInt, Info))
532          return APValue();
533      } else {
534        sInt = Info.Ctx.MakeIntValue(0, EltTy);
535      }
536      Elements.push_back(APValue(sInt));
537    } else {
538      llvm::APFloat f(0.0);
539      if (i < NumInits) {
540        if (!EvaluateFloat(E->getInit(i), f, Info))
541          return APValue();
542      } else {
543        f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
544      }
545      Elements.push_back(APValue(f));
546    }
547  }
548  return APValue(&Elements[0], Elements.size());
549}
550
551APValue
552VectorExprEvaluator::GetZeroVector(QualType T) {
553  const VectorType *VT = T->getAsVectorType();
554  QualType EltTy = VT->getElementType();
555  APValue ZeroElement;
556  if (EltTy->isIntegerType())
557    ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
558  else
559    ZeroElement =
560        APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
561
562  llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
563  return APValue(&Elements[0], Elements.size());
564}
565
566APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
567  bool BoolResult;
568  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
569    return APValue();
570
571  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
572
573  APValue Result;
574  if (EvaluateVector(EvalExpr, Result, Info))
575    return Result;
576  return APValue();
577}
578
579APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
580  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
581    Info.EvalResult.HasSideEffects = true;
582  return GetZeroVector(E->getType());
583}
584
585//===----------------------------------------------------------------------===//
586// Integer Evaluation
587//===----------------------------------------------------------------------===//
588
589namespace {
590class VISIBILITY_HIDDEN IntExprEvaluator
591  : public StmtVisitor<IntExprEvaluator, bool> {
592  EvalInfo &Info;
593  APValue &Result;
594public:
595  IntExprEvaluator(EvalInfo &info, APValue &result)
596    : Info(info), Result(result) {}
597
598  bool Success(const llvm::APSInt &SI, const Expr *E) {
599    assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
600    assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
601           "Invalid evaluation result.");
602    assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
603           "Invalid evaluation result.");
604    Result = APValue(SI);
605    return true;
606  }
607
608  bool Success(const llvm::APInt &I, const Expr *E) {
609    assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
610    assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
611           "Invalid evaluation result.");
612    Result = APValue(APSInt(I));
613    Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
614    return true;
615  }
616
617  bool Success(uint64_t Value, const Expr *E) {
618    assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
619    Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
620    return true;
621  }
622
623  bool Error(SourceLocation L, diag::kind D, const Expr *E) {
624    // Take the first error.
625    if (Info.EvalResult.Diag == 0) {
626      Info.EvalResult.DiagLoc = L;
627      Info.EvalResult.Diag = D;
628      Info.EvalResult.DiagExpr = E;
629    }
630    return false;
631  }
632
633  //===--------------------------------------------------------------------===//
634  //                            Visitor Methods
635  //===--------------------------------------------------------------------===//
636
637  bool VisitStmt(Stmt *) {
638    assert(0 && "This should be called on integers, stmts are not integers");
639    return false;
640  }
641
642  bool VisitExpr(Expr *E) {
643    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
644  }
645
646  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
647
648  bool VisitIntegerLiteral(const IntegerLiteral *E) {
649    return Success(E->getValue(), E);
650  }
651  bool VisitCharacterLiteral(const CharacterLiteral *E) {
652    return Success(E->getValue(), E);
653  }
654  bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
655    // Per gcc docs "this built-in function ignores top level
656    // qualifiers".  We need to use the canonical version to properly
657    // be able to strip CRV qualifiers from the type.
658    QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
659    QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
660    return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
661                                               T1.getUnqualifiedType()),
662                   E);
663  }
664  bool VisitDeclRefExpr(const DeclRefExpr *E);
665  bool VisitCallExpr(const CallExpr *E);
666  bool VisitBinaryOperator(const BinaryOperator *E);
667  bool VisitUnaryOperator(const UnaryOperator *E);
668  bool VisitConditionalOperator(const ConditionalOperator *E);
669
670  bool VisitCastExpr(CastExpr* E);
671  bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
672
673  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
674    return Success(E->getValue(), E);
675  }
676
677  bool VisitGNUNullExpr(const GNUNullExpr *E) {
678    return Success(0, E);
679  }
680
681  bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
682    return Success(0, E);
683  }
684
685  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
686    return Success(0, E);
687  }
688
689  bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
690    return Success(E->EvaluateTrait(), E);
691  }
692
693  bool VisitChooseExpr(const ChooseExpr *E) {
694    return Visit(E->getChosenSubExpr(Info.Ctx));
695  }
696
697  bool VisitUnaryReal(const UnaryOperator *E);
698  bool VisitUnaryImag(const UnaryOperator *E);
699
700private:
701  unsigned GetAlignOfExpr(const Expr *E);
702  unsigned GetAlignOfType(QualType T);
703  // FIXME: Missing: array subscript of vector, member of vector
704};
705} // end anonymous namespace
706
707static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
708  if (!E->getType()->isIntegralType())
709    return false;
710
711  return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
712}
713
714static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
715  APValue Val;
716  if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
717    return false;
718  Result = Val.getInt();
719  return true;
720}
721
722bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
723  // Enums are integer constant exprs.
724  if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
725    // FIXME: This is an ugly hack around the fact that enums don't set their
726    // signedness consistently; see PR3173.
727    APSInt SI = D->getInitVal();
728    SI.setIsUnsigned(!E->getType()->isSignedIntegerType());
729    // FIXME: This is an ugly hack around the fact that enums don't
730    // set their width (!?!) consistently; see PR3173.
731    SI.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
732    return Success(SI, E);
733  }
734
735  // In C++, const, non-volatile integers initialized with ICEs are ICEs.
736  // In C, they can also be folded, although they are not ICEs.
737  if (E->getType().getCVRQualifiers() == QualType::Const) {
738    if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
739      if (APValue *V = D->getEvaluatedValue())
740        return Success(V->getInt(), E);
741      if (const Expr *Init = D->getInit()) {
742        if (Visit(const_cast<Expr*>(Init))) {
743          // Cache the evaluated value in the variable declaration.
744          D->setEvaluatedValue(Info.Ctx, Result);
745          return true;
746        }
747
748        return false;
749      }
750    }
751  }
752
753  // Otherwise, random variable references are not constants.
754  return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
755}
756
757/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
758/// as GCC.
759static int EvaluateBuiltinClassifyType(const CallExpr *E) {
760  // The following enum mimics the values returned by GCC.
761  // FIXME: Does GCC differ between lvalue and rvalue references here?
762  enum gcc_type_class {
763    no_type_class = -1,
764    void_type_class, integer_type_class, char_type_class,
765    enumeral_type_class, boolean_type_class,
766    pointer_type_class, reference_type_class, offset_type_class,
767    real_type_class, complex_type_class,
768    function_type_class, method_type_class,
769    record_type_class, union_type_class,
770    array_type_class, string_type_class,
771    lang_type_class
772  };
773
774  // If no argument was supplied, default to "no_type_class". This isn't
775  // ideal, however it is what gcc does.
776  if (E->getNumArgs() == 0)
777    return no_type_class;
778
779  QualType ArgTy = E->getArg(0)->getType();
780  if (ArgTy->isVoidType())
781    return void_type_class;
782  else if (ArgTy->isEnumeralType())
783    return enumeral_type_class;
784  else if (ArgTy->isBooleanType())
785    return boolean_type_class;
786  else if (ArgTy->isCharType())
787    return string_type_class; // gcc doesn't appear to use char_type_class
788  else if (ArgTy->isIntegerType())
789    return integer_type_class;
790  else if (ArgTy->isPointerType())
791    return pointer_type_class;
792  else if (ArgTy->isReferenceType())
793    return reference_type_class;
794  else if (ArgTy->isRealType())
795    return real_type_class;
796  else if (ArgTy->isComplexType())
797    return complex_type_class;
798  else if (ArgTy->isFunctionType())
799    return function_type_class;
800  else if (ArgTy->isStructureType())
801    return record_type_class;
802  else if (ArgTy->isUnionType())
803    return union_type_class;
804  else if (ArgTy->isArrayType())
805    return array_type_class;
806  else if (ArgTy->isUnionType())
807    return union_type_class;
808  else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
809    assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
810  return -1;
811}
812
813bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
814  switch (E->isBuiltinCall(Info.Ctx)) {
815  default:
816    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
817  case Builtin::BI__builtin_classify_type:
818    return Success(EvaluateBuiltinClassifyType(E), E);
819
820  case Builtin::BI__builtin_constant_p:
821    // __builtin_constant_p always has one operand: it returns true if that
822    // operand can be folded, false otherwise.
823    return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
824  }
825}
826
827bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
828  if (E->getOpcode() == BinaryOperator::Comma) {
829    if (!Visit(E->getRHS()))
830      return false;
831
832    // If we can't evaluate the LHS, it might have side effects;
833    // conservatively mark it.
834    if (!E->getLHS()->isEvaluatable(Info.Ctx))
835      Info.EvalResult.HasSideEffects = true;
836
837    return true;
838  }
839
840  if (E->isLogicalOp()) {
841    // These need to be handled specially because the operands aren't
842    // necessarily integral
843    bool lhsResult, rhsResult;
844
845    if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
846      // We were able to evaluate the LHS, see if we can get away with not
847      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
848      if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
849        return Success(lhsResult, E);
850
851      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
852        if (E->getOpcode() == BinaryOperator::LOr)
853          return Success(lhsResult || rhsResult, E);
854        else
855          return Success(lhsResult && rhsResult, E);
856      }
857    } else {
858      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
859        // We can't evaluate the LHS; however, sometimes the result
860        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
861        if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
862            !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
863          // Since we weren't able to evaluate the left hand side, it
864          // must have had side effects.
865          Info.EvalResult.HasSideEffects = true;
866
867          return Success(rhsResult, E);
868        }
869      }
870    }
871
872    return false;
873  }
874
875  QualType LHSTy = E->getLHS()->getType();
876  QualType RHSTy = E->getRHS()->getType();
877
878  if (LHSTy->isAnyComplexType()) {
879    assert(RHSTy->isAnyComplexType() && "Invalid comparison");
880    APValue LHS, RHS;
881
882    if (!EvaluateComplex(E->getLHS(), LHS, Info))
883      return false;
884
885    if (!EvaluateComplex(E->getRHS(), RHS, Info))
886      return false;
887
888    if (LHS.isComplexFloat()) {
889      APFloat::cmpResult CR_r =
890        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
891      APFloat::cmpResult CR_i =
892        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
893
894      if (E->getOpcode() == BinaryOperator::EQ)
895        return Success((CR_r == APFloat::cmpEqual &&
896                        CR_i == APFloat::cmpEqual), E);
897      else {
898        assert(E->getOpcode() == BinaryOperator::NE &&
899               "Invalid complex comparison.");
900        return Success(((CR_r == APFloat::cmpGreaterThan ||
901                         CR_r == APFloat::cmpLessThan) &&
902                        (CR_i == APFloat::cmpGreaterThan ||
903                         CR_i == APFloat::cmpLessThan)), E);
904      }
905    } else {
906      if (E->getOpcode() == BinaryOperator::EQ)
907        return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
908                        LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
909      else {
910        assert(E->getOpcode() == BinaryOperator::NE &&
911               "Invalid compex comparison.");
912        return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
913                        LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
914      }
915    }
916  }
917
918  if (LHSTy->isRealFloatingType() &&
919      RHSTy->isRealFloatingType()) {
920    APFloat RHS(0.0), LHS(0.0);
921
922    if (!EvaluateFloat(E->getRHS(), RHS, Info))
923      return false;
924
925    if (!EvaluateFloat(E->getLHS(), LHS, Info))
926      return false;
927
928    APFloat::cmpResult CR = LHS.compare(RHS);
929
930    switch (E->getOpcode()) {
931    default:
932      assert(0 && "Invalid binary operator!");
933    case BinaryOperator::LT:
934      return Success(CR == APFloat::cmpLessThan, E);
935    case BinaryOperator::GT:
936      return Success(CR == APFloat::cmpGreaterThan, E);
937    case BinaryOperator::LE:
938      return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
939    case BinaryOperator::GE:
940      return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
941                     E);
942    case BinaryOperator::EQ:
943      return Success(CR == APFloat::cmpEqual, E);
944    case BinaryOperator::NE:
945      return Success(CR == APFloat::cmpGreaterThan
946                     || CR == APFloat::cmpLessThan, E);
947    }
948  }
949
950  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
951    if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
952      APValue LHSValue;
953      if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
954        return false;
955
956      APValue RHSValue;
957      if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
958        return false;
959
960      // Reject any bases from the normal codepath; we special-case comparisons
961      // to null.
962      if (LHSValue.getLValueBase()) {
963        if (!E->isEqualityOp())
964          return false;
965        if (RHSValue.getLValueBase() || RHSValue.getLValueOffset())
966          return false;
967        bool bres;
968        if (!EvalPointerValueAsBool(LHSValue, bres))
969          return false;
970        return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
971      } else if (RHSValue.getLValueBase()) {
972        if (!E->isEqualityOp())
973          return false;
974        if (LHSValue.getLValueBase() || LHSValue.getLValueOffset())
975          return false;
976        bool bres;
977        if (!EvalPointerValueAsBool(RHSValue, bres))
978          return false;
979        return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
980      }
981
982      if (E->getOpcode() == BinaryOperator::Sub) {
983        const QualType Type = E->getLHS()->getType();
984        const QualType ElementType = Type->getAsPointerType()->getPointeeType();
985
986        uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
987        if (!ElementType->isVoidType() && !ElementType->isFunctionType())
988          D /= Info.Ctx.getTypeSize(ElementType) / 8;
989
990        return Success(D, E);
991      }
992      bool Result;
993      if (E->getOpcode() == BinaryOperator::EQ) {
994        Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
995      } else {
996        Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
997      }
998      return Success(Result, E);
999    }
1000  }
1001  if (!LHSTy->isIntegralType() ||
1002      !RHSTy->isIntegralType()) {
1003    // We can't continue from here for non-integral types, and they
1004    // could potentially confuse the following operations.
1005    return false;
1006  }
1007
1008  // The LHS of a constant expr is always evaluated and needed.
1009  if (!Visit(E->getLHS()))
1010    return false; // error in subexpression.
1011
1012  APValue RHSVal;
1013  if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
1014    return false;
1015
1016  // Handle cases like (unsigned long)&a + 4.
1017  if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
1018    uint64_t offset = Result.getLValueOffset();
1019    if (E->getOpcode() == BinaryOperator::Add)
1020      offset += RHSVal.getInt().getZExtValue();
1021    else
1022      offset -= RHSVal.getInt().getZExtValue();
1023    Result = APValue(Result.getLValueBase(), offset);
1024    return true;
1025  }
1026
1027  // Handle cases like 4 + (unsigned long)&a
1028  if (E->getOpcode() == BinaryOperator::Add &&
1029        RHSVal.isLValue() && Result.isInt()) {
1030    uint64_t offset = RHSVal.getLValueOffset();
1031    offset += Result.getInt().getZExtValue();
1032    Result = APValue(RHSVal.getLValueBase(), offset);
1033    return true;
1034  }
1035
1036  // All the following cases expect both operands to be an integer
1037  if (!Result.isInt() || !RHSVal.isInt())
1038    return false;
1039
1040  APSInt& RHS = RHSVal.getInt();
1041
1042  switch (E->getOpcode()) {
1043  default:
1044    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1045  case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1046  case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1047  case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1048  case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1049  case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1050  case BinaryOperator::Or:  return Success(Result.getInt() | RHS, E);
1051  case BinaryOperator::Div:
1052    if (RHS == 0)
1053      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1054    return Success(Result.getInt() / RHS, E);
1055  case BinaryOperator::Rem:
1056    if (RHS == 0)
1057      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1058    return Success(Result.getInt() % RHS, E);
1059  case BinaryOperator::Shl: {
1060    // FIXME: Warn about out of range shift amounts!
1061    unsigned SA =
1062      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1063    return Success(Result.getInt() << SA, E);
1064  }
1065  case BinaryOperator::Shr: {
1066    unsigned SA =
1067      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1068    return Success(Result.getInt() >> SA, E);
1069  }
1070
1071  case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1072  case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1073  case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1074  case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1075  case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1076  case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
1077  }
1078}
1079
1080bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
1081  bool Cond;
1082  if (!HandleConversionToBool(E->getCond(), Cond, Info))
1083    return false;
1084
1085  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1086}
1087
1088unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
1089  // Get information about the alignment.
1090  unsigned CharSize = Info.Ctx.Target.getCharWidth();
1091
1092  // __alignof is defined to return the preferred alignment.
1093  return Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize;
1094}
1095
1096unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
1097  E = E->IgnoreParens();
1098
1099  // alignof decl is always accepted, even if it doesn't make sense: we default
1100  // to 1 in those cases.
1101  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1102    return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
1103
1104  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
1105    return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
1106
1107  return GetAlignOfType(E->getType());
1108}
1109
1110
1111/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1112/// expression's type.
1113bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1114  QualType DstTy = E->getType();
1115
1116  // Handle alignof separately.
1117  if (!E->isSizeOf()) {
1118    if (E->isArgumentType())
1119      return Success(GetAlignOfType(E->getArgumentType()), E);
1120    else
1121      return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
1122  }
1123
1124  QualType SrcTy = E->getTypeOfArgument();
1125
1126  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1127  // extension.
1128  if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1129    return Success(1, E);
1130
1131  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1132  if (!SrcTy->isConstantSizeType())
1133    return false;
1134
1135  // Get information about the size.
1136  unsigned BitWidth = Info.Ctx.getTypeSize(SrcTy);
1137  return Success(BitWidth / Info.Ctx.Target.getCharWidth(), E);
1138}
1139
1140bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1141  // Special case unary operators that do not need their subexpression
1142  // evaluated.  offsetof/sizeof/alignof are all special.
1143  if (E->isOffsetOfOp()) {
1144    // The AST for offsetof is defined in such a way that we can just
1145    // directly Evaluate it as an l-value.
1146    APValue LV;
1147    if (!EvaluateLValue(E->getSubExpr(), LV, Info))
1148      return false;
1149    if (LV.getLValueBase())
1150      return false;
1151    return Success(LV.getLValueOffset(), E);
1152  }
1153
1154  if (E->getOpcode() == UnaryOperator::LNot) {
1155    // LNot's operand isn't necessarily an integer, so we handle it specially.
1156    bool bres;
1157    if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1158      return false;
1159    return Success(!bres, E);
1160  }
1161
1162  // Only handle integral operations...
1163  if (!E->getSubExpr()->getType()->isIntegralType())
1164    return false;
1165
1166  // Get the operand value into 'Result'.
1167  if (!Visit(E->getSubExpr()))
1168    return false;
1169
1170  switch (E->getOpcode()) {
1171  default:
1172    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1173    // See C99 6.6p3.
1174    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1175  case UnaryOperator::Extension:
1176    // FIXME: Should extension allow i-c-e extension expressions in its scope?
1177    // If so, we could clear the diagnostic ID.
1178    return true;
1179  case UnaryOperator::Plus:
1180    // The result is always just the subexpr.
1181    return true;
1182  case UnaryOperator::Minus:
1183    if (!Result.isInt()) return false;
1184    return Success(-Result.getInt(), E);
1185  case UnaryOperator::Not:
1186    if (!Result.isInt()) return false;
1187    return Success(~Result.getInt(), E);
1188  }
1189}
1190
1191/// HandleCast - This is used to evaluate implicit or explicit casts where the
1192/// result type is integer.
1193bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
1194  Expr *SubExpr = E->getSubExpr();
1195  QualType DestType = E->getType();
1196  QualType SrcType = SubExpr->getType();
1197
1198  if (DestType->isBooleanType()) {
1199    bool BoolResult;
1200    if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1201      return false;
1202    return Success(BoolResult, E);
1203  }
1204
1205  // Handle simple integer->integer casts.
1206  if (SrcType->isIntegralType()) {
1207    if (!Visit(SubExpr))
1208      return false;
1209
1210    if (!Result.isInt()) {
1211      // Only allow casts of lvalues if they are lossless.
1212      return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1213    }
1214
1215    return Success(HandleIntToIntCast(DestType, SrcType,
1216                                      Result.getInt(), Info.Ctx), E);
1217  }
1218
1219  // FIXME: Clean this up!
1220  if (SrcType->isPointerType()) {
1221    APValue LV;
1222    if (!EvaluatePointer(SubExpr, LV, Info))
1223      return false;
1224
1225    if (LV.getLValueBase()) {
1226      // Only allow based lvalue casts if they are lossless.
1227      if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1228        return false;
1229
1230      Result = LV;
1231      return true;
1232    }
1233
1234    APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset(), SrcType);
1235    return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
1236  }
1237
1238  if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1239    // This handles double-conversion cases, where there's both
1240    // an l-value promotion and an implicit conversion to int.
1241    APValue LV;
1242    if (!EvaluateLValue(SubExpr, LV, Info))
1243      return false;
1244
1245    if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1246      return false;
1247
1248    Result = LV;
1249    return true;
1250  }
1251
1252  if (SrcType->isAnyComplexType()) {
1253    APValue C;
1254    if (!EvaluateComplex(SubExpr, C, Info))
1255      return false;
1256    if (C.isComplexFloat())
1257      return Success(HandleFloatToIntCast(DestType, SrcType,
1258                                          C.getComplexFloatReal(), Info.Ctx),
1259                     E);
1260    else
1261      return Success(HandleIntToIntCast(DestType, SrcType,
1262                                        C.getComplexIntReal(), Info.Ctx), E);
1263  }
1264  // FIXME: Handle vectors
1265
1266  if (!SrcType->isRealFloatingType())
1267    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1268
1269  APFloat F(0.0);
1270  if (!EvaluateFloat(SubExpr, F, Info))
1271    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1272
1273  return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1274}
1275
1276bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1277  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1278    APValue LV;
1279    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1280      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1281    return Success(LV.getComplexIntReal(), E);
1282  }
1283
1284  return Visit(E->getSubExpr());
1285}
1286
1287bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1288  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
1289    APValue LV;
1290    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1291      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1292    return Success(LV.getComplexIntImag(), E);
1293  }
1294
1295  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1296    Info.EvalResult.HasSideEffects = true;
1297  return Success(0, E);
1298}
1299
1300//===----------------------------------------------------------------------===//
1301// Float Evaluation
1302//===----------------------------------------------------------------------===//
1303
1304namespace {
1305class VISIBILITY_HIDDEN FloatExprEvaluator
1306  : public StmtVisitor<FloatExprEvaluator, bool> {
1307  EvalInfo &Info;
1308  APFloat &Result;
1309public:
1310  FloatExprEvaluator(EvalInfo &info, APFloat &result)
1311    : Info(info), Result(result) {}
1312
1313  bool VisitStmt(Stmt *S) {
1314    return false;
1315  }
1316
1317  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1318  bool VisitCallExpr(const CallExpr *E);
1319
1320  bool VisitUnaryOperator(const UnaryOperator *E);
1321  bool VisitBinaryOperator(const BinaryOperator *E);
1322  bool VisitFloatingLiteral(const FloatingLiteral *E);
1323  bool VisitCastExpr(CastExpr *E);
1324  bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
1325
1326  bool VisitChooseExpr(const ChooseExpr *E)
1327    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1328  bool VisitUnaryExtension(const UnaryOperator *E)
1329    { return Visit(E->getSubExpr()); }
1330
1331  // FIXME: Missing: __real__/__imag__, array subscript of vector,
1332  //                 member of vector, ImplicitValueInitExpr,
1333  //                 conditional ?:, comma
1334};
1335} // end anonymous namespace
1336
1337static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1338  return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1339}
1340
1341bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
1342  switch (E->isBuiltinCall(Info.Ctx)) {
1343  default: return false;
1344  case Builtin::BI__builtin_huge_val:
1345  case Builtin::BI__builtin_huge_valf:
1346  case Builtin::BI__builtin_huge_vall:
1347  case Builtin::BI__builtin_inf:
1348  case Builtin::BI__builtin_inff:
1349  case Builtin::BI__builtin_infl: {
1350    const llvm::fltSemantics &Sem =
1351      Info.Ctx.getFloatTypeSemantics(E->getType());
1352    Result = llvm::APFloat::getInf(Sem);
1353    return true;
1354  }
1355
1356  case Builtin::BI__builtin_nan:
1357  case Builtin::BI__builtin_nanf:
1358  case Builtin::BI__builtin_nanl:
1359    // If this is __builtin_nan() turn this into a nan, otherwise we
1360    // can't constant fold it.
1361    if (const StringLiteral *S =
1362        dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1363      if (!S->isWide()) {
1364        const llvm::fltSemantics &Sem =
1365          Info.Ctx.getFloatTypeSemantics(E->getType());
1366        llvm::SmallString<16> s;
1367        s.append(S->getStrData(), S->getStrData() + S->getByteLength());
1368        s += '\0';
1369        long l;
1370        char *endp;
1371        l = strtol(&s[0], &endp, 0);
1372        if (endp != s.end()-1)
1373          return false;
1374        unsigned type = (unsigned int)l;;
1375        Result = llvm::APFloat::getNaN(Sem, false, type);
1376        return true;
1377      }
1378    }
1379    return false;
1380
1381  case Builtin::BI__builtin_fabs:
1382  case Builtin::BI__builtin_fabsf:
1383  case Builtin::BI__builtin_fabsl:
1384    if (!EvaluateFloat(E->getArg(0), Result, Info))
1385      return false;
1386
1387    if (Result.isNegative())
1388      Result.changeSign();
1389    return true;
1390
1391  case Builtin::BI__builtin_copysign:
1392  case Builtin::BI__builtin_copysignf:
1393  case Builtin::BI__builtin_copysignl: {
1394    APFloat RHS(0.);
1395    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1396        !EvaluateFloat(E->getArg(1), RHS, Info))
1397      return false;
1398    Result.copySign(RHS);
1399    return true;
1400  }
1401  }
1402}
1403
1404bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1405  if (E->getOpcode() == UnaryOperator::Deref)
1406    return false;
1407
1408  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1409    return false;
1410
1411  switch (E->getOpcode()) {
1412  default: return false;
1413  case UnaryOperator::Plus:
1414    return true;
1415  case UnaryOperator::Minus:
1416    Result.changeSign();
1417    return true;
1418  }
1419}
1420
1421bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1422  // FIXME: Diagnostics?  I really don't understand how the warnings
1423  // and errors are supposed to work.
1424  APFloat RHS(0.0);
1425  if (!EvaluateFloat(E->getLHS(), Result, Info))
1426    return false;
1427  if (!EvaluateFloat(E->getRHS(), RHS, Info))
1428    return false;
1429
1430  switch (E->getOpcode()) {
1431  default: return false;
1432  case BinaryOperator::Mul:
1433    Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1434    return true;
1435  case BinaryOperator::Add:
1436    Result.add(RHS, APFloat::rmNearestTiesToEven);
1437    return true;
1438  case BinaryOperator::Sub:
1439    Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1440    return true;
1441  case BinaryOperator::Div:
1442    Result.divide(RHS, APFloat::rmNearestTiesToEven);
1443    return true;
1444  }
1445}
1446
1447bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1448  Result = E->getValue();
1449  return true;
1450}
1451
1452bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1453  Expr* SubExpr = E->getSubExpr();
1454
1455  if (SubExpr->getType()->isIntegralType()) {
1456    APSInt IntResult;
1457    if (!EvaluateInteger(SubExpr, IntResult, Info))
1458      return false;
1459    Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1460                                  IntResult, Info.Ctx);
1461    return true;
1462  }
1463  if (SubExpr->getType()->isRealFloatingType()) {
1464    if (!Visit(SubExpr))
1465      return false;
1466    Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1467                                    Result, Info.Ctx);
1468    return true;
1469  }
1470  // FIXME: Handle complex types
1471
1472  return false;
1473}
1474
1475bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1476  Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1477  return true;
1478}
1479
1480//===----------------------------------------------------------------------===//
1481// Complex Evaluation (for float and integer)
1482//===----------------------------------------------------------------------===//
1483
1484namespace {
1485class VISIBILITY_HIDDEN ComplexExprEvaluator
1486  : public StmtVisitor<ComplexExprEvaluator, APValue> {
1487  EvalInfo &Info;
1488
1489public:
1490  ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
1491
1492  //===--------------------------------------------------------------------===//
1493  //                            Visitor Methods
1494  //===--------------------------------------------------------------------===//
1495
1496  APValue VisitStmt(Stmt *S) {
1497    return APValue();
1498  }
1499
1500  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1501
1502  APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1503    Expr* SubExpr = E->getSubExpr();
1504
1505    if (SubExpr->getType()->isRealFloatingType()) {
1506      APFloat Result(0.0);
1507
1508      if (!EvaluateFloat(SubExpr, Result, Info))
1509        return APValue();
1510
1511      return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
1512                     Result);
1513    } else {
1514      assert(SubExpr->getType()->isIntegerType() &&
1515             "Unexpected imaginary literal.");
1516
1517      llvm::APSInt Result;
1518      if (!EvaluateInteger(SubExpr, Result, Info))
1519        return APValue();
1520
1521      llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1522      Zero = 0;
1523      return APValue(Zero, Result);
1524    }
1525  }
1526
1527  APValue VisitCastExpr(CastExpr *E) {
1528    Expr* SubExpr = E->getSubExpr();
1529    QualType EltType = E->getType()->getAsComplexType()->getElementType();
1530    QualType SubType = SubExpr->getType();
1531
1532    if (SubType->isRealFloatingType()) {
1533      APFloat Result(0.0);
1534
1535      if (!EvaluateFloat(SubExpr, Result, Info))
1536        return APValue();
1537
1538      if (EltType->isRealFloatingType()) {
1539        Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
1540        return APValue(Result,
1541                       APFloat(Result.getSemantics(), APFloat::fcZero, false));
1542      } else {
1543        llvm::APSInt IResult;
1544        IResult = HandleFloatToIntCast(EltType, SubType, Result, Info.Ctx);
1545        llvm::APSInt Zero(IResult.getBitWidth(), !IResult.isSigned());
1546        Zero = 0;
1547        return APValue(IResult, Zero);
1548      }
1549    } else if (SubType->isIntegerType()) {
1550      APSInt Result;
1551
1552      if (!EvaluateInteger(SubExpr, Result, Info))
1553        return APValue();
1554
1555      if (EltType->isRealFloatingType()) {
1556        APFloat FResult =
1557            HandleIntToFloatCast(EltType, SubType, Result, Info.Ctx);
1558        return APValue(FResult,
1559                       APFloat(FResult.getSemantics(), APFloat::fcZero, false));
1560      } else {
1561        Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
1562        llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1563        Zero = 0;
1564        return APValue(Result, Zero);
1565      }
1566    } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1567      APValue Src;
1568
1569      if (!EvaluateComplex(SubExpr, Src, Info))
1570        return APValue();
1571
1572      QualType SrcType = CT->getElementType();
1573
1574      if (Src.isComplexFloat()) {
1575        if (EltType->isRealFloatingType()) {
1576          return APValue(HandleFloatToFloatCast(EltType, SrcType,
1577                                                Src.getComplexFloatReal(),
1578                                                Info.Ctx),
1579                         HandleFloatToFloatCast(EltType, SrcType,
1580                                                Src.getComplexFloatImag(),
1581                                                Info.Ctx));
1582        } else {
1583          return APValue(HandleFloatToIntCast(EltType, SrcType,
1584                                              Src.getComplexFloatReal(),
1585                                              Info.Ctx),
1586                         HandleFloatToIntCast(EltType, SrcType,
1587                                              Src.getComplexFloatImag(),
1588                                              Info.Ctx));
1589        }
1590      } else {
1591        assert(Src.isComplexInt() && "Invalid evaluate result.");
1592        if (EltType->isRealFloatingType()) {
1593          return APValue(HandleIntToFloatCast(EltType, SrcType,
1594                                              Src.getComplexIntReal(),
1595                                              Info.Ctx),
1596                         HandleIntToFloatCast(EltType, SrcType,
1597                                              Src.getComplexIntImag(),
1598                                              Info.Ctx));
1599        } else {
1600          return APValue(HandleIntToIntCast(EltType, SrcType,
1601                                            Src.getComplexIntReal(),
1602                                            Info.Ctx),
1603                         HandleIntToIntCast(EltType, SrcType,
1604                                            Src.getComplexIntImag(),
1605                                            Info.Ctx));
1606        }
1607      }
1608    }
1609
1610    // FIXME: Handle more casts.
1611    return APValue();
1612  }
1613
1614  APValue VisitBinaryOperator(const BinaryOperator *E);
1615  APValue VisitChooseExpr(const ChooseExpr *E)
1616    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1617  APValue VisitUnaryExtension(const UnaryOperator *E)
1618    { return Visit(E->getSubExpr()); }
1619  // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
1620  //                conditional ?:, comma
1621};
1622} // end anonymous namespace
1623
1624static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
1625{
1626  Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1627  assert((!Result.isComplexFloat() ||
1628          (&Result.getComplexFloatReal().getSemantics() ==
1629           &Result.getComplexFloatImag().getSemantics())) &&
1630         "Invalid complex evaluation.");
1631  return Result.isComplexFloat() || Result.isComplexInt();
1632}
1633
1634APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
1635{
1636  APValue Result, RHS;
1637
1638  if (!EvaluateComplex(E->getLHS(), Result, Info))
1639    return APValue();
1640
1641  if (!EvaluateComplex(E->getRHS(), RHS, Info))
1642    return APValue();
1643
1644  assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1645         "Invalid operands to binary operator.");
1646  switch (E->getOpcode()) {
1647  default: return APValue();
1648  case BinaryOperator::Add:
1649    if (Result.isComplexFloat()) {
1650      Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1651                                       APFloat::rmNearestTiesToEven);
1652      Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1653                                       APFloat::rmNearestTiesToEven);
1654    } else {
1655      Result.getComplexIntReal() += RHS.getComplexIntReal();
1656      Result.getComplexIntImag() += RHS.getComplexIntImag();
1657    }
1658    break;
1659  case BinaryOperator::Sub:
1660    if (Result.isComplexFloat()) {
1661      Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1662                                            APFloat::rmNearestTiesToEven);
1663      Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1664                                            APFloat::rmNearestTiesToEven);
1665    } else {
1666      Result.getComplexIntReal() -= RHS.getComplexIntReal();
1667      Result.getComplexIntImag() -= RHS.getComplexIntImag();
1668    }
1669    break;
1670  case BinaryOperator::Mul:
1671    if (Result.isComplexFloat()) {
1672      APValue LHS = Result;
1673      APFloat &LHS_r = LHS.getComplexFloatReal();
1674      APFloat &LHS_i = LHS.getComplexFloatImag();
1675      APFloat &RHS_r = RHS.getComplexFloatReal();
1676      APFloat &RHS_i = RHS.getComplexFloatImag();
1677
1678      APFloat Tmp = LHS_r;
1679      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1680      Result.getComplexFloatReal() = Tmp;
1681      Tmp = LHS_i;
1682      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1683      Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1684
1685      Tmp = LHS_r;
1686      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1687      Result.getComplexFloatImag() = Tmp;
1688      Tmp = LHS_i;
1689      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1690      Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1691    } else {
1692      APValue LHS = Result;
1693      Result.getComplexIntReal() =
1694        (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1695         LHS.getComplexIntImag() * RHS.getComplexIntImag());
1696      Result.getComplexIntImag() =
1697        (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1698         LHS.getComplexIntImag() * RHS.getComplexIntReal());
1699    }
1700    break;
1701  }
1702
1703  return Result;
1704}
1705
1706//===----------------------------------------------------------------------===//
1707// Top level Expr::Evaluate method.
1708//===----------------------------------------------------------------------===//
1709
1710/// Evaluate - Return true if this is a constant which we can fold using
1711/// any crazy technique (that has nothing to do with language standards) that
1712/// we want to.  If this function returns true, it returns the folded constant
1713/// in Result.
1714bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1715  EvalInfo Info(Ctx, Result);
1716
1717  if (getType()->isVectorType()) {
1718    if (!EvaluateVector(this, Result.Val, Info))
1719      return false;
1720  } else if (getType()->isIntegerType()) {
1721    if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
1722      return false;
1723  } else if (getType()->hasPointerRepresentation()) {
1724    if (!EvaluatePointer(this, Result.Val, Info))
1725      return false;
1726  } else if (getType()->isRealFloatingType()) {
1727    llvm::APFloat f(0.0);
1728    if (!EvaluateFloat(this, f, Info))
1729      return false;
1730
1731    Result.Val = APValue(f);
1732  } else if (getType()->isAnyComplexType()) {
1733    if (!EvaluateComplex(this, Result.Val, Info))
1734      return false;
1735  } else
1736    return false;
1737
1738  return true;
1739}
1740
1741bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
1742  EvalInfo Info(Ctx, Result);
1743
1744  return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
1745}
1746
1747/// isEvaluatable - Call Evaluate to see if this expression can be constant
1748/// folded, but discard the result.
1749bool Expr::isEvaluatable(ASTContext &Ctx) const {
1750  EvalResult Result;
1751  return Evaluate(Result, Ctx) && !Result.HasSideEffects;
1752}
1753
1754APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
1755  EvalResult EvalResult;
1756  bool Result = Evaluate(EvalResult, Ctx);
1757  Result = Result;
1758  assert(Result && "Could not evaluate expression");
1759  assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
1760
1761  return EvalResult.Val.getInt();
1762}
1763