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