Home | History | Annotate | Download | only in AST
      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/CharUnits.h"
     17 #include "clang/AST/RecordLayout.h"
     18 #include "clang/AST/StmtVisitor.h"
     19 #include "clang/AST/TypeLoc.h"
     20 #include "clang/AST/ASTDiagnostic.h"
     21 #include "clang/AST/Expr.h"
     22 #include "clang/Basic/Builtins.h"
     23 #include "clang/Basic/TargetInfo.h"
     24 #include "llvm/ADT/SmallString.h"
     25 #include <cstring>
     26 
     27 using namespace clang;
     28 using llvm::APSInt;
     29 using llvm::APFloat;
     30 
     31 /// EvalInfo - This is a private struct used by the evaluator to capture
     32 /// information about a subexpression as it is folded.  It retains information
     33 /// about the AST context, but also maintains information about the folded
     34 /// expression.
     35 ///
     36 /// If an expression could be evaluated, it is still possible it is not a C
     37 /// "integer constant expression" or constant expression.  If not, this struct
     38 /// captures information about how and why not.
     39 ///
     40 /// One bit of information passed *into* the request for constant folding
     41 /// indicates whether the subexpression is "evaluated" or not according to C
     42 /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
     43 /// evaluate the expression regardless of what the RHS is, but C only allows
     44 /// certain things in certain situations.
     45 namespace {
     46   struct EvalInfo {
     47     const ASTContext &Ctx;
     48 
     49     /// EvalStatus - Contains information about the evaluation.
     50     Expr::EvalStatus &EvalStatus;
     51 
     52     typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
     53     MapTy OpaqueValues;
     54     const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
     55       MapTy::const_iterator i = OpaqueValues.find(e);
     56       if (i == OpaqueValues.end()) return 0;
     57       return &i->second;
     58     }
     59 
     60     EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
     61       : Ctx(C), EvalStatus(S) {}
     62 
     63     const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
     64   };
     65 
     66   struct ComplexValue {
     67   private:
     68     bool IsInt;
     69 
     70   public:
     71     APSInt IntReal, IntImag;
     72     APFloat FloatReal, FloatImag;
     73 
     74     ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
     75 
     76     void makeComplexFloat() { IsInt = false; }
     77     bool isComplexFloat() const { return !IsInt; }
     78     APFloat &getComplexFloatReal() { return FloatReal; }
     79     APFloat &getComplexFloatImag() { return FloatImag; }
     80 
     81     void makeComplexInt() { IsInt = true; }
     82     bool isComplexInt() const { return IsInt; }
     83     APSInt &getComplexIntReal() { return IntReal; }
     84     APSInt &getComplexIntImag() { return IntImag; }
     85 
     86     void moveInto(APValue &v) const {
     87       if (isComplexFloat())
     88         v = APValue(FloatReal, FloatImag);
     89       else
     90         v = APValue(IntReal, IntImag);
     91     }
     92     void setFrom(const APValue &v) {
     93       assert(v.isComplexFloat() || v.isComplexInt());
     94       if (v.isComplexFloat()) {
     95         makeComplexFloat();
     96         FloatReal = v.getComplexFloatReal();
     97         FloatImag = v.getComplexFloatImag();
     98       } else {
     99         makeComplexInt();
    100         IntReal = v.getComplexIntReal();
    101         IntImag = v.getComplexIntImag();
    102       }
    103     }
    104   };
    105 
    106   struct LValue {
    107     const Expr *Base;
    108     CharUnits Offset;
    109 
    110     const Expr *getLValueBase() { return Base; }
    111     CharUnits getLValueOffset() { return Offset; }
    112 
    113     void moveInto(APValue &v) const {
    114       v = APValue(Base, Offset);
    115     }
    116     void setFrom(const APValue &v) {
    117       assert(v.isLValue());
    118       Base = v.getLValueBase();
    119       Offset = v.getLValueOffset();
    120     }
    121   };
    122 }
    123 
    124 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
    125 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
    126 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
    127 static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
    128 static bool EvaluateIntegerOrLValue(const Expr *E, APValue  &Result,
    129                                     EvalInfo &Info);
    130 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
    131 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
    132 
    133 //===----------------------------------------------------------------------===//
    134 // Misc utilities
    135 //===----------------------------------------------------------------------===//
    136 
    137 static bool IsGlobalLValue(const Expr* E) {
    138   if (!E) return true;
    139 
    140   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
    141     if (isa<FunctionDecl>(DRE->getDecl()))
    142       return true;
    143     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
    144       return VD->hasGlobalStorage();
    145     return false;
    146   }
    147 
    148   if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
    149     return CLE->isFileScope();
    150 
    151   return true;
    152 }
    153 
    154 static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
    155   const Expr* Base = Value.Base;
    156 
    157   // A null base expression indicates a null pointer.  These are always
    158   // evaluatable, and they are false unless the offset is zero.
    159   if (!Base) {
    160     Result = !Value.Offset.isZero();
    161     return true;
    162   }
    163 
    164   // Require the base expression to be a global l-value.
    165   if (!IsGlobalLValue(Base)) return false;
    166 
    167   // We have a non-null base expression.  These are generally known to
    168   // be true, but if it'a decl-ref to a weak symbol it can be null at
    169   // runtime.
    170   Result = true;
    171 
    172   const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
    173   if (!DeclRef)
    174     return true;
    175 
    176   // If it's a weak symbol, it isn't constant-evaluable.
    177   const ValueDecl* Decl = DeclRef->getDecl();
    178   if (Decl->hasAttr<WeakAttr>() ||
    179       Decl->hasAttr<WeakRefAttr>() ||
    180       Decl->isWeakImported())
    181     return false;
    182 
    183   return true;
    184 }
    185 
    186 static bool HandleConversionToBool(const Expr* E, bool& Result,
    187                                    EvalInfo &Info) {
    188   if (E->getType()->isIntegralOrEnumerationType()) {
    189     APSInt IntResult;
    190     if (!EvaluateInteger(E, IntResult, Info))
    191       return false;
    192     Result = IntResult != 0;
    193     return true;
    194   } else if (E->getType()->isRealFloatingType()) {
    195     APFloat FloatResult(0.0);
    196     if (!EvaluateFloat(E, FloatResult, Info))
    197       return false;
    198     Result = !FloatResult.isZero();
    199     return true;
    200   } else if (E->getType()->hasPointerRepresentation()) {
    201     LValue PointerResult;
    202     if (!EvaluatePointer(E, PointerResult, Info))
    203       return false;
    204     return EvalPointerValueAsBool(PointerResult, Result);
    205   } else if (E->getType()->isAnyComplexType()) {
    206     ComplexValue ComplexResult;
    207     if (!EvaluateComplex(E, ComplexResult, Info))
    208       return false;
    209     if (ComplexResult.isComplexFloat()) {
    210       Result = !ComplexResult.getComplexFloatReal().isZero() ||
    211                !ComplexResult.getComplexFloatImag().isZero();
    212     } else {
    213       Result = ComplexResult.getComplexIntReal().getBoolValue() ||
    214                ComplexResult.getComplexIntImag().getBoolValue();
    215     }
    216     return true;
    217   }
    218 
    219   return false;
    220 }
    221 
    222 static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
    223                                    APFloat &Value, const ASTContext &Ctx) {
    224   unsigned DestWidth = Ctx.getIntWidth(DestType);
    225   // Determine whether we are converting to unsigned or signed.
    226   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
    227 
    228   // FIXME: Warning for overflow.
    229   APSInt Result(DestWidth, !DestSigned);
    230   bool ignored;
    231   (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
    232   return Result;
    233 }
    234 
    235 static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
    236                                       APFloat &Value, const ASTContext &Ctx) {
    237   bool ignored;
    238   APFloat Result = Value;
    239   Result.convert(Ctx.getFloatTypeSemantics(DestType),
    240                  APFloat::rmNearestTiesToEven, &ignored);
    241   return Result;
    242 }
    243 
    244 static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
    245                                  APSInt &Value, const ASTContext &Ctx) {
    246   unsigned DestWidth = Ctx.getIntWidth(DestType);
    247   APSInt Result = Value;
    248   // Figure out if this is a truncate, extend or noop cast.
    249   // If the input is signed, do a sign extend, noop, or truncate.
    250   Result = Result.extOrTrunc(DestWidth);
    251   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
    252   return Result;
    253 }
    254 
    255 static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
    256                                     APSInt &Value, const ASTContext &Ctx) {
    257 
    258   APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
    259   Result.convertFromAPInt(Value, Value.isSigned(),
    260                           APFloat::rmNearestTiesToEven);
    261   return Result;
    262 }
    263 
    264 namespace {
    265 class HasSideEffect
    266   : public ConstStmtVisitor<HasSideEffect, bool> {
    267   const ASTContext &Ctx;
    268 public:
    269 
    270   HasSideEffect(const ASTContext &C) : Ctx(C) {}
    271 
    272   // Unhandled nodes conservatively default to having side effects.
    273   bool VisitStmt(const Stmt *S) {
    274     return true;
    275   }
    276 
    277   bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
    278   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
    279     return Visit(E->getResultExpr());
    280   }
    281   bool VisitDeclRefExpr(const DeclRefExpr *E) {
    282     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
    283       return true;
    284     return false;
    285   }
    286   bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
    287     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
    288       return true;
    289     return false;
    290   }
    291   bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
    292     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
    293       return true;
    294     return false;
    295   }
    296 
    297   // We don't want to evaluate BlockExprs multiple times, as they generate
    298   // a ton of code.
    299   bool VisitBlockExpr(const BlockExpr *E) { return true; }
    300   bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
    301   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
    302     { return Visit(E->getInitializer()); }
    303   bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
    304   bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
    305   bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
    306   bool VisitStringLiteral(const StringLiteral *E) { return false; }
    307   bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
    308   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
    309     { return false; }
    310   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
    311     { return Visit(E->getLHS()) || Visit(E->getRHS()); }
    312   bool VisitChooseExpr(const ChooseExpr *E)
    313     { return Visit(E->getChosenSubExpr(Ctx)); }
    314   bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
    315   bool VisitBinAssign(const BinaryOperator *E) { return true; }
    316   bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
    317   bool VisitBinaryOperator(const BinaryOperator *E)
    318   { return Visit(E->getLHS()) || Visit(E->getRHS()); }
    319   bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
    320   bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
    321   bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
    322   bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
    323   bool VisitUnaryDeref(const UnaryOperator *E) {
    324     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
    325       return true;
    326     return Visit(E->getSubExpr());
    327   }
    328   bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
    329 
    330   // Has side effects if any element does.
    331   bool VisitInitListExpr(const InitListExpr *E) {
    332     for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
    333       if (Visit(E->getInit(i))) return true;
    334     if (const Expr *filler = E->getArrayFiller())
    335       return Visit(filler);
    336     return false;
    337   }
    338 
    339   bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
    340 };
    341 
    342 class OpaqueValueEvaluation {
    343   EvalInfo &info;
    344   OpaqueValueExpr *opaqueValue;
    345 
    346 public:
    347   OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
    348                         Expr *value)
    349     : info(info), opaqueValue(opaqueValue) {
    350 
    351     // If evaluation fails, fail immediately.
    352     if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
    353       this->opaqueValue = 0;
    354       return;
    355     }
    356   }
    357 
    358   bool hasError() const { return opaqueValue == 0; }
    359 
    360   ~OpaqueValueEvaluation() {
    361     // FIXME: This will not work for recursive constexpr functions using opaque
    362     // values. Restore the former value.
    363     if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
    364   }
    365 };
    366 
    367 } // end anonymous namespace
    368 
    369 //===----------------------------------------------------------------------===//
    370 // Generic Evaluation
    371 //===----------------------------------------------------------------------===//
    372 namespace {
    373 
    374 template <class Derived, typename RetTy=void>
    375 class ExprEvaluatorBase
    376   : public ConstStmtVisitor<Derived, RetTy> {
    377 private:
    378   RetTy DerivedSuccess(const APValue &V, const Expr *E) {
    379     return static_cast<Derived*>(this)->Success(V, E);
    380   }
    381   RetTy DerivedError(const Expr *E) {
    382     return static_cast<Derived*>(this)->Error(E);
    383   }
    384   RetTy DerivedValueInitialization(const Expr *E) {
    385     return static_cast<Derived*>(this)->ValueInitialization(E);
    386   }
    387 
    388 protected:
    389   EvalInfo &Info;
    390   typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
    391   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
    392 
    393   RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
    394 
    395 public:
    396   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
    397 
    398   RetTy VisitStmt(const Stmt *) {
    399     llvm_unreachable("Expression evaluator should not be called on stmts");
    400   }
    401   RetTy VisitExpr(const Expr *E) {
    402     return DerivedError(E);
    403   }
    404 
    405   RetTy VisitParenExpr(const ParenExpr *E)
    406     { return StmtVisitorTy::Visit(E->getSubExpr()); }
    407   RetTy VisitUnaryExtension(const UnaryOperator *E)
    408     { return StmtVisitorTy::Visit(E->getSubExpr()); }
    409   RetTy VisitUnaryPlus(const UnaryOperator *E)
    410     { return StmtVisitorTy::Visit(E->getSubExpr()); }
    411   RetTy VisitChooseExpr(const ChooseExpr *E)
    412     { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
    413   RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
    414     { return StmtVisitorTy::Visit(E->getResultExpr()); }
    415   RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
    416     { return StmtVisitorTy::Visit(E->getReplacement()); }
    417 
    418   RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
    419     OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
    420     if (opaque.hasError())
    421       return DerivedError(E);
    422 
    423     bool cond;
    424     if (!HandleConversionToBool(E->getCond(), cond, Info))
    425       return DerivedError(E);
    426 
    427     return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
    428   }
    429 
    430   RetTy VisitConditionalOperator(const ConditionalOperator *E) {
    431     bool BoolResult;
    432     if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
    433       return DerivedError(E);
    434 
    435     Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
    436     return StmtVisitorTy::Visit(EvalExpr);
    437   }
    438 
    439   RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
    440     const APValue *value = Info.getOpaqueValue(E);
    441     if (!value)
    442       return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
    443                                  : DerivedError(E));
    444     return DerivedSuccess(*value, E);
    445   }
    446 
    447   RetTy VisitInitListExpr(const InitListExpr *E) {
    448     if (Info.getLangOpts().CPlusPlus0x) {
    449       if (E->getNumInits() == 0)
    450         return DerivedValueInitialization(E);
    451       if (E->getNumInits() == 1)
    452         return StmtVisitorTy::Visit(E->getInit(0));
    453     }
    454     return DerivedError(E);
    455   }
    456   RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
    457     return DerivedValueInitialization(E);
    458   }
    459   RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
    460     return DerivedValueInitialization(E);
    461   }
    462 
    463 };
    464 
    465 }
    466 
    467 //===----------------------------------------------------------------------===//
    468 // LValue Evaluation
    469 //===----------------------------------------------------------------------===//
    470 namespace {
    471 class LValueExprEvaluator
    472   : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
    473   LValue &Result;
    474   const Decl *PrevDecl;
    475 
    476   bool Success(const Expr *E) {
    477     Result.Base = E;
    478     Result.Offset = CharUnits::Zero();
    479     return true;
    480   }
    481 public:
    482 
    483   LValueExprEvaluator(EvalInfo &info, LValue &Result) :
    484     ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
    485 
    486   bool Success(const APValue &V, const Expr *E) {
    487     Result.setFrom(V);
    488     return true;
    489   }
    490   bool Error(const Expr *E) {
    491     return false;
    492   }
    493 
    494   bool VisitDeclRefExpr(const DeclRefExpr *E);
    495   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
    496   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
    497   bool VisitMemberExpr(const MemberExpr *E);
    498   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
    499   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
    500   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
    501   bool VisitUnaryDeref(const UnaryOperator *E);
    502 
    503   bool VisitCastExpr(const CastExpr *E) {
    504     switch (E->getCastKind()) {
    505     default:
    506       return false;
    507 
    508     case CK_NoOp:
    509     case CK_LValueBitCast:
    510       return Visit(E->getSubExpr());
    511 
    512     // FIXME: Support CK_DerivedToBase and friends.
    513     }
    514   }
    515 
    516   // FIXME: Missing: __real__, __imag__
    517 
    518 };
    519 } // end anonymous namespace
    520 
    521 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
    522   return LValueExprEvaluator(Info, Result).Visit(E);
    523 }
    524 
    525 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
    526   if (isa<FunctionDecl>(E->getDecl())) {
    527     return Success(E);
    528   } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
    529     if (!VD->getType()->isReferenceType())
    530       return Success(E);
    531     // Reference parameters can refer to anything even if they have an
    532     // "initializer" in the form of a default argument.
    533     if (!isa<ParmVarDecl>(VD)) {
    534       // FIXME: Check whether VD might be overridden!
    535 
    536       // Check for recursive initializers of references.
    537       if (PrevDecl == VD)
    538         return Error(E);
    539       PrevDecl = VD;
    540       if (const Expr *Init = VD->getAnyInitializer())
    541         return Visit(Init);
    542     }
    543   }
    544 
    545   return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
    546 }
    547 
    548 bool
    549 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
    550   return Success(E);
    551 }
    552 
    553 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
    554   QualType Ty;
    555   if (E->isArrow()) {
    556     if (!EvaluatePointer(E->getBase(), Result, Info))
    557       return false;
    558     Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
    559   } else {
    560     if (!Visit(E->getBase()))
    561       return false;
    562     Ty = E->getBase()->getType();
    563   }
    564 
    565   const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
    566   const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
    567 
    568   const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
    569   if (!FD) // FIXME: deal with other kinds of member expressions
    570     return false;
    571 
    572   if (FD->getType()->isReferenceType())
    573     return false;
    574 
    575   unsigned i = FD->getFieldIndex();
    576   Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
    577   return true;
    578 }
    579 
    580 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
    581   if (!EvaluatePointer(E->getBase(), Result, Info))
    582     return false;
    583 
    584   APSInt Index;
    585   if (!EvaluateInteger(E->getIdx(), Index, Info))
    586     return false;
    587 
    588   CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
    589   Result.Offset += Index.getSExtValue() * ElementSize;
    590   return true;
    591 }
    592 
    593 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
    594   return EvaluatePointer(E->getSubExpr(), Result, Info);
    595 }
    596 
    597 //===----------------------------------------------------------------------===//
    598 // Pointer Evaluation
    599 //===----------------------------------------------------------------------===//
    600 
    601 namespace {
    602 class PointerExprEvaluator
    603   : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
    604   LValue &Result;
    605 
    606   bool Success(const Expr *E) {
    607     Result.Base = E;
    608     Result.Offset = CharUnits::Zero();
    609     return true;
    610   }
    611 public:
    612 
    613   PointerExprEvaluator(EvalInfo &info, LValue &Result)
    614     : ExprEvaluatorBaseTy(info), Result(Result) {}
    615 
    616   bool Success(const APValue &V, const Expr *E) {
    617     Result.setFrom(V);
    618     return true;
    619   }
    620   bool Error(const Stmt *S) {
    621     return false;
    622   }
    623   bool ValueInitialization(const Expr *E) {
    624     return Success((Expr*)0);
    625   }
    626 
    627   bool VisitBinaryOperator(const BinaryOperator *E);
    628   bool VisitCastExpr(const CastExpr* E);
    629   bool VisitUnaryAddrOf(const UnaryOperator *E);
    630   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
    631       { return Success(E); }
    632   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
    633       { return Success(E); }
    634   bool VisitCallExpr(const CallExpr *E);
    635   bool VisitBlockExpr(const BlockExpr *E) {
    636     if (!E->getBlockDecl()->hasCaptures())
    637       return Success(E);
    638     return false;
    639   }
    640   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
    641       { return ValueInitialization(E); }
    642 
    643   // FIXME: Missing: @protocol, @selector
    644 };
    645 } // end anonymous namespace
    646 
    647 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
    648   assert(E->getType()->hasPointerRepresentation());
    649   return PointerExprEvaluator(Info, Result).Visit(E);
    650 }
    651 
    652 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
    653   if (E->getOpcode() != BO_Add &&
    654       E->getOpcode() != BO_Sub)
    655     return false;
    656 
    657   const Expr *PExp = E->getLHS();
    658   const Expr *IExp = E->getRHS();
    659   if (IExp->getType()->isPointerType())
    660     std::swap(PExp, IExp);
    661 
    662   if (!EvaluatePointer(PExp, Result, Info))
    663     return false;
    664 
    665   llvm::APSInt Offset;
    666   if (!EvaluateInteger(IExp, Offset, Info))
    667     return false;
    668   int64_t AdditionalOffset
    669     = Offset.isSigned() ? Offset.getSExtValue()
    670                         : static_cast<int64_t>(Offset.getZExtValue());
    671 
    672   // Compute the new offset in the appropriate width.
    673 
    674   QualType PointeeType =
    675     PExp->getType()->getAs<PointerType>()->getPointeeType();
    676   CharUnits SizeOfPointee;
    677 
    678   // Explicitly handle GNU void* and function pointer arithmetic extensions.
    679   if (PointeeType->isVoidType() || PointeeType->isFunctionType())
    680     SizeOfPointee = CharUnits::One();
    681   else
    682     SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
    683 
    684   if (E->getOpcode() == BO_Add)
    685     Result.Offset += AdditionalOffset * SizeOfPointee;
    686   else
    687     Result.Offset -= AdditionalOffset * SizeOfPointee;
    688 
    689   return true;
    690 }
    691 
    692 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
    693   return EvaluateLValue(E->getSubExpr(), Result, Info);
    694 }
    695 
    696 
    697 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
    698   const Expr* SubExpr = E->getSubExpr();
    699 
    700   switch (E->getCastKind()) {
    701   default:
    702     break;
    703 
    704   case CK_NoOp:
    705   case CK_BitCast:
    706   case CK_CPointerToObjCPointerCast:
    707   case CK_BlockPointerToObjCPointerCast:
    708   case CK_AnyPointerToBlockPointerCast:
    709     return Visit(SubExpr);
    710 
    711   case CK_DerivedToBase:
    712   case CK_UncheckedDerivedToBase: {
    713     LValue BaseLV;
    714     if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
    715       return false;
    716 
    717     // Now figure out the necessary offset to add to the baseLV to get from
    718     // the derived class to the base class.
    719     CharUnits Offset = CharUnits::Zero();
    720 
    721     QualType Ty = E->getSubExpr()->getType();
    722     const CXXRecordDecl *DerivedDecl =
    723       Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
    724 
    725     for (CastExpr::path_const_iterator PathI = E->path_begin(),
    726          PathE = E->path_end(); PathI != PathE; ++PathI) {
    727       const CXXBaseSpecifier *Base = *PathI;
    728 
    729       // FIXME: If the base is virtual, we'd need to determine the type of the
    730       // most derived class and we don't support that right now.
    731       if (Base->isVirtual())
    732         return false;
    733 
    734       const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
    735       const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
    736 
    737       Offset += Layout.getBaseClassOffset(BaseDecl);
    738       DerivedDecl = BaseDecl;
    739     }
    740 
    741     Result.Base = BaseLV.getLValueBase();
    742     Result.Offset = BaseLV.getLValueOffset() + Offset;
    743     return true;
    744   }
    745 
    746   case CK_NullToPointer: {
    747     Result.Base = 0;
    748     Result.Offset = CharUnits::Zero();
    749     return true;
    750   }
    751 
    752   case CK_IntegralToPointer: {
    753     APValue Value;
    754     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
    755       break;
    756 
    757     if (Value.isInt()) {
    758       Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
    759       Result.Base = 0;
    760       Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
    761       return true;
    762     } else {
    763       // Cast is of an lvalue, no need to change value.
    764       Result.Base = Value.getLValueBase();
    765       Result.Offset = Value.getLValueOffset();
    766       return true;
    767     }
    768   }
    769   case CK_ArrayToPointerDecay:
    770   case CK_FunctionToPointerDecay:
    771     return EvaluateLValue(SubExpr, Result, Info);
    772   }
    773 
    774   return false;
    775 }
    776 
    777 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
    778   if (E->isBuiltinCall(Info.Ctx) ==
    779         Builtin::BI__builtin___CFStringMakeConstantString ||
    780       E->isBuiltinCall(Info.Ctx) ==
    781         Builtin::BI__builtin___NSStringMakeConstantString)
    782     return Success(E);
    783 
    784   return ExprEvaluatorBaseTy::VisitCallExpr(E);
    785 }
    786 
    787 //===----------------------------------------------------------------------===//
    788 // Vector Evaluation
    789 //===----------------------------------------------------------------------===//
    790 
    791 namespace {
    792   class VectorExprEvaluator
    793   : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
    794     APValue GetZeroVector(QualType VecType);
    795   public:
    796 
    797     VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
    798 
    799     APValue Success(const APValue &V, const Expr *E) { return V; }
    800     APValue Error(const Expr *E) { return APValue(); }
    801     APValue ValueInitialization(const Expr *E)
    802       { return GetZeroVector(E->getType()); }
    803 
    804     APValue VisitUnaryReal(const UnaryOperator *E)
    805       { return Visit(E->getSubExpr()); }
    806     APValue VisitCastExpr(const CastExpr* E);
    807     APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
    808     APValue VisitInitListExpr(const InitListExpr *E);
    809     APValue VisitUnaryImag(const UnaryOperator *E);
    810     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
    811     //                 binary comparisons, binary and/or/xor,
    812     //                 shufflevector, ExtVectorElementExpr
    813     //        (Note that these require implementing conversions
    814     //         between vector types.)
    815   };
    816 } // end anonymous namespace
    817 
    818 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
    819   if (!E->getType()->isVectorType())
    820     return false;
    821   Result = VectorExprEvaluator(Info).Visit(E);
    822   return !Result.isUninit();
    823 }
    824 
    825 APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
    826   const VectorType *VTy = E->getType()->getAs<VectorType>();
    827   QualType EltTy = VTy->getElementType();
    828   unsigned NElts = VTy->getNumElements();
    829   unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
    830 
    831   const Expr* SE = E->getSubExpr();
    832   QualType SETy = SE->getType();
    833 
    834   switch (E->getCastKind()) {
    835   case CK_VectorSplat: {
    836     APValue Result = APValue();
    837     if (SETy->isIntegerType()) {
    838       APSInt IntResult;
    839       if (!EvaluateInteger(SE, IntResult, Info))
    840          return APValue();
    841       Result = APValue(IntResult);
    842     } else if (SETy->isRealFloatingType()) {
    843        APFloat F(0.0);
    844        if (!EvaluateFloat(SE, F, Info))
    845          return APValue();
    846        Result = APValue(F);
    847     } else {
    848       return APValue();
    849     }
    850 
    851     // Splat and create vector APValue.
    852     SmallVector<APValue, 4> Elts(NElts, Result);
    853     return APValue(&Elts[0], Elts.size());
    854   }
    855   case CK_BitCast: {
    856     if (SETy->isVectorType())
    857       return Visit(SE);
    858 
    859     if (!SETy->isIntegerType())
    860       return APValue();
    861 
    862     APSInt Init;
    863     if (!EvaluateInteger(SE, Init, Info))
    864       return APValue();
    865 
    866     assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
    867            "Vectors must be composed of ints or floats");
    868 
    869     SmallVector<APValue, 4> Elts;
    870     for (unsigned i = 0; i != NElts; ++i) {
    871       APSInt Tmp = Init.extOrTrunc(EltWidth);
    872 
    873       if (EltTy->isIntegerType())
    874         Elts.push_back(APValue(Tmp));
    875       else
    876         Elts.push_back(APValue(APFloat(Tmp)));
    877 
    878       Init >>= EltWidth;
    879     }
    880     return APValue(&Elts[0], Elts.size());
    881   }
    882   case CK_LValueToRValue:
    883   case CK_NoOp:
    884     return Visit(SE);
    885   default:
    886     return APValue();
    887   }
    888 }
    889 
    890 APValue
    891 VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
    892   return this->Visit(E->getInitializer());
    893 }
    894 
    895 APValue
    896 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
    897   const VectorType *VT = E->getType()->getAs<VectorType>();
    898   unsigned NumInits = E->getNumInits();
    899   unsigned NumElements = VT->getNumElements();
    900 
    901   QualType EltTy = VT->getElementType();
    902   SmallVector<APValue, 4> Elements;
    903 
    904   // If a vector is initialized with a single element, that value
    905   // becomes every element of the vector, not just the first.
    906   // This is the behavior described in the IBM AltiVec documentation.
    907   if (NumInits == 1) {
    908 
    909     // Handle the case where the vector is initialized by a another
    910     // vector (OpenCL 6.1.6).
    911     if (E->getInit(0)->getType()->isVectorType())
    912       return this->Visit(const_cast<Expr*>(E->getInit(0)));
    913 
    914     APValue InitValue;
    915     if (EltTy->isIntegerType()) {
    916       llvm::APSInt sInt(32);
    917       if (!EvaluateInteger(E->getInit(0), sInt, Info))
    918         return APValue();
    919       InitValue = APValue(sInt);
    920     } else {
    921       llvm::APFloat f(0.0);
    922       if (!EvaluateFloat(E->getInit(0), f, Info))
    923         return APValue();
    924       InitValue = APValue(f);
    925     }
    926     for (unsigned i = 0; i < NumElements; i++) {
    927       Elements.push_back(InitValue);
    928     }
    929   } else {
    930     for (unsigned i = 0; i < NumElements; i++) {
    931       if (EltTy->isIntegerType()) {
    932         llvm::APSInt sInt(32);
    933         if (i < NumInits) {
    934           if (!EvaluateInteger(E->getInit(i), sInt, Info))
    935             return APValue();
    936         } else {
    937           sInt = Info.Ctx.MakeIntValue(0, EltTy);
    938         }
    939         Elements.push_back(APValue(sInt));
    940       } else {
    941         llvm::APFloat f(0.0);
    942         if (i < NumInits) {
    943           if (!EvaluateFloat(E->getInit(i), f, Info))
    944             return APValue();
    945         } else {
    946           f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
    947         }
    948         Elements.push_back(APValue(f));
    949       }
    950     }
    951   }
    952   return APValue(&Elements[0], Elements.size());
    953 }
    954 
    955 APValue
    956 VectorExprEvaluator::GetZeroVector(QualType T) {
    957   const VectorType *VT = T->getAs<VectorType>();
    958   QualType EltTy = VT->getElementType();
    959   APValue ZeroElement;
    960   if (EltTy->isIntegerType())
    961     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
    962   else
    963     ZeroElement =
    964         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
    965 
    966   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
    967   return APValue(&Elements[0], Elements.size());
    968 }
    969 
    970 APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
    971   APValue Scratch;
    972   if (!Evaluate(Scratch, Info, E->getSubExpr()))
    973     Info.EvalStatus.HasSideEffects = true;
    974   return GetZeroVector(E->getType());
    975 }
    976 
    977 //===----------------------------------------------------------------------===//
    978 // Integer Evaluation
    979 //===----------------------------------------------------------------------===//
    980 
    981 namespace {
    982 class IntExprEvaluator
    983   : public ExprEvaluatorBase<IntExprEvaluator, bool> {
    984   APValue &Result;
    985 public:
    986   IntExprEvaluator(EvalInfo &info, APValue &result)
    987     : ExprEvaluatorBaseTy(info), Result(result) {}
    988 
    989   bool Success(const llvm::APSInt &SI, const Expr *E) {
    990     assert(E->getType()->isIntegralOrEnumerationType() &&
    991            "Invalid evaluation result.");
    992     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
    993            "Invalid evaluation result.");
    994     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
    995            "Invalid evaluation result.");
    996     Result = APValue(SI);
    997     return true;
    998   }
    999 
   1000   bool Success(const llvm::APInt &I, const Expr *E) {
   1001     assert(E->getType()->isIntegralOrEnumerationType() &&
   1002            "Invalid evaluation result.");
   1003     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
   1004            "Invalid evaluation result.");
   1005     Result = APValue(APSInt(I));
   1006     Result.getInt().setIsUnsigned(
   1007                             E->getType()->isUnsignedIntegerOrEnumerationType());
   1008     return true;
   1009   }
   1010 
   1011   bool Success(uint64_t Value, const Expr *E) {
   1012     assert(E->getType()->isIntegralOrEnumerationType() &&
   1013            "Invalid evaluation result.");
   1014     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
   1015     return true;
   1016   }
   1017 
   1018   bool Success(CharUnits Size, const Expr *E) {
   1019     return Success(Size.getQuantity(), E);
   1020   }
   1021 
   1022 
   1023   bool Error(SourceLocation L, diag::kind D, const Expr *E) {
   1024     // Take the first error.
   1025     if (Info.EvalStatus.Diag == 0) {
   1026       Info.EvalStatus.DiagLoc = L;
   1027       Info.EvalStatus.Diag = D;
   1028       Info.EvalStatus.DiagExpr = E;
   1029     }
   1030     return false;
   1031   }
   1032 
   1033   bool Success(const APValue &V, const Expr *E) {
   1034     return Success(V.getInt(), E);
   1035   }
   1036   bool Error(const Expr *E) {
   1037     return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
   1038   }
   1039 
   1040   bool ValueInitialization(const Expr *E) { return Success(0, E); }
   1041 
   1042   //===--------------------------------------------------------------------===//
   1043   //                            Visitor Methods
   1044   //===--------------------------------------------------------------------===//
   1045 
   1046   bool VisitIntegerLiteral(const IntegerLiteral *E) {
   1047     return Success(E->getValue(), E);
   1048   }
   1049   bool VisitCharacterLiteral(const CharacterLiteral *E) {
   1050     return Success(E->getValue(), E);
   1051   }
   1052 
   1053   bool CheckReferencedDecl(const Expr *E, const Decl *D);
   1054   bool VisitDeclRefExpr(const DeclRefExpr *E) {
   1055     if (CheckReferencedDecl(E, E->getDecl()))
   1056       return true;
   1057 
   1058     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
   1059   }
   1060   bool VisitMemberExpr(const MemberExpr *E) {
   1061     if (CheckReferencedDecl(E, E->getMemberDecl())) {
   1062       // Conservatively assume a MemberExpr will have side-effects
   1063       Info.EvalStatus.HasSideEffects = true;
   1064       return true;
   1065     }
   1066 
   1067     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
   1068   }
   1069 
   1070   bool VisitCallExpr(const CallExpr *E);
   1071   bool VisitBinaryOperator(const BinaryOperator *E);
   1072   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
   1073   bool VisitUnaryOperator(const UnaryOperator *E);
   1074 
   1075   bool VisitCastExpr(const CastExpr* E);
   1076   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
   1077 
   1078   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
   1079     return Success(E->getValue(), E);
   1080   }
   1081 
   1082   // Note, GNU defines __null as an integer, not a pointer.
   1083   bool VisitGNUNullExpr(const GNUNullExpr *E) {
   1084     return ValueInitialization(E);
   1085   }
   1086 
   1087   bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
   1088     return Success(E->getValue(), E);
   1089   }
   1090 
   1091   bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
   1092     return Success(E->getValue(), E);
   1093   }
   1094 
   1095   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
   1096     return Success(E->getValue(), E);
   1097   }
   1098 
   1099   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
   1100     return Success(E->getValue(), E);
   1101   }
   1102 
   1103   bool VisitUnaryReal(const UnaryOperator *E);
   1104   bool VisitUnaryImag(const UnaryOperator *E);
   1105 
   1106   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
   1107   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
   1108 
   1109 private:
   1110   CharUnits GetAlignOfExpr(const Expr *E);
   1111   CharUnits GetAlignOfType(QualType T);
   1112   static QualType GetObjectType(const Expr *E);
   1113   bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
   1114   // FIXME: Missing: array subscript of vector, member of vector
   1115 };
   1116 } // end anonymous namespace
   1117 
   1118 static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
   1119   assert(E->getType()->isIntegralOrEnumerationType());
   1120   return IntExprEvaluator(Info, Result).Visit(E);
   1121 }
   1122 
   1123 static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
   1124   assert(E->getType()->isIntegralOrEnumerationType());
   1125 
   1126   APValue Val;
   1127   if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
   1128     return false;
   1129   Result = Val.getInt();
   1130   return true;
   1131 }
   1132 
   1133 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
   1134   // Enums are integer constant exprs.
   1135   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
   1136     // Check for signedness/width mismatches between E type and ECD value.
   1137     bool SameSign = (ECD->getInitVal().isSigned()
   1138                      == E->getType()->isSignedIntegerOrEnumerationType());
   1139     bool SameWidth = (ECD->getInitVal().getBitWidth()
   1140                       == Info.Ctx.getIntWidth(E->getType()));
   1141     if (SameSign && SameWidth)
   1142       return Success(ECD->getInitVal(), E);
   1143     else {
   1144       // Get rid of mismatch (otherwise Success assertions will fail)
   1145       // by computing a new value matching the type of E.
   1146       llvm::APSInt Val = ECD->getInitVal();
   1147       if (!SameSign)
   1148         Val.setIsSigned(!ECD->getInitVal().isSigned());
   1149       if (!SameWidth)
   1150         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
   1151       return Success(Val, E);
   1152     }
   1153   }
   1154 
   1155   // In C++, const, non-volatile integers initialized with ICEs are ICEs.
   1156   // In C, they can also be folded, although they are not ICEs.
   1157   if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
   1158                                                         == Qualifiers::Const) {
   1159 
   1160     if (isa<ParmVarDecl>(D))
   1161       return false;
   1162 
   1163     if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
   1164       if (const Expr *Init = VD->getAnyInitializer()) {
   1165         if (APValue *V = VD->getEvaluatedValue()) {
   1166           if (V->isInt())
   1167             return Success(V->getInt(), E);
   1168           return false;
   1169         }
   1170 
   1171         if (VD->isEvaluatingValue())
   1172           return false;
   1173 
   1174         VD->setEvaluatingValue();
   1175 
   1176         Expr::EvalResult EResult;
   1177         // FIXME: Produce a diagnostic if the initializer isn't a constant
   1178         // expression.
   1179         if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
   1180             EResult.Val.isInt()) {
   1181           // Cache the evaluated value in the variable declaration.
   1182           Result = EResult.Val;
   1183           VD->setEvaluatedValue(Result);
   1184           return true;
   1185         }
   1186 
   1187         VD->setEvaluatedValue(APValue());
   1188       }
   1189     }
   1190   }
   1191 
   1192   // Otherwise, random variable references are not constants.
   1193   return false;
   1194 }
   1195 
   1196 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
   1197 /// as GCC.
   1198 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
   1199   // The following enum mimics the values returned by GCC.
   1200   // FIXME: Does GCC differ between lvalue and rvalue references here?
   1201   enum gcc_type_class {
   1202     no_type_class = -1,
   1203     void_type_class, integer_type_class, char_type_class,
   1204     enumeral_type_class, boolean_type_class,
   1205     pointer_type_class, reference_type_class, offset_type_class,
   1206     real_type_class, complex_type_class,
   1207     function_type_class, method_type_class,
   1208     record_type_class, union_type_class,
   1209     array_type_class, string_type_class,
   1210     lang_type_class
   1211   };
   1212 
   1213   // If no argument was supplied, default to "no_type_class". This isn't
   1214   // ideal, however it is what gcc does.
   1215   if (E->getNumArgs() == 0)
   1216     return no_type_class;
   1217 
   1218   QualType ArgTy = E->getArg(0)->getType();
   1219   if (ArgTy->isVoidType())
   1220     return void_type_class;
   1221   else if (ArgTy->isEnumeralType())
   1222     return enumeral_type_class;
   1223   else if (ArgTy->isBooleanType())
   1224     return boolean_type_class;
   1225   else if (ArgTy->isCharType())
   1226     return string_type_class; // gcc doesn't appear to use char_type_class
   1227   else if (ArgTy->isIntegerType())
   1228     return integer_type_class;
   1229   else if (ArgTy->isPointerType())
   1230     return pointer_type_class;
   1231   else if (ArgTy->isReferenceType())
   1232     return reference_type_class;
   1233   else if (ArgTy->isRealType())
   1234     return real_type_class;
   1235   else if (ArgTy->isComplexType())
   1236     return complex_type_class;
   1237   else if (ArgTy->isFunctionType())
   1238     return function_type_class;
   1239   else if (ArgTy->isStructureOrClassType())
   1240     return record_type_class;
   1241   else if (ArgTy->isUnionType())
   1242     return union_type_class;
   1243   else if (ArgTy->isArrayType())
   1244     return array_type_class;
   1245   else if (ArgTy->isUnionType())
   1246     return union_type_class;
   1247   else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
   1248     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
   1249   return -1;
   1250 }
   1251 
   1252 /// Retrieves the "underlying object type" of the given expression,
   1253 /// as used by __builtin_object_size.
   1254 QualType IntExprEvaluator::GetObjectType(const Expr *E) {
   1255   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
   1256     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
   1257       return VD->getType();
   1258   } else if (isa<CompoundLiteralExpr>(E)) {
   1259     return E->getType();
   1260   }
   1261 
   1262   return QualType();
   1263 }
   1264 
   1265 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
   1266   // TODO: Perhaps we should let LLVM lower this?
   1267   LValue Base;
   1268   if (!EvaluatePointer(E->getArg(0), Base, Info))
   1269     return false;
   1270 
   1271   // If we can prove the base is null, lower to zero now.
   1272   const Expr *LVBase = Base.getLValueBase();
   1273   if (!LVBase) return Success(0, E);
   1274 
   1275   QualType T = GetObjectType(LVBase);
   1276   if (T.isNull() ||
   1277       T->isIncompleteType() ||
   1278       T->isFunctionType() ||
   1279       T->isVariablyModifiedType() ||
   1280       T->isDependentType())
   1281     return false;
   1282 
   1283   CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
   1284   CharUnits Offset = Base.getLValueOffset();
   1285 
   1286   if (!Offset.isNegative() && Offset <= Size)
   1287     Size -= Offset;
   1288   else
   1289     Size = CharUnits::Zero();
   1290   return Success(Size, E);
   1291 }
   1292 
   1293 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
   1294   switch (E->isBuiltinCall(Info.Ctx)) {
   1295   default:
   1296     return ExprEvaluatorBaseTy::VisitCallExpr(E);
   1297 
   1298   case Builtin::BI__builtin_object_size: {
   1299     if (TryEvaluateBuiltinObjectSize(E))
   1300       return true;
   1301 
   1302     // If evaluating the argument has side-effects we can't determine
   1303     // the size of the object and lower it to unknown now.
   1304     if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
   1305       if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
   1306         return Success(-1ULL, E);
   1307       return Success(0, E);
   1308     }
   1309 
   1310     return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
   1311   }
   1312 
   1313   case Builtin::BI__builtin_classify_type:
   1314     return Success(EvaluateBuiltinClassifyType(E), E);
   1315 
   1316   case Builtin::BI__builtin_constant_p:
   1317     // __builtin_constant_p always has one operand: it returns true if that
   1318     // operand can be folded, false otherwise.
   1319     return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
   1320 
   1321   case Builtin::BI__builtin_eh_return_data_regno: {
   1322     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
   1323     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
   1324     return Success(Operand, E);
   1325   }
   1326 
   1327   case Builtin::BI__builtin_expect:
   1328     return Visit(E->getArg(0));
   1329 
   1330   case Builtin::BIstrlen:
   1331   case Builtin::BI__builtin_strlen:
   1332     // As an extension, we support strlen() and __builtin_strlen() as constant
   1333     // expressions when the argument is a string literal.
   1334     if (const StringLiteral *S
   1335                = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
   1336       // The string literal may have embedded null characters. Find the first
   1337       // one and truncate there.
   1338       StringRef Str = S->getString();
   1339       StringRef::size_type Pos = Str.find(0);
   1340       if (Pos != StringRef::npos)
   1341         Str = Str.substr(0, Pos);
   1342 
   1343       return Success(Str.size(), E);
   1344     }
   1345 
   1346     return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
   1347 
   1348   case Builtin::BI__atomic_is_lock_free: {
   1349     APSInt SizeVal;
   1350     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
   1351       return false;
   1352 
   1353     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
   1354     // of two less than the maximum inline atomic width, we know it is
   1355     // lock-free.  If the size isn't a power of two, or greater than the
   1356     // maximum alignment where we promote atomics, we know it is not lock-free
   1357     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
   1358     // the answer can only be determined at runtime; for example, 16-byte
   1359     // atomics have lock-free implementations on some, but not all,
   1360     // x86-64 processors.
   1361 
   1362     // Check power-of-two.
   1363     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
   1364     if (!Size.isPowerOfTwo())
   1365 #if 0
   1366       // FIXME: Suppress this folding until the ABI for the promotion width
   1367       // settles.
   1368       return Success(0, E);
   1369 #else
   1370       return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
   1371 #endif
   1372 
   1373 #if 0
   1374     // Check against promotion width.
   1375     // FIXME: Suppress this folding until the ABI for the promotion width
   1376     // settles.
   1377     unsigned PromoteWidthBits =
   1378         Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
   1379     if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
   1380       return Success(0, E);
   1381 #endif
   1382 
   1383     // Check against inlining width.
   1384     unsigned InlineWidthBits =
   1385         Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
   1386     if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
   1387       return Success(1, E);
   1388 
   1389     return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
   1390   }
   1391   }
   1392 }
   1393 
   1394 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   1395   if (E->getOpcode() == BO_Comma) {
   1396     if (!Visit(E->getRHS()))
   1397       return false;
   1398 
   1399     // If we can't evaluate the LHS, it might have side effects;
   1400     // conservatively mark it.
   1401     APValue Scratch;
   1402     if (!Evaluate(Scratch, Info, E->getLHS()))
   1403       Info.EvalStatus.HasSideEffects = true;
   1404 
   1405     return true;
   1406   }
   1407 
   1408   if (E->isLogicalOp()) {
   1409     // These need to be handled specially because the operands aren't
   1410     // necessarily integral
   1411     bool lhsResult, rhsResult;
   1412 
   1413     if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
   1414       // We were able to evaluate the LHS, see if we can get away with not
   1415       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
   1416       if (lhsResult == (E->getOpcode() == BO_LOr))
   1417         return Success(lhsResult, E);
   1418 
   1419       if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
   1420         if (E->getOpcode() == BO_LOr)
   1421           return Success(lhsResult || rhsResult, E);
   1422         else
   1423           return Success(lhsResult && rhsResult, E);
   1424       }
   1425     } else {
   1426       if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
   1427         // We can't evaluate the LHS; however, sometimes the result
   1428         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
   1429         if (rhsResult == (E->getOpcode() == BO_LOr) ||
   1430             !rhsResult == (E->getOpcode() == BO_LAnd)) {
   1431           // Since we weren't able to evaluate the left hand side, it
   1432           // must have had side effects.
   1433           Info.EvalStatus.HasSideEffects = true;
   1434 
   1435           return Success(rhsResult, E);
   1436         }
   1437       }
   1438     }
   1439 
   1440     return false;
   1441   }
   1442 
   1443   QualType LHSTy = E->getLHS()->getType();
   1444   QualType RHSTy = E->getRHS()->getType();
   1445 
   1446   if (LHSTy->isAnyComplexType()) {
   1447     assert(RHSTy->isAnyComplexType() && "Invalid comparison");
   1448     ComplexValue LHS, RHS;
   1449 
   1450     if (!EvaluateComplex(E->getLHS(), LHS, Info))
   1451       return false;
   1452 
   1453     if (!EvaluateComplex(E->getRHS(), RHS, Info))
   1454       return false;
   1455 
   1456     if (LHS.isComplexFloat()) {
   1457       APFloat::cmpResult CR_r =
   1458         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
   1459       APFloat::cmpResult CR_i =
   1460         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
   1461 
   1462       if (E->getOpcode() == BO_EQ)
   1463         return Success((CR_r == APFloat::cmpEqual &&
   1464                         CR_i == APFloat::cmpEqual), E);
   1465       else {
   1466         assert(E->getOpcode() == BO_NE &&
   1467                "Invalid complex comparison.");
   1468         return Success(((CR_r == APFloat::cmpGreaterThan ||
   1469                          CR_r == APFloat::cmpLessThan ||
   1470                          CR_r == APFloat::cmpUnordered) ||
   1471                         (CR_i == APFloat::cmpGreaterThan ||
   1472                          CR_i == APFloat::cmpLessThan ||
   1473                          CR_i == APFloat::cmpUnordered)), E);
   1474       }
   1475     } else {
   1476       if (E->getOpcode() == BO_EQ)
   1477         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
   1478                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
   1479       else {
   1480         assert(E->getOpcode() == BO_NE &&
   1481                "Invalid compex comparison.");
   1482         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
   1483                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
   1484       }
   1485     }
   1486   }
   1487 
   1488   if (LHSTy->isRealFloatingType() &&
   1489       RHSTy->isRealFloatingType()) {
   1490     APFloat RHS(0.0), LHS(0.0);
   1491 
   1492     if (!EvaluateFloat(E->getRHS(), RHS, Info))
   1493       return false;
   1494 
   1495     if (!EvaluateFloat(E->getLHS(), LHS, Info))
   1496       return false;
   1497 
   1498     APFloat::cmpResult CR = LHS.compare(RHS);
   1499 
   1500     switch (E->getOpcode()) {
   1501     default:
   1502       llvm_unreachable("Invalid binary operator!");
   1503     case BO_LT:
   1504       return Success(CR == APFloat::cmpLessThan, E);
   1505     case BO_GT:
   1506       return Success(CR == APFloat::cmpGreaterThan, E);
   1507     case BO_LE:
   1508       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
   1509     case BO_GE:
   1510       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
   1511                      E);
   1512     case BO_EQ:
   1513       return Success(CR == APFloat::cmpEqual, E);
   1514     case BO_NE:
   1515       return Success(CR == APFloat::cmpGreaterThan
   1516                      || CR == APFloat::cmpLessThan
   1517                      || CR == APFloat::cmpUnordered, E);
   1518     }
   1519   }
   1520 
   1521   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
   1522     if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
   1523       LValue LHSValue;
   1524       if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
   1525         return false;
   1526 
   1527       LValue RHSValue;
   1528       if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
   1529         return false;
   1530 
   1531       // Reject any bases from the normal codepath; we special-case comparisons
   1532       // to null.
   1533       if (LHSValue.getLValueBase()) {
   1534         if (!E->isEqualityOp())
   1535           return false;
   1536         if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
   1537           return false;
   1538         bool bres;
   1539         if (!EvalPointerValueAsBool(LHSValue, bres))
   1540           return false;
   1541         return Success(bres ^ (E->getOpcode() == BO_EQ), E);
   1542       } else if (RHSValue.getLValueBase()) {
   1543         if (!E->isEqualityOp())
   1544           return false;
   1545         if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
   1546           return false;
   1547         bool bres;
   1548         if (!EvalPointerValueAsBool(RHSValue, bres))
   1549           return false;
   1550         return Success(bres ^ (E->getOpcode() == BO_EQ), E);
   1551       }
   1552 
   1553       if (E->getOpcode() == BO_Sub) {
   1554         QualType Type = E->getLHS()->getType();
   1555         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
   1556 
   1557         CharUnits ElementSize = CharUnits::One();
   1558         if (!ElementType->isVoidType() && !ElementType->isFunctionType())
   1559           ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
   1560 
   1561         CharUnits Diff = LHSValue.getLValueOffset() -
   1562                              RHSValue.getLValueOffset();
   1563         return Success(Diff / ElementSize, E);
   1564       }
   1565       bool Result;
   1566       if (E->getOpcode() == BO_EQ) {
   1567         Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
   1568       } else {
   1569         Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
   1570       }
   1571       return Success(Result, E);
   1572     }
   1573   }
   1574   if (!LHSTy->isIntegralOrEnumerationType() ||
   1575       !RHSTy->isIntegralOrEnumerationType()) {
   1576     // We can't continue from here for non-integral types, and they
   1577     // could potentially confuse the following operations.
   1578     return false;
   1579   }
   1580 
   1581   // The LHS of a constant expr is always evaluated and needed.
   1582   if (!Visit(E->getLHS()))
   1583     return false; // error in subexpression.
   1584 
   1585   APValue RHSVal;
   1586   if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
   1587     return false;
   1588 
   1589   // Handle cases like (unsigned long)&a + 4.
   1590   if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
   1591     CharUnits Offset = Result.getLValueOffset();
   1592     CharUnits AdditionalOffset = CharUnits::fromQuantity(
   1593                                      RHSVal.getInt().getZExtValue());
   1594     if (E->getOpcode() == BO_Add)
   1595       Offset += AdditionalOffset;
   1596     else
   1597       Offset -= AdditionalOffset;
   1598     Result = APValue(Result.getLValueBase(), Offset);
   1599     return true;
   1600   }
   1601 
   1602   // Handle cases like 4 + (unsigned long)&a
   1603   if (E->getOpcode() == BO_Add &&
   1604         RHSVal.isLValue() && Result.isInt()) {
   1605     CharUnits Offset = RHSVal.getLValueOffset();
   1606     Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
   1607     Result = APValue(RHSVal.getLValueBase(), Offset);
   1608     return true;
   1609   }
   1610 
   1611   // All the following cases expect both operands to be an integer
   1612   if (!Result.isInt() || !RHSVal.isInt())
   1613     return false;
   1614 
   1615   APSInt& RHS = RHSVal.getInt();
   1616 
   1617   switch (E->getOpcode()) {
   1618   default:
   1619     return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
   1620   case BO_Mul: return Success(Result.getInt() * RHS, E);
   1621   case BO_Add: return Success(Result.getInt() + RHS, E);
   1622   case BO_Sub: return Success(Result.getInt() - RHS, E);
   1623   case BO_And: return Success(Result.getInt() & RHS, E);
   1624   case BO_Xor: return Success(Result.getInt() ^ RHS, E);
   1625   case BO_Or:  return Success(Result.getInt() | RHS, E);
   1626   case BO_Div:
   1627     if (RHS == 0)
   1628       return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
   1629     return Success(Result.getInt() / RHS, E);
   1630   case BO_Rem:
   1631     if (RHS == 0)
   1632       return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
   1633     return Success(Result.getInt() % RHS, E);
   1634   case BO_Shl: {
   1635     // During constant-folding, a negative shift is an opposite shift.
   1636     if (RHS.isSigned() && RHS.isNegative()) {
   1637       RHS = -RHS;
   1638       goto shift_right;
   1639     }
   1640 
   1641   shift_left:
   1642     unsigned SA
   1643       = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
   1644     return Success(Result.getInt() << SA, E);
   1645   }
   1646   case BO_Shr: {
   1647     // During constant-folding, a negative shift is an opposite shift.
   1648     if (RHS.isSigned() && RHS.isNegative()) {
   1649       RHS = -RHS;
   1650       goto shift_left;
   1651     }
   1652 
   1653   shift_right:
   1654     unsigned SA =
   1655       (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
   1656     return Success(Result.getInt() >> SA, E);
   1657   }
   1658 
   1659   case BO_LT: return Success(Result.getInt() < RHS, E);
   1660   case BO_GT: return Success(Result.getInt() > RHS, E);
   1661   case BO_LE: return Success(Result.getInt() <= RHS, E);
   1662   case BO_GE: return Success(Result.getInt() >= RHS, E);
   1663   case BO_EQ: return Success(Result.getInt() == RHS, E);
   1664   case BO_NE: return Success(Result.getInt() != RHS, E);
   1665   }
   1666 }
   1667 
   1668 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
   1669   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
   1670   //   the result is the size of the referenced type."
   1671   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
   1672   //   result shall be the alignment of the referenced type."
   1673   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
   1674     T = Ref->getPointeeType();
   1675 
   1676   // __alignof is defined to return the preferred alignment.
   1677   return Info.Ctx.toCharUnitsFromBits(
   1678     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
   1679 }
   1680 
   1681 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
   1682   E = E->IgnoreParens();
   1683 
   1684   // alignof decl is always accepted, even if it doesn't make sense: we default
   1685   // to 1 in those cases.
   1686   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
   1687     return Info.Ctx.getDeclAlign(DRE->getDecl(),
   1688                                  /*RefAsPointee*/true);
   1689 
   1690   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
   1691     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
   1692                                  /*RefAsPointee*/true);
   1693 
   1694   return GetAlignOfType(E->getType());
   1695 }
   1696 
   1697 
   1698 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
   1699 /// a result as the expression's type.
   1700 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
   1701                                     const UnaryExprOrTypeTraitExpr *E) {
   1702   switch(E->getKind()) {
   1703   case UETT_AlignOf: {
   1704     if (E->isArgumentType())
   1705       return Success(GetAlignOfType(E->getArgumentType()), E);
   1706     else
   1707       return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
   1708   }
   1709 
   1710   case UETT_VecStep: {
   1711     QualType Ty = E->getTypeOfArgument();
   1712 
   1713     if (Ty->isVectorType()) {
   1714       unsigned n = Ty->getAs<VectorType>()->getNumElements();
   1715 
   1716       // The vec_step built-in functions that take a 3-component
   1717       // vector return 4. (OpenCL 1.1 spec 6.11.12)
   1718       if (n == 3)
   1719         n = 4;
   1720 
   1721       return Success(n, E);
   1722     } else
   1723       return Success(1, E);
   1724   }
   1725 
   1726   case UETT_SizeOf: {
   1727     QualType SrcTy = E->getTypeOfArgument();
   1728     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
   1729     //   the result is the size of the referenced type."
   1730     // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
   1731     //   result shall be the alignment of the referenced type."
   1732     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
   1733       SrcTy = Ref->getPointeeType();
   1734 
   1735     // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
   1736     // extension.
   1737     if (SrcTy->isVoidType() || SrcTy->isFunctionType())
   1738       return Success(1, E);
   1739 
   1740     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
   1741     if (!SrcTy->isConstantSizeType())
   1742       return false;
   1743 
   1744     // Get information about the size.
   1745     return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
   1746   }
   1747   }
   1748 
   1749   llvm_unreachable("unknown expr/type trait");
   1750   return false;
   1751 }
   1752 
   1753 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
   1754   CharUnits Result;
   1755   unsigned n = OOE->getNumComponents();
   1756   if (n == 0)
   1757     return false;
   1758   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
   1759   for (unsigned i = 0; i != n; ++i) {
   1760     OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
   1761     switch (ON.getKind()) {
   1762     case OffsetOfExpr::OffsetOfNode::Array: {
   1763       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
   1764       APSInt IdxResult;
   1765       if (!EvaluateInteger(Idx, IdxResult, Info))
   1766         return false;
   1767       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
   1768       if (!AT)
   1769         return false;
   1770       CurrentType = AT->getElementType();
   1771       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
   1772       Result += IdxResult.getSExtValue() * ElementSize;
   1773         break;
   1774     }
   1775 
   1776     case OffsetOfExpr::OffsetOfNode::Field: {
   1777       FieldDecl *MemberDecl = ON.getField();
   1778       const RecordType *RT = CurrentType->getAs<RecordType>();
   1779       if (!RT)
   1780         return false;
   1781       RecordDecl *RD = RT->getDecl();
   1782       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
   1783       unsigned i = MemberDecl->getFieldIndex();
   1784       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
   1785       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
   1786       CurrentType = MemberDecl->getType().getNonReferenceType();
   1787       break;
   1788     }
   1789 
   1790     case OffsetOfExpr::OffsetOfNode::Identifier:
   1791       llvm_unreachable("dependent __builtin_offsetof");
   1792       return false;
   1793 
   1794     case OffsetOfExpr::OffsetOfNode::Base: {
   1795       CXXBaseSpecifier *BaseSpec = ON.getBase();
   1796       if (BaseSpec->isVirtual())
   1797         return false;
   1798 
   1799       // Find the layout of the class whose base we are looking into.
   1800       const RecordType *RT = CurrentType->getAs<RecordType>();
   1801       if (!RT)
   1802         return false;
   1803       RecordDecl *RD = RT->getDecl();
   1804       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
   1805 
   1806       // Find the base class itself.
   1807       CurrentType = BaseSpec->getType();
   1808       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
   1809       if (!BaseRT)
   1810         return false;
   1811 
   1812       // Add the offset to the base.
   1813       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
   1814       break;
   1815     }
   1816     }
   1817   }
   1818   return Success(Result, OOE);
   1819 }
   1820 
   1821 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
   1822   if (E->getOpcode() == UO_LNot) {
   1823     // LNot's operand isn't necessarily an integer, so we handle it specially.
   1824     bool bres;
   1825     if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
   1826       return false;
   1827     return Success(!bres, E);
   1828   }
   1829 
   1830   // Only handle integral operations...
   1831   if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
   1832     return false;
   1833 
   1834   // Get the operand value into 'Result'.
   1835   if (!Visit(E->getSubExpr()))
   1836     return false;
   1837 
   1838   switch (E->getOpcode()) {
   1839   default:
   1840     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
   1841     // See C99 6.6p3.
   1842     return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
   1843   case UO_Extension:
   1844     // FIXME: Should extension allow i-c-e extension expressions in its scope?
   1845     // If so, we could clear the diagnostic ID.
   1846     return true;
   1847   case UO_Plus:
   1848     // The result is always just the subexpr.
   1849     return true;
   1850   case UO_Minus:
   1851     if (!Result.isInt()) return false;
   1852     return Success(-Result.getInt(), E);
   1853   case UO_Not:
   1854     if (!Result.isInt()) return false;
   1855     return Success(~Result.getInt(), E);
   1856   }
   1857 }
   1858 
   1859 /// HandleCast - This is used to evaluate implicit or explicit casts where the
   1860 /// result type is integer.
   1861 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
   1862   const Expr *SubExpr = E->getSubExpr();
   1863   QualType DestType = E->getType();
   1864   QualType SrcType = SubExpr->getType();
   1865 
   1866   switch (E->getCastKind()) {
   1867   case CK_BaseToDerived:
   1868   case CK_DerivedToBase:
   1869   case CK_UncheckedDerivedToBase:
   1870   case CK_Dynamic:
   1871   case CK_ToUnion:
   1872   case CK_ArrayToPointerDecay:
   1873   case CK_FunctionToPointerDecay:
   1874   case CK_NullToPointer:
   1875   case CK_NullToMemberPointer:
   1876   case CK_BaseToDerivedMemberPointer:
   1877   case CK_DerivedToBaseMemberPointer:
   1878   case CK_ConstructorConversion:
   1879   case CK_IntegralToPointer:
   1880   case CK_ToVoid:
   1881   case CK_VectorSplat:
   1882   case CK_IntegralToFloating:
   1883   case CK_FloatingCast:
   1884   case CK_CPointerToObjCPointerCast:
   1885   case CK_BlockPointerToObjCPointerCast:
   1886   case CK_AnyPointerToBlockPointerCast:
   1887   case CK_ObjCObjectLValueCast:
   1888   case CK_FloatingRealToComplex:
   1889   case CK_FloatingComplexToReal:
   1890   case CK_FloatingComplexCast:
   1891   case CK_FloatingComplexToIntegralComplex:
   1892   case CK_IntegralRealToComplex:
   1893   case CK_IntegralComplexCast:
   1894   case CK_IntegralComplexToFloatingComplex:
   1895     llvm_unreachable("invalid cast kind for integral value");
   1896 
   1897   case CK_BitCast:
   1898   case CK_Dependent:
   1899   case CK_GetObjCProperty:
   1900   case CK_LValueBitCast:
   1901   case CK_UserDefinedConversion:
   1902   case CK_ARCProduceObject:
   1903   case CK_ARCConsumeObject:
   1904   case CK_ARCReclaimReturnedObject:
   1905   case CK_ARCExtendBlockObject:
   1906     return false;
   1907 
   1908   case CK_LValueToRValue:
   1909   case CK_NoOp:
   1910     return Visit(E->getSubExpr());
   1911 
   1912   case CK_MemberPointerToBoolean:
   1913   case CK_PointerToBoolean:
   1914   case CK_IntegralToBoolean:
   1915   case CK_FloatingToBoolean:
   1916   case CK_FloatingComplexToBoolean:
   1917   case CK_IntegralComplexToBoolean: {
   1918     bool BoolResult;
   1919     if (!HandleConversionToBool(SubExpr, BoolResult, Info))
   1920       return false;
   1921     return Success(BoolResult, E);
   1922   }
   1923 
   1924   case CK_IntegralCast: {
   1925     if (!Visit(SubExpr))
   1926       return false;
   1927 
   1928     if (!Result.isInt()) {
   1929       // Only allow casts of lvalues if they are lossless.
   1930       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
   1931     }
   1932 
   1933     return Success(HandleIntToIntCast(DestType, SrcType,
   1934                                       Result.getInt(), Info.Ctx), E);
   1935   }
   1936 
   1937   case CK_PointerToIntegral: {
   1938     LValue LV;
   1939     if (!EvaluatePointer(SubExpr, LV, Info))
   1940       return false;
   1941 
   1942     if (LV.getLValueBase()) {
   1943       // Only allow based lvalue casts if they are lossless.
   1944       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
   1945         return false;
   1946 
   1947       LV.moveInto(Result);
   1948       return true;
   1949     }
   1950 
   1951     APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
   1952                                          SrcType);
   1953     return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
   1954   }
   1955 
   1956   case CK_IntegralComplexToReal: {
   1957     ComplexValue C;
   1958     if (!EvaluateComplex(SubExpr, C, Info))
   1959       return false;
   1960     return Success(C.getComplexIntReal(), E);
   1961   }
   1962 
   1963   case CK_FloatingToIntegral: {
   1964     APFloat F(0.0);
   1965     if (!EvaluateFloat(SubExpr, F, Info))
   1966       return false;
   1967 
   1968     return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
   1969   }
   1970   }
   1971 
   1972   llvm_unreachable("unknown cast resulting in integral value");
   1973   return false;
   1974 }
   1975 
   1976 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
   1977   if (E->getSubExpr()->getType()->isAnyComplexType()) {
   1978     ComplexValue LV;
   1979     if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
   1980       return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
   1981     return Success(LV.getComplexIntReal(), E);
   1982   }
   1983 
   1984   return Visit(E->getSubExpr());
   1985 }
   1986 
   1987 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   1988   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
   1989     ComplexValue LV;
   1990     if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
   1991       return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
   1992     return Success(LV.getComplexIntImag(), E);
   1993   }
   1994 
   1995   APValue Scratch;
   1996   if (!Evaluate(Scratch, Info, E->getSubExpr()))
   1997     Info.EvalStatus.HasSideEffects = true;
   1998   return Success(0, E);
   1999 }
   2000 
   2001 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
   2002   return Success(E->getPackLength(), E);
   2003 }
   2004 
   2005 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
   2006   return Success(E->getValue(), E);
   2007 }
   2008 
   2009 //===----------------------------------------------------------------------===//
   2010 // Float Evaluation
   2011 //===----------------------------------------------------------------------===//
   2012 
   2013 namespace {
   2014 class FloatExprEvaluator
   2015   : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
   2016   APFloat &Result;
   2017 public:
   2018   FloatExprEvaluator(EvalInfo &info, APFloat &result)
   2019     : ExprEvaluatorBaseTy(info), Result(result) {}
   2020 
   2021   bool Success(const APValue &V, const Expr *e) {
   2022     Result = V.getFloat();
   2023     return true;
   2024   }
   2025   bool Error(const Stmt *S) {
   2026     return false;
   2027   }
   2028 
   2029   bool ValueInitialization(const Expr *E) {
   2030     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
   2031     return true;
   2032   }
   2033 
   2034   bool VisitCallExpr(const CallExpr *E);
   2035 
   2036   bool VisitUnaryOperator(const UnaryOperator *E);
   2037   bool VisitBinaryOperator(const BinaryOperator *E);
   2038   bool VisitFloatingLiteral(const FloatingLiteral *E);
   2039   bool VisitCastExpr(const CastExpr *E);
   2040 
   2041   bool VisitUnaryReal(const UnaryOperator *E);
   2042   bool VisitUnaryImag(const UnaryOperator *E);
   2043 
   2044   bool VisitDeclRefExpr(const DeclRefExpr *E);
   2045 
   2046   // FIXME: Missing: array subscript of vector, member of vector,
   2047   //                 ImplicitValueInitExpr
   2048 };
   2049 } // end anonymous namespace
   2050 
   2051 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
   2052   assert(E->getType()->isRealFloatingType());
   2053   return FloatExprEvaluator(Info, Result).Visit(E);
   2054 }
   2055 
   2056 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
   2057                                   QualType ResultTy,
   2058                                   const Expr *Arg,
   2059                                   bool SNaN,
   2060                                   llvm::APFloat &Result) {
   2061   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
   2062   if (!S) return false;
   2063 
   2064   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
   2065 
   2066   llvm::APInt fill;
   2067 
   2068   // Treat empty strings as if they were zero.
   2069   if (S->getString().empty())
   2070     fill = llvm::APInt(32, 0);
   2071   else if (S->getString().getAsInteger(0, fill))
   2072     return false;
   2073 
   2074   if (SNaN)
   2075     Result = llvm::APFloat::getSNaN(Sem, false, &fill);
   2076   else
   2077     Result = llvm::APFloat::getQNaN(Sem, false, &fill);
   2078   return true;
   2079 }
   2080 
   2081 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
   2082   switch (E->isBuiltinCall(Info.Ctx)) {
   2083   default:
   2084     return ExprEvaluatorBaseTy::VisitCallExpr(E);
   2085 
   2086   case Builtin::BI__builtin_huge_val:
   2087   case Builtin::BI__builtin_huge_valf:
   2088   case Builtin::BI__builtin_huge_vall:
   2089   case Builtin::BI__builtin_inf:
   2090   case Builtin::BI__builtin_inff:
   2091   case Builtin::BI__builtin_infl: {
   2092     const llvm::fltSemantics &Sem =
   2093       Info.Ctx.getFloatTypeSemantics(E->getType());
   2094     Result = llvm::APFloat::getInf(Sem);
   2095     return true;
   2096   }
   2097 
   2098   case Builtin::BI__builtin_nans:
   2099   case Builtin::BI__builtin_nansf:
   2100   case Builtin::BI__builtin_nansl:
   2101     return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
   2102                                  true, Result);
   2103 
   2104   case Builtin::BI__builtin_nan:
   2105   case Builtin::BI__builtin_nanf:
   2106   case Builtin::BI__builtin_nanl:
   2107     // If this is __builtin_nan() turn this into a nan, otherwise we
   2108     // can't constant fold it.
   2109     return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
   2110                                  false, Result);
   2111 
   2112   case Builtin::BI__builtin_fabs:
   2113   case Builtin::BI__builtin_fabsf:
   2114   case Builtin::BI__builtin_fabsl:
   2115     if (!EvaluateFloat(E->getArg(0), Result, Info))
   2116       return false;
   2117 
   2118     if (Result.isNegative())
   2119       Result.changeSign();
   2120     return true;
   2121 
   2122   case Builtin::BI__builtin_copysign:
   2123   case Builtin::BI__builtin_copysignf:
   2124   case Builtin::BI__builtin_copysignl: {
   2125     APFloat RHS(0.);
   2126     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
   2127         !EvaluateFloat(E->getArg(1), RHS, Info))
   2128       return false;
   2129     Result.copySign(RHS);
   2130     return true;
   2131   }
   2132   }
   2133 }
   2134 
   2135 bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
   2136   if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
   2137     return true;
   2138 
   2139   const Decl *D = E->getDecl();
   2140   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
   2141   const VarDecl *VD = cast<VarDecl>(D);
   2142 
   2143   // Require the qualifiers to be const and not volatile.
   2144   CanQualType T = Info.Ctx.getCanonicalType(E->getType());
   2145   if (!T.isConstQualified() || T.isVolatileQualified())
   2146     return false;
   2147 
   2148   const Expr *Init = VD->getAnyInitializer();
   2149   if (!Init) return false;
   2150 
   2151   if (APValue *V = VD->getEvaluatedValue()) {
   2152     if (V->isFloat()) {
   2153       Result = V->getFloat();
   2154       return true;
   2155     }
   2156     return false;
   2157   }
   2158 
   2159   if (VD->isEvaluatingValue())
   2160     return false;
   2161 
   2162   VD->setEvaluatingValue();
   2163 
   2164   Expr::EvalResult InitResult;
   2165   if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
   2166       InitResult.Val.isFloat()) {
   2167     // Cache the evaluated value in the variable declaration.
   2168     Result = InitResult.Val.getFloat();
   2169     VD->setEvaluatedValue(InitResult.Val);
   2170     return true;
   2171   }
   2172 
   2173   VD->setEvaluatedValue(APValue());
   2174   return false;
   2175 }
   2176 
   2177 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
   2178   if (E->getSubExpr()->getType()->isAnyComplexType()) {
   2179     ComplexValue CV;
   2180     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
   2181       return false;
   2182     Result = CV.FloatReal;
   2183     return true;
   2184   }
   2185 
   2186   return Visit(E->getSubExpr());
   2187 }
   2188 
   2189 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   2190   if (E->getSubExpr()->getType()->isAnyComplexType()) {
   2191     ComplexValue CV;
   2192     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
   2193       return false;
   2194     Result = CV.FloatImag;
   2195     return true;
   2196   }
   2197 
   2198   APValue Scratch;
   2199   if (!Evaluate(Scratch, Info, E->getSubExpr()))
   2200     Info.EvalStatus.HasSideEffects = true;
   2201   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
   2202   Result = llvm::APFloat::getZero(Sem);
   2203   return true;
   2204 }
   2205 
   2206 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
   2207   if (E->getOpcode() == UO_Deref)
   2208     return false;
   2209 
   2210   if (!EvaluateFloat(E->getSubExpr(), Result, Info))
   2211     return false;
   2212 
   2213   switch (E->getOpcode()) {
   2214   default: return false;
   2215   case UO_Plus:
   2216     return true;
   2217   case UO_Minus:
   2218     Result.changeSign();
   2219     return true;
   2220   }
   2221 }
   2222 
   2223 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   2224   if (E->getOpcode() == BO_Comma) {
   2225     if (!EvaluateFloat(E->getRHS(), Result, Info))
   2226       return false;
   2227 
   2228     // If we can't evaluate the LHS, it might have side effects;
   2229     // conservatively mark it.
   2230     APValue Scratch;
   2231     if (!Evaluate(Scratch, Info, E->getLHS()))
   2232       Info.EvalStatus.HasSideEffects = true;
   2233 
   2234     return true;
   2235   }
   2236 
   2237   // We can't evaluate pointer-to-member operations.
   2238   if (E->isPtrMemOp())
   2239     return false;
   2240 
   2241   // FIXME: Diagnostics?  I really don't understand how the warnings
   2242   // and errors are supposed to work.
   2243   APFloat RHS(0.0);
   2244   if (!EvaluateFloat(E->getLHS(), Result, Info))
   2245     return false;
   2246   if (!EvaluateFloat(E->getRHS(), RHS, Info))
   2247     return false;
   2248 
   2249   switch (E->getOpcode()) {
   2250   default: return false;
   2251   case BO_Mul:
   2252     Result.multiply(RHS, APFloat::rmNearestTiesToEven);
   2253     return true;
   2254   case BO_Add:
   2255     Result.add(RHS, APFloat::rmNearestTiesToEven);
   2256     return true;
   2257   case BO_Sub:
   2258     Result.subtract(RHS, APFloat::rmNearestTiesToEven);
   2259     return true;
   2260   case BO_Div:
   2261     Result.divide(RHS, APFloat::rmNearestTiesToEven);
   2262     return true;
   2263   }
   2264 }
   2265 
   2266 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
   2267   Result = E->getValue();
   2268   return true;
   2269 }
   2270 
   2271 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
   2272   const Expr* SubExpr = E->getSubExpr();
   2273 
   2274   switch (E->getCastKind()) {
   2275   default:
   2276     return false;
   2277 
   2278   case CK_LValueToRValue:
   2279   case CK_NoOp:
   2280     return Visit(SubExpr);
   2281 
   2282   case CK_IntegralToFloating: {
   2283     APSInt IntResult;
   2284     if (!EvaluateInteger(SubExpr, IntResult, Info))
   2285       return false;
   2286     Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
   2287                                   IntResult, Info.Ctx);
   2288     return true;
   2289   }
   2290 
   2291   case CK_FloatingCast: {
   2292     if (!Visit(SubExpr))
   2293       return false;
   2294     Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
   2295                                     Result, Info.Ctx);
   2296     return true;
   2297   }
   2298 
   2299   case CK_FloatingComplexToReal: {
   2300     ComplexValue V;
   2301     if (!EvaluateComplex(SubExpr, V, Info))
   2302       return false;
   2303     Result = V.getComplexFloatReal();
   2304     return true;
   2305   }
   2306   }
   2307 
   2308   return false;
   2309 }
   2310 
   2311 //===----------------------------------------------------------------------===//
   2312 // Complex Evaluation (for float and integer)
   2313 //===----------------------------------------------------------------------===//
   2314 
   2315 namespace {
   2316 class ComplexExprEvaluator
   2317   : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
   2318   ComplexValue &Result;
   2319 
   2320 public:
   2321   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
   2322     : ExprEvaluatorBaseTy(info), Result(Result) {}
   2323 
   2324   bool Success(const APValue &V, const Expr *e) {
   2325     Result.setFrom(V);
   2326     return true;
   2327   }
   2328   bool Error(const Expr *E) {
   2329     return false;
   2330   }
   2331 
   2332   //===--------------------------------------------------------------------===//
   2333   //                            Visitor Methods
   2334   //===--------------------------------------------------------------------===//
   2335 
   2336   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
   2337 
   2338   bool VisitCastExpr(const CastExpr *E);
   2339 
   2340   bool VisitBinaryOperator(const BinaryOperator *E);
   2341   bool VisitUnaryOperator(const UnaryOperator *E);
   2342   // FIXME Missing: ImplicitValueInitExpr, InitListExpr
   2343 };
   2344 } // end anonymous namespace
   2345 
   2346 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
   2347                             EvalInfo &Info) {
   2348   assert(E->getType()->isAnyComplexType());
   2349   return ComplexExprEvaluator(Info, Result).Visit(E);
   2350 }
   2351 
   2352 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
   2353   const Expr* SubExpr = E->getSubExpr();
   2354 
   2355   if (SubExpr->getType()->isRealFloatingType()) {
   2356     Result.makeComplexFloat();
   2357     APFloat &Imag = Result.FloatImag;
   2358     if (!EvaluateFloat(SubExpr, Imag, Info))
   2359       return false;
   2360 
   2361     Result.FloatReal = APFloat(Imag.getSemantics());
   2362     return true;
   2363   } else {
   2364     assert(SubExpr->getType()->isIntegerType() &&
   2365            "Unexpected imaginary literal.");
   2366 
   2367     Result.makeComplexInt();
   2368     APSInt &Imag = Result.IntImag;
   2369     if (!EvaluateInteger(SubExpr, Imag, Info))
   2370       return false;
   2371 
   2372     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
   2373     return true;
   2374   }
   2375 }
   2376 
   2377 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
   2378 
   2379   switch (E->getCastKind()) {
   2380   case CK_BitCast:
   2381   case CK_BaseToDerived:
   2382   case CK_DerivedToBase:
   2383   case CK_UncheckedDerivedToBase:
   2384   case CK_Dynamic:
   2385   case CK_ToUnion:
   2386   case CK_ArrayToPointerDecay:
   2387   case CK_FunctionToPointerDecay:
   2388   case CK_NullToPointer:
   2389   case CK_NullToMemberPointer:
   2390   case CK_BaseToDerivedMemberPointer:
   2391   case CK_DerivedToBaseMemberPointer:
   2392   case CK_MemberPointerToBoolean:
   2393   case CK_ConstructorConversion:
   2394   case CK_IntegralToPointer:
   2395   case CK_PointerToIntegral:
   2396   case CK_PointerToBoolean:
   2397   case CK_ToVoid:
   2398   case CK_VectorSplat:
   2399   case CK_IntegralCast:
   2400   case CK_IntegralToBoolean:
   2401   case CK_IntegralToFloating:
   2402   case CK_FloatingToIntegral:
   2403   case CK_FloatingToBoolean:
   2404   case CK_FloatingCast:
   2405   case CK_CPointerToObjCPointerCast:
   2406   case CK_BlockPointerToObjCPointerCast:
   2407   case CK_AnyPointerToBlockPointerCast:
   2408   case CK_ObjCObjectLValueCast:
   2409   case CK_FloatingComplexToReal:
   2410   case CK_FloatingComplexToBoolean:
   2411   case CK_IntegralComplexToReal:
   2412   case CK_IntegralComplexToBoolean:
   2413   case CK_ARCProduceObject:
   2414   case CK_ARCConsumeObject:
   2415   case CK_ARCReclaimReturnedObject:
   2416   case CK_ARCExtendBlockObject:
   2417     llvm_unreachable("invalid cast kind for complex value");
   2418 
   2419   case CK_LValueToRValue:
   2420   case CK_NoOp:
   2421     return Visit(E->getSubExpr());
   2422 
   2423   case CK_Dependent:
   2424   case CK_GetObjCProperty:
   2425   case CK_LValueBitCast:
   2426   case CK_UserDefinedConversion:
   2427     return false;
   2428 
   2429   case CK_FloatingRealToComplex: {
   2430     APFloat &Real = Result.FloatReal;
   2431     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
   2432       return false;
   2433 
   2434     Result.makeComplexFloat();
   2435     Result.FloatImag = APFloat(Real.getSemantics());
   2436     return true;
   2437   }
   2438 
   2439   case CK_FloatingComplexCast: {
   2440     if (!Visit(E->getSubExpr()))
   2441       return false;
   2442 
   2443     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   2444     QualType From
   2445       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   2446 
   2447     Result.FloatReal
   2448       = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
   2449     Result.FloatImag
   2450       = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
   2451     return true;
   2452   }
   2453 
   2454   case CK_FloatingComplexToIntegralComplex: {
   2455     if (!Visit(E->getSubExpr()))
   2456       return false;
   2457 
   2458     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   2459     QualType From
   2460       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   2461     Result.makeComplexInt();
   2462     Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
   2463     Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
   2464     return true;
   2465   }
   2466 
   2467   case CK_IntegralRealToComplex: {
   2468     APSInt &Real = Result.IntReal;
   2469     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
   2470       return false;
   2471 
   2472     Result.makeComplexInt();
   2473     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
   2474     return true;
   2475   }
   2476 
   2477   case CK_IntegralComplexCast: {
   2478     if (!Visit(E->getSubExpr()))
   2479       return false;
   2480 
   2481     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   2482     QualType From
   2483       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   2484 
   2485     Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
   2486     Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
   2487     return true;
   2488   }
   2489 
   2490   case CK_IntegralComplexToFloatingComplex: {
   2491     if (!Visit(E->getSubExpr()))
   2492       return false;
   2493 
   2494     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   2495     QualType From
   2496       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   2497     Result.makeComplexFloat();
   2498     Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
   2499     Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
   2500     return true;
   2501   }
   2502   }
   2503 
   2504   llvm_unreachable("unknown cast resulting in complex value");
   2505   return false;
   2506 }
   2507 
   2508 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   2509   if (E->getOpcode() == BO_Comma) {
   2510     if (!Visit(E->getRHS()))
   2511       return false;
   2512 
   2513     // If we can't evaluate the LHS, it might have side effects;
   2514     // conservatively mark it.
   2515     APValue Scratch;
   2516     if (!Evaluate(Scratch, Info, E->getLHS()))
   2517       Info.EvalStatus.HasSideEffects = true;
   2518 
   2519     return true;
   2520   }
   2521   if (!Visit(E->getLHS()))
   2522     return false;
   2523 
   2524   ComplexValue RHS;
   2525   if (!EvaluateComplex(E->getRHS(), RHS, Info))
   2526     return false;
   2527 
   2528   assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
   2529          "Invalid operands to binary operator.");
   2530   switch (E->getOpcode()) {
   2531   default: return false;
   2532   case BO_Add:
   2533     if (Result.isComplexFloat()) {
   2534       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
   2535                                        APFloat::rmNearestTiesToEven);
   2536       Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
   2537                                        APFloat::rmNearestTiesToEven);
   2538     } else {
   2539       Result.getComplexIntReal() += RHS.getComplexIntReal();
   2540       Result.getComplexIntImag() += RHS.getComplexIntImag();
   2541     }
   2542     break;
   2543   case BO_Sub:
   2544     if (Result.isComplexFloat()) {
   2545       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
   2546                                             APFloat::rmNearestTiesToEven);
   2547       Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
   2548                                             APFloat::rmNearestTiesToEven);
   2549     } else {
   2550       Result.getComplexIntReal() -= RHS.getComplexIntReal();
   2551       Result.getComplexIntImag() -= RHS.getComplexIntImag();
   2552     }
   2553     break;
   2554   case BO_Mul:
   2555     if (Result.isComplexFloat()) {
   2556       ComplexValue LHS = Result;
   2557       APFloat &LHS_r = LHS.getComplexFloatReal();
   2558       APFloat &LHS_i = LHS.getComplexFloatImag();
   2559       APFloat &RHS_r = RHS.getComplexFloatReal();
   2560       APFloat &RHS_i = RHS.getComplexFloatImag();
   2561 
   2562       APFloat Tmp = LHS_r;
   2563       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
   2564       Result.getComplexFloatReal() = Tmp;
   2565       Tmp = LHS_i;
   2566       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
   2567       Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
   2568 
   2569       Tmp = LHS_r;
   2570       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
   2571       Result.getComplexFloatImag() = Tmp;
   2572       Tmp = LHS_i;
   2573       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
   2574       Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
   2575     } else {
   2576       ComplexValue LHS = Result;
   2577       Result.getComplexIntReal() =
   2578         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
   2579          LHS.getComplexIntImag() * RHS.getComplexIntImag());
   2580       Result.getComplexIntImag() =
   2581         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
   2582          LHS.getComplexIntImag() * RHS.getComplexIntReal());
   2583     }
   2584     break;
   2585   case BO_Div:
   2586     if (Result.isComplexFloat()) {
   2587       ComplexValue LHS = Result;
   2588       APFloat &LHS_r = LHS.getComplexFloatReal();
   2589       APFloat &LHS_i = LHS.getComplexFloatImag();
   2590       APFloat &RHS_r = RHS.getComplexFloatReal();
   2591       APFloat &RHS_i = RHS.getComplexFloatImag();
   2592       APFloat &Res_r = Result.getComplexFloatReal();
   2593       APFloat &Res_i = Result.getComplexFloatImag();
   2594 
   2595       APFloat Den = RHS_r;
   2596       Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
   2597       APFloat Tmp = RHS_i;
   2598       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
   2599       Den.add(Tmp, APFloat::rmNearestTiesToEven);
   2600 
   2601       Res_r = LHS_r;
   2602       Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
   2603       Tmp = LHS_i;
   2604       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
   2605       Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
   2606       Res_r.divide(Den, APFloat::rmNearestTiesToEven);
   2607 
   2608       Res_i = LHS_i;
   2609       Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
   2610       Tmp = LHS_r;
   2611       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
   2612       Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
   2613       Res_i.divide(Den, APFloat::rmNearestTiesToEven);
   2614     } else {
   2615       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
   2616         // FIXME: what about diagnostics?
   2617         return false;
   2618       }
   2619       ComplexValue LHS = Result;
   2620       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
   2621         RHS.getComplexIntImag() * RHS.getComplexIntImag();
   2622       Result.getComplexIntReal() =
   2623         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
   2624          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
   2625       Result.getComplexIntImag() =
   2626         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
   2627          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
   2628     }
   2629     break;
   2630   }
   2631 
   2632   return true;
   2633 }
   2634 
   2635 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
   2636   // Get the operand value into 'Result'.
   2637   if (!Visit(E->getSubExpr()))
   2638     return false;
   2639 
   2640   switch (E->getOpcode()) {
   2641   default:
   2642     // FIXME: what about diagnostics?
   2643     return false;
   2644   case UO_Extension:
   2645     return true;
   2646   case UO_Plus:
   2647     // The result is always just the subexpr.
   2648     return true;
   2649   case UO_Minus:
   2650     if (Result.isComplexFloat()) {
   2651       Result.getComplexFloatReal().changeSign();
   2652       Result.getComplexFloatImag().changeSign();
   2653     }
   2654     else {
   2655       Result.getComplexIntReal() = -Result.getComplexIntReal();
   2656       Result.getComplexIntImag() = -Result.getComplexIntImag();
   2657     }
   2658     return true;
   2659   case UO_Not:
   2660     if (Result.isComplexFloat())
   2661       Result.getComplexFloatImag().changeSign();
   2662     else
   2663       Result.getComplexIntImag() = -Result.getComplexIntImag();
   2664     return true;
   2665   }
   2666 }
   2667 
   2668 //===----------------------------------------------------------------------===//
   2669 // Top level Expr::Evaluate method.
   2670 //===----------------------------------------------------------------------===//
   2671 
   2672 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
   2673   if (E->getType()->isVectorType()) {
   2674     if (!EvaluateVector(E, Result, Info))
   2675       return false;
   2676   } else if (E->getType()->isIntegralOrEnumerationType()) {
   2677     if (!IntExprEvaluator(Info, Result).Visit(E))
   2678       return false;
   2679     if (Result.isLValue() &&
   2680         !IsGlobalLValue(Result.getLValueBase()))
   2681       return false;
   2682   } else if (E->getType()->hasPointerRepresentation()) {
   2683     LValue LV;
   2684     if (!EvaluatePointer(E, LV, Info))
   2685       return false;
   2686     if (!IsGlobalLValue(LV.Base))
   2687       return false;
   2688     LV.moveInto(Result);
   2689   } else if (E->getType()->isRealFloatingType()) {
   2690     llvm::APFloat F(0.0);
   2691     if (!EvaluateFloat(E, F, Info))
   2692       return false;
   2693 
   2694     Result = APValue(F);
   2695   } else if (E->getType()->isAnyComplexType()) {
   2696     ComplexValue C;
   2697     if (!EvaluateComplex(E, C, Info))
   2698       return false;
   2699     C.moveInto(Result);
   2700   } else
   2701     return false;
   2702 
   2703   return true;
   2704 }
   2705 
   2706 /// Evaluate - Return true if this is a constant which we can fold using
   2707 /// any crazy technique (that has nothing to do with language standards) that
   2708 /// we want to.  If this function returns true, it returns the folded constant
   2709 /// in Result.
   2710 bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
   2711   EvalInfo Info(Ctx, Result);
   2712   return ::Evaluate(Result.Val, Info, this);
   2713 }
   2714 
   2715 bool Expr::EvaluateAsBooleanCondition(bool &Result,
   2716                                       const ASTContext &Ctx) const {
   2717   EvalStatus Scratch;
   2718   EvalInfo Info(Ctx, Scratch);
   2719 
   2720   return HandleConversionToBool(this, Result, Info);
   2721 }
   2722 
   2723 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
   2724   EvalStatus Scratch;
   2725   EvalInfo Info(Ctx, Scratch);
   2726 
   2727   return EvaluateInteger(this, Result, Info) && !Scratch.HasSideEffects;
   2728 }
   2729 
   2730 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
   2731   EvalInfo Info(Ctx, Result);
   2732 
   2733   LValue LV;
   2734   if (EvaluateLValue(this, LV, Info) &&
   2735       !Result.HasSideEffects &&
   2736       IsGlobalLValue(LV.Base)) {
   2737     LV.moveInto(Result.Val);
   2738     return true;
   2739   }
   2740   return false;
   2741 }
   2742 
   2743 bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
   2744                                const ASTContext &Ctx) const {
   2745   EvalInfo Info(Ctx, Result);
   2746 
   2747   LValue LV;
   2748   if (EvaluateLValue(this, LV, Info)) {
   2749     LV.moveInto(Result.Val);
   2750     return true;
   2751   }
   2752   return false;
   2753 }
   2754 
   2755 /// isEvaluatable - Call Evaluate to see if this expression can be constant
   2756 /// folded, but discard the result.
   2757 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
   2758   EvalResult Result;
   2759   return Evaluate(Result, Ctx) && !Result.HasSideEffects;
   2760 }
   2761 
   2762 bool Expr::HasSideEffects(const ASTContext &Ctx) const {
   2763   return HasSideEffect(Ctx).Visit(this);
   2764 }
   2765 
   2766 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
   2767   EvalResult EvalResult;
   2768   bool Result = Evaluate(EvalResult, Ctx);
   2769   (void)Result;
   2770   assert(Result && "Could not evaluate expression");
   2771   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
   2772 
   2773   return EvalResult.Val.getInt();
   2774 }
   2775 
   2776  bool Expr::EvalResult::isGlobalLValue() const {
   2777    assert(Val.isLValue());
   2778    return IsGlobalLValue(Val.getLValueBase());
   2779  }
   2780 
   2781 
   2782 /// isIntegerConstantExpr - this recursive routine will test if an expression is
   2783 /// an integer constant expression.
   2784 
   2785 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
   2786 /// comma, etc
   2787 ///
   2788 /// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
   2789 /// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
   2790 /// cast+dereference.
   2791 
   2792 // CheckICE - This function does the fundamental ICE checking: the returned
   2793 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
   2794 // Note that to reduce code duplication, this helper does no evaluation
   2795 // itself; the caller checks whether the expression is evaluatable, and
   2796 // in the rare cases where CheckICE actually cares about the evaluated
   2797 // value, it calls into Evalute.
   2798 //
   2799 // Meanings of Val:
   2800 // 0: This expression is an ICE if it can be evaluated by Evaluate.
   2801 // 1: This expression is not an ICE, but if it isn't evaluated, it's
   2802 //    a legal subexpression for an ICE. This return value is used to handle
   2803 //    the comma operator in C99 mode.
   2804 // 2: This expression is not an ICE, and is not a legal subexpression for one.
   2805 
   2806 namespace {
   2807 
   2808 struct ICEDiag {
   2809   unsigned Val;
   2810   SourceLocation Loc;
   2811 
   2812   public:
   2813   ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
   2814   ICEDiag() : Val(0) {}
   2815 };
   2816 
   2817 }
   2818 
   2819 static ICEDiag NoDiag() { return ICEDiag(); }
   2820 
   2821 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
   2822   Expr::EvalResult EVResult;
   2823   if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
   2824       !EVResult.Val.isInt()) {
   2825     return ICEDiag(2, E->getLocStart());
   2826   }
   2827   return NoDiag();
   2828 }
   2829 
   2830 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
   2831   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
   2832   if (!E->getType()->isIntegralOrEnumerationType()) {
   2833     return ICEDiag(2, E->getLocStart());
   2834   }
   2835 
   2836   switch (E->getStmtClass()) {
   2837 #define ABSTRACT_STMT(Node)
   2838 #define STMT(Node, Base) case Expr::Node##Class:
   2839 #define EXPR(Node, Base)
   2840 #include "clang/AST/StmtNodes.inc"
   2841   case Expr::PredefinedExprClass:
   2842   case Expr::FloatingLiteralClass:
   2843   case Expr::ImaginaryLiteralClass:
   2844   case Expr::StringLiteralClass:
   2845   case Expr::ArraySubscriptExprClass:
   2846   case Expr::MemberExprClass:
   2847   case Expr::CompoundAssignOperatorClass:
   2848   case Expr::CompoundLiteralExprClass:
   2849   case Expr::ExtVectorElementExprClass:
   2850   case Expr::DesignatedInitExprClass:
   2851   case Expr::ImplicitValueInitExprClass:
   2852   case Expr::ParenListExprClass:
   2853   case Expr::VAArgExprClass:
   2854   case Expr::AddrLabelExprClass:
   2855   case Expr::StmtExprClass:
   2856   case Expr::CXXMemberCallExprClass:
   2857   case Expr::CUDAKernelCallExprClass:
   2858   case Expr::CXXDynamicCastExprClass:
   2859   case Expr::CXXTypeidExprClass:
   2860   case Expr::CXXUuidofExprClass:
   2861   case Expr::CXXNullPtrLiteralExprClass:
   2862   case Expr::CXXThisExprClass:
   2863   case Expr::CXXThrowExprClass:
   2864   case Expr::CXXNewExprClass:
   2865   case Expr::CXXDeleteExprClass:
   2866   case Expr::CXXPseudoDestructorExprClass:
   2867   case Expr::UnresolvedLookupExprClass:
   2868   case Expr::DependentScopeDeclRefExprClass:
   2869   case Expr::CXXConstructExprClass:
   2870   case Expr::CXXBindTemporaryExprClass:
   2871   case Expr::ExprWithCleanupsClass:
   2872   case Expr::CXXTemporaryObjectExprClass:
   2873   case Expr::CXXUnresolvedConstructExprClass:
   2874   case Expr::CXXDependentScopeMemberExprClass:
   2875   case Expr::UnresolvedMemberExprClass:
   2876   case Expr::ObjCStringLiteralClass:
   2877   case Expr::ObjCEncodeExprClass:
   2878   case Expr::ObjCMessageExprClass:
   2879   case Expr::ObjCSelectorExprClass:
   2880   case Expr::ObjCProtocolExprClass:
   2881   case Expr::ObjCIvarRefExprClass:
   2882   case Expr::ObjCPropertyRefExprClass:
   2883   case Expr::ObjCIsaExprClass:
   2884   case Expr::ShuffleVectorExprClass:
   2885   case Expr::BlockExprClass:
   2886   case Expr::BlockDeclRefExprClass:
   2887   case Expr::NoStmtClass:
   2888   case Expr::OpaqueValueExprClass:
   2889   case Expr::PackExpansionExprClass:
   2890   case Expr::SubstNonTypeTemplateParmPackExprClass:
   2891   case Expr::AsTypeExprClass:
   2892   case Expr::ObjCIndirectCopyRestoreExprClass:
   2893   case Expr::MaterializeTemporaryExprClass:
   2894   case Expr::AtomicExprClass:
   2895     return ICEDiag(2, E->getLocStart());
   2896 
   2897   case Expr::InitListExprClass:
   2898     if (Ctx.getLangOptions().CPlusPlus0x) {
   2899       const InitListExpr *ILE = cast<InitListExpr>(E);
   2900       if (ILE->getNumInits() == 0)
   2901         return NoDiag();
   2902       if (ILE->getNumInits() == 1)
   2903         return CheckICE(ILE->getInit(0), Ctx);
   2904       // Fall through for more than 1 expression.
   2905     }
   2906     return ICEDiag(2, E->getLocStart());
   2907 
   2908   case Expr::SizeOfPackExprClass:
   2909   case Expr::GNUNullExprClass:
   2910     // GCC considers the GNU __null value to be an integral constant expression.
   2911     return NoDiag();
   2912 
   2913   case Expr::SubstNonTypeTemplateParmExprClass:
   2914     return
   2915       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
   2916 
   2917   case Expr::ParenExprClass:
   2918     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
   2919   case Expr::GenericSelectionExprClass:
   2920     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
   2921   case Expr::IntegerLiteralClass:
   2922   case Expr::CharacterLiteralClass:
   2923   case Expr::CXXBoolLiteralExprClass:
   2924   case Expr::CXXScalarValueInitExprClass:
   2925   case Expr::UnaryTypeTraitExprClass:
   2926   case Expr::BinaryTypeTraitExprClass:
   2927   case Expr::ArrayTypeTraitExprClass:
   2928   case Expr::ExpressionTraitExprClass:
   2929   case Expr::CXXNoexceptExprClass:
   2930     return NoDiag();
   2931   case Expr::CallExprClass:
   2932   case Expr::CXXOperatorCallExprClass: {
   2933     const CallExpr *CE = cast<CallExpr>(E);
   2934     if (CE->isBuiltinCall(Ctx))
   2935       return CheckEvalInICE(E, Ctx);
   2936     return ICEDiag(2, E->getLocStart());
   2937   }
   2938   case Expr::DeclRefExprClass:
   2939     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
   2940       return NoDiag();
   2941     if (Ctx.getLangOptions().CPlusPlus &&
   2942         E->getType().getCVRQualifiers() == Qualifiers::Const) {
   2943       const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
   2944 
   2945       // Parameter variables are never constants.  Without this check,
   2946       // getAnyInitializer() can find a default argument, which leads
   2947       // to chaos.
   2948       if (isa<ParmVarDecl>(D))
   2949         return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
   2950 
   2951       // C++ 7.1.5.1p2
   2952       //   A variable of non-volatile const-qualified integral or enumeration
   2953       //   type initialized by an ICE can be used in ICEs.
   2954       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
   2955         Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
   2956         if (Quals.hasVolatile() || !Quals.hasConst())
   2957           return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
   2958 
   2959         // Look for a declaration of this variable that has an initializer.
   2960         const VarDecl *ID = 0;
   2961         const Expr *Init = Dcl->getAnyInitializer(ID);
   2962         if (Init) {
   2963           if (ID->isInitKnownICE()) {
   2964             // We have already checked whether this subexpression is an
   2965             // integral constant expression.
   2966             if (ID->isInitICE())
   2967               return NoDiag();
   2968             else
   2969               return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
   2970           }
   2971 
   2972           // It's an ICE whether or not the definition we found is
   2973           // out-of-line.  See DR 721 and the discussion in Clang PR
   2974           // 6206 for details.
   2975 
   2976           if (Dcl->isCheckingICE()) {
   2977             return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
   2978           }
   2979 
   2980           Dcl->setCheckingICE();
   2981           ICEDiag Result = CheckICE(Init, Ctx);
   2982           // Cache the result of the ICE test.
   2983           Dcl->setInitKnownICE(Result.Val == 0);
   2984           return Result;
   2985         }
   2986       }
   2987     }
   2988     return ICEDiag(2, E->getLocStart());
   2989   case Expr::UnaryOperatorClass: {
   2990     const UnaryOperator *Exp = cast<UnaryOperator>(E);
   2991     switch (Exp->getOpcode()) {
   2992     case UO_PostInc:
   2993     case UO_PostDec:
   2994     case UO_PreInc:
   2995     case UO_PreDec:
   2996     case UO_AddrOf:
   2997     case UO_Deref:
   2998       return ICEDiag(2, E->getLocStart());
   2999     case UO_Extension:
   3000     case UO_LNot:
   3001     case UO_Plus:
   3002     case UO_Minus:
   3003     case UO_Not:
   3004     case UO_Real:
   3005     case UO_Imag:
   3006       return CheckICE(Exp->getSubExpr(), Ctx);
   3007     }
   3008 
   3009     // OffsetOf falls through here.
   3010   }
   3011   case Expr::OffsetOfExprClass: {
   3012       // Note that per C99, offsetof must be an ICE. And AFAIK, using
   3013       // Evaluate matches the proposed gcc behavior for cases like
   3014       // "offsetof(struct s{int x[4];}, x[!.0])".  This doesn't affect
   3015       // compliance: we should warn earlier for offsetof expressions with
   3016       // array subscripts that aren't ICEs, and if the array subscripts
   3017       // are ICEs, the value of the offsetof must be an integer constant.
   3018       return CheckEvalInICE(E, Ctx);
   3019   }
   3020   case Expr::UnaryExprOrTypeTraitExprClass: {
   3021     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
   3022     if ((Exp->getKind() ==  UETT_SizeOf) &&
   3023         Exp->getTypeOfArgument()->isVariableArrayType())
   3024       return ICEDiag(2, E->getLocStart());
   3025     return NoDiag();
   3026   }
   3027   case Expr::BinaryOperatorClass: {
   3028     const BinaryOperator *Exp = cast<BinaryOperator>(E);
   3029     switch (Exp->getOpcode()) {
   3030     case BO_PtrMemD:
   3031     case BO_PtrMemI:
   3032     case BO_Assign:
   3033     case BO_MulAssign:
   3034     case BO_DivAssign:
   3035     case BO_RemAssign:
   3036     case BO_AddAssign:
   3037     case BO_SubAssign:
   3038     case BO_ShlAssign:
   3039     case BO_ShrAssign:
   3040     case BO_AndAssign:
   3041     case BO_XorAssign:
   3042     case BO_OrAssign:
   3043       return ICEDiag(2, E->getLocStart());
   3044 
   3045     case BO_Mul:
   3046     case BO_Div:
   3047     case BO_Rem:
   3048     case BO_Add:
   3049     case BO_Sub:
   3050     case BO_Shl:
   3051     case BO_Shr:
   3052     case BO_LT:
   3053     case BO_GT:
   3054     case BO_LE:
   3055     case BO_GE:
   3056     case BO_EQ:
   3057     case BO_NE:
   3058     case BO_And:
   3059     case BO_Xor:
   3060     case BO_Or:
   3061     case BO_Comma: {
   3062       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
   3063       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
   3064       if (Exp->getOpcode() == BO_Div ||
   3065           Exp->getOpcode() == BO_Rem) {
   3066         // Evaluate gives an error for undefined Div/Rem, so make sure
   3067         // we don't evaluate one.
   3068         if (LHSResult.Val == 0 && RHSResult.Val == 0) {
   3069           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
   3070           if (REval == 0)
   3071             return ICEDiag(1, E->getLocStart());
   3072           if (REval.isSigned() && REval.isAllOnesValue()) {
   3073             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
   3074             if (LEval.isMinSignedValue())
   3075               return ICEDiag(1, E->getLocStart());
   3076           }
   3077         }
   3078       }
   3079       if (Exp->getOpcode() == BO_Comma) {
   3080         if (Ctx.getLangOptions().C99) {
   3081           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
   3082           // if it isn't evaluated.
   3083           if (LHSResult.Val == 0 && RHSResult.Val == 0)
   3084             return ICEDiag(1, E->getLocStart());
   3085         } else {
   3086           // In both C89 and C++, commas in ICEs are illegal.
   3087           return ICEDiag(2, E->getLocStart());
   3088         }
   3089       }
   3090       if (LHSResult.Val >= RHSResult.Val)
   3091         return LHSResult;
   3092       return RHSResult;
   3093     }
   3094     case BO_LAnd:
   3095     case BO_LOr: {
   3096       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
   3097 
   3098       // C++0x [expr.const]p2:
   3099       //   [...] subexpressions of logical AND (5.14), logical OR
   3100       //   (5.15), and condi- tional (5.16) operations that are not
   3101       //   evaluated are not considered.
   3102       if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
   3103         if (Exp->getOpcode() == BO_LAnd &&
   3104             Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
   3105           return LHSResult;
   3106 
   3107         if (Exp->getOpcode() == BO_LOr &&
   3108             Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
   3109           return LHSResult;
   3110       }
   3111 
   3112       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
   3113       if (LHSResult.Val == 0 && RHSResult.Val == 1) {
   3114         // Rare case where the RHS has a comma "side-effect"; we need
   3115         // to actually check the condition to see whether the side
   3116         // with the comma is evaluated.
   3117         if ((Exp->getOpcode() == BO_LAnd) !=
   3118             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
   3119           return RHSResult;
   3120         return NoDiag();
   3121       }
   3122 
   3123       if (LHSResult.Val >= RHSResult.Val)
   3124         return LHSResult;
   3125       return RHSResult;
   3126     }
   3127     }
   3128   }
   3129   case Expr::ImplicitCastExprClass:
   3130   case Expr::CStyleCastExprClass:
   3131   case Expr::CXXFunctionalCastExprClass:
   3132   case Expr::CXXStaticCastExprClass:
   3133   case Expr::CXXReinterpretCastExprClass:
   3134   case Expr::CXXConstCastExprClass:
   3135   case Expr::ObjCBridgedCastExprClass: {
   3136     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
   3137     switch (cast<CastExpr>(E)->getCastKind()) {
   3138     case CK_LValueToRValue:
   3139     case CK_NoOp:
   3140     case CK_IntegralToBoolean:
   3141     case CK_IntegralCast:
   3142       return CheckICE(SubExpr, Ctx);
   3143     default:
   3144       if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
   3145         return NoDiag();
   3146       return ICEDiag(2, E->getLocStart());
   3147     }
   3148   }
   3149   case Expr::BinaryConditionalOperatorClass: {
   3150     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
   3151     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
   3152     if (CommonResult.Val == 2) return CommonResult;
   3153     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
   3154     if (FalseResult.Val == 2) return FalseResult;
   3155     if (CommonResult.Val == 1) return CommonResult;
   3156     if (FalseResult.Val == 1 &&
   3157         Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
   3158     return FalseResult;
   3159   }
   3160   case Expr::ConditionalOperatorClass: {
   3161     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
   3162     // If the condition (ignoring parens) is a __builtin_constant_p call,
   3163     // then only the true side is actually considered in an integer constant
   3164     // expression, and it is fully evaluated.  This is an important GNU
   3165     // extension.  See GCC PR38377 for discussion.
   3166     if (const CallExpr *CallCE
   3167         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
   3168       if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
   3169         Expr::EvalResult EVResult;
   3170         if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
   3171             !EVResult.Val.isInt()) {
   3172           return ICEDiag(2, E->getLocStart());
   3173         }
   3174         return NoDiag();
   3175       }
   3176     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
   3177     if (CondResult.Val == 2)
   3178       return CondResult;
   3179 
   3180     // C++0x [expr.const]p2:
   3181     //   subexpressions of [...] conditional (5.16) operations that
   3182     //   are not evaluated are not considered
   3183     bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
   3184       ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
   3185       : false;
   3186     ICEDiag TrueResult = NoDiag();
   3187     if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
   3188       TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
   3189     ICEDiag FalseResult = NoDiag();
   3190     if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
   3191       FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
   3192 
   3193     if (TrueResult.Val == 2)
   3194       return TrueResult;
   3195     if (FalseResult.Val == 2)
   3196       return FalseResult;
   3197     if (CondResult.Val == 1)
   3198       return CondResult;
   3199     if (TrueResult.Val == 0 && FalseResult.Val == 0)
   3200       return NoDiag();
   3201     // Rare case where the diagnostics depend on which side is evaluated
   3202     // Note that if we get here, CondResult is 0, and at least one of
   3203     // TrueResult and FalseResult is non-zero.
   3204     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
   3205       return FalseResult;
   3206     }
   3207     return TrueResult;
   3208   }
   3209   case Expr::CXXDefaultArgExprClass:
   3210     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
   3211   case Expr::ChooseExprClass: {
   3212     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
   3213   }
   3214   }
   3215 
   3216   // Silence a GCC warning
   3217   return ICEDiag(2, E->getLocStart());
   3218 }
   3219 
   3220 bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
   3221                                  SourceLocation *Loc, bool isEvaluated) const {
   3222   ICEDiag d = CheckICE(this, Ctx);
   3223   if (d.Val != 0) {
   3224     if (Loc) *Loc = d.Loc;
   3225     return false;
   3226   }
   3227   EvalResult EvalResult;
   3228   if (!Evaluate(EvalResult, Ctx))
   3229     llvm_unreachable("ICE cannot be evaluated!");
   3230   assert(!EvalResult.HasSideEffects && "ICE with side effects!");
   3231   assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
   3232   Result = EvalResult.Val.getInt();
   3233   return true;
   3234 }
   3235