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 // Constant expression evaluation produces four main results:
     13 //
     14 //  * A success/failure flag indicating whether constant folding was successful.
     15 //    This is the 'bool' return value used by most of the code in this file. A
     16 //    'false' return value indicates that constant folding has failed, and any
     17 //    appropriate diagnostic has already been produced.
     18 //
     19 //  * An evaluated result, valid only if constant folding has not failed.
     20 //
     21 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
     22 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
     23 //    where it is possible to determine the evaluated result regardless.
     24 //
     25 //  * A set of notes indicating why the evaluation was not a constant expression
     26 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
     27 //    too, why the expression could not be folded.
     28 //
     29 // If we are checking for a potential constant expression, failure to constant
     30 // fold a potential constant sub-expression will be indicated by a 'false'
     31 // return value (the expression could not be folded) and no diagnostic (the
     32 // expression is not necessarily non-constant).
     33 //
     34 //===----------------------------------------------------------------------===//
     35 
     36 #include "clang/AST/APValue.h"
     37 #include "clang/AST/ASTContext.h"
     38 #include "clang/AST/ASTDiagnostic.h"
     39 #include "clang/AST/ASTLambda.h"
     40 #include "clang/AST/CharUnits.h"
     41 #include "clang/AST/Expr.h"
     42 #include "clang/AST/RecordLayout.h"
     43 #include "clang/AST/StmtVisitor.h"
     44 #include "clang/AST/TypeLoc.h"
     45 #include "clang/Basic/Builtins.h"
     46 #include "clang/Basic/TargetInfo.h"
     47 #include "llvm/ADT/SmallString.h"
     48 #include "llvm/Support/raw_ostream.h"
     49 #include <cstring>
     50 #include <functional>
     51 
     52 using namespace clang;
     53 using llvm::APSInt;
     54 using llvm::APFloat;
     55 
     56 static bool IsGlobalLValue(APValue::LValueBase B);
     57 
     58 namespace {
     59   struct LValue;
     60   struct CallStackFrame;
     61   struct EvalInfo;
     62 
     63   static QualType getType(APValue::LValueBase B) {
     64     if (!B) return QualType();
     65     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
     66       return D->getType();
     67 
     68     const Expr *Base = B.get<const Expr*>();
     69 
     70     // For a materialized temporary, the type of the temporary we materialized
     71     // may not be the type of the expression.
     72     if (const MaterializeTemporaryExpr *MTE =
     73             dyn_cast<MaterializeTemporaryExpr>(Base)) {
     74       SmallVector<const Expr *, 2> CommaLHSs;
     75       SmallVector<SubobjectAdjustment, 2> Adjustments;
     76       const Expr *Temp = MTE->GetTemporaryExpr();
     77       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
     78                                                                Adjustments);
     79       // Keep any cv-qualifiers from the reference if we generated a temporary
     80       // for it.
     81       if (Inner != Temp)
     82         return Inner->getType();
     83     }
     84 
     85     return Base->getType();
     86   }
     87 
     88   /// Get an LValue path entry, which is known to not be an array index, as a
     89   /// field or base class.
     90   static
     91   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
     92     APValue::BaseOrMemberType Value;
     93     Value.setFromOpaqueValue(E.BaseOrMember);
     94     return Value;
     95   }
     96 
     97   /// Get an LValue path entry, which is known to not be an array index, as a
     98   /// field declaration.
     99   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
    100     return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
    101   }
    102   /// Get an LValue path entry, which is known to not be an array index, as a
    103   /// base class declaration.
    104   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
    105     return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
    106   }
    107   /// Determine whether this LValue path entry for a base class names a virtual
    108   /// base class.
    109   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
    110     return getAsBaseOrMember(E).getInt();
    111   }
    112 
    113   /// Find the path length and type of the most-derived subobject in the given
    114   /// path, and find the size of the containing array, if any.
    115   static
    116   unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
    117                                     ArrayRef<APValue::LValuePathEntry> Path,
    118                                     uint64_t &ArraySize, QualType &Type,
    119                                     bool &IsArray) {
    120     unsigned MostDerivedLength = 0;
    121     Type = Base;
    122     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
    123       if (Type->isArrayType()) {
    124         const ConstantArrayType *CAT =
    125           cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
    126         Type = CAT->getElementType();
    127         ArraySize = CAT->getSize().getZExtValue();
    128         MostDerivedLength = I + 1;
    129         IsArray = true;
    130       } else if (Type->isAnyComplexType()) {
    131         const ComplexType *CT = Type->castAs<ComplexType>();
    132         Type = CT->getElementType();
    133         ArraySize = 2;
    134         MostDerivedLength = I + 1;
    135         IsArray = true;
    136       } else if (const FieldDecl *FD = getAsField(Path[I])) {
    137         Type = FD->getType();
    138         ArraySize = 0;
    139         MostDerivedLength = I + 1;
    140         IsArray = false;
    141       } else {
    142         // Path[I] describes a base class.
    143         ArraySize = 0;
    144         IsArray = false;
    145       }
    146     }
    147     return MostDerivedLength;
    148   }
    149 
    150   // The order of this enum is important for diagnostics.
    151   enum CheckSubobjectKind {
    152     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
    153     CSK_This, CSK_Real, CSK_Imag
    154   };
    155 
    156   /// A path from a glvalue to a subobject of that glvalue.
    157   struct SubobjectDesignator {
    158     /// True if the subobject was named in a manner not supported by C++11. Such
    159     /// lvalues can still be folded, but they are not core constant expressions
    160     /// and we cannot perform lvalue-to-rvalue conversions on them.
    161     unsigned Invalid : 1;
    162 
    163     /// Is this a pointer one past the end of an object?
    164     unsigned IsOnePastTheEnd : 1;
    165 
    166     /// Indicator of whether the most-derived object is an array element.
    167     unsigned MostDerivedIsArrayElement : 1;
    168 
    169     /// The length of the path to the most-derived object of which this is a
    170     /// subobject.
    171     unsigned MostDerivedPathLength : 29;
    172 
    173     /// The size of the array of which the most-derived object is an element.
    174     /// This will always be 0 if the most-derived object is not an array
    175     /// element. 0 is not an indicator of whether or not the most-derived object
    176     /// is an array, however, because 0-length arrays are allowed.
    177     uint64_t MostDerivedArraySize;
    178 
    179     /// The type of the most derived object referred to by this address.
    180     QualType MostDerivedType;
    181 
    182     typedef APValue::LValuePathEntry PathEntry;
    183 
    184     /// The entries on the path from the glvalue to the designated subobject.
    185     SmallVector<PathEntry, 8> Entries;
    186 
    187     SubobjectDesignator() : Invalid(true) {}
    188 
    189     explicit SubobjectDesignator(QualType T)
    190         : Invalid(false), IsOnePastTheEnd(false),
    191           MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
    192           MostDerivedArraySize(0), MostDerivedType(T) {}
    193 
    194     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
    195         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
    196           MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
    197           MostDerivedArraySize(0) {
    198       if (!Invalid) {
    199         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
    200         ArrayRef<PathEntry> VEntries = V.getLValuePath();
    201         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
    202         if (V.getLValueBase()) {
    203           bool IsArray = false;
    204           MostDerivedPathLength =
    205               findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
    206                                        V.getLValuePath(), MostDerivedArraySize,
    207                                        MostDerivedType, IsArray);
    208           MostDerivedIsArrayElement = IsArray;
    209         }
    210       }
    211     }
    212 
    213     void setInvalid() {
    214       Invalid = true;
    215       Entries.clear();
    216     }
    217 
    218     /// Determine whether this is a one-past-the-end pointer.
    219     bool isOnePastTheEnd() const {
    220       assert(!Invalid);
    221       if (IsOnePastTheEnd)
    222         return true;
    223       if (MostDerivedIsArrayElement &&
    224           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
    225         return true;
    226       return false;
    227     }
    228 
    229     /// Check that this refers to a valid subobject.
    230     bool isValidSubobject() const {
    231       if (Invalid)
    232         return false;
    233       return !isOnePastTheEnd();
    234     }
    235     /// Check that this refers to a valid subobject, and if not, produce a
    236     /// relevant diagnostic and set the designator as invalid.
    237     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
    238 
    239     /// Update this designator to refer to the first element within this array.
    240     void addArrayUnchecked(const ConstantArrayType *CAT) {
    241       PathEntry Entry;
    242       Entry.ArrayIndex = 0;
    243       Entries.push_back(Entry);
    244 
    245       // This is a most-derived object.
    246       MostDerivedType = CAT->getElementType();
    247       MostDerivedIsArrayElement = true;
    248       MostDerivedArraySize = CAT->getSize().getZExtValue();
    249       MostDerivedPathLength = Entries.size();
    250     }
    251     /// Update this designator to refer to the given base or member of this
    252     /// object.
    253     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
    254       PathEntry Entry;
    255       APValue::BaseOrMemberType Value(D, Virtual);
    256       Entry.BaseOrMember = Value.getOpaqueValue();
    257       Entries.push_back(Entry);
    258 
    259       // If this isn't a base class, it's a new most-derived object.
    260       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
    261         MostDerivedType = FD->getType();
    262         MostDerivedIsArrayElement = false;
    263         MostDerivedArraySize = 0;
    264         MostDerivedPathLength = Entries.size();
    265       }
    266     }
    267     /// Update this designator to refer to the given complex component.
    268     void addComplexUnchecked(QualType EltTy, bool Imag) {
    269       PathEntry Entry;
    270       Entry.ArrayIndex = Imag;
    271       Entries.push_back(Entry);
    272 
    273       // This is technically a most-derived object, though in practice this
    274       // is unlikely to matter.
    275       MostDerivedType = EltTy;
    276       MostDerivedIsArrayElement = true;
    277       MostDerivedArraySize = 2;
    278       MostDerivedPathLength = Entries.size();
    279     }
    280     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
    281     /// Add N to the address of this subobject.
    282     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
    283       if (Invalid) return;
    284       if (MostDerivedPathLength == Entries.size() &&
    285           MostDerivedIsArrayElement) {
    286         Entries.back().ArrayIndex += N;
    287         if (Entries.back().ArrayIndex > MostDerivedArraySize) {
    288           diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
    289           setInvalid();
    290         }
    291         return;
    292       }
    293       // [expr.add]p4: For the purposes of these operators, a pointer to a
    294       // nonarray object behaves the same as a pointer to the first element of
    295       // an array of length one with the type of the object as its element type.
    296       if (IsOnePastTheEnd && N == (uint64_t)-1)
    297         IsOnePastTheEnd = false;
    298       else if (!IsOnePastTheEnd && N == 1)
    299         IsOnePastTheEnd = true;
    300       else if (N != 0) {
    301         diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
    302         setInvalid();
    303       }
    304     }
    305   };
    306 
    307   /// A stack frame in the constexpr call stack.
    308   struct CallStackFrame {
    309     EvalInfo &Info;
    310 
    311     /// Parent - The caller of this stack frame.
    312     CallStackFrame *Caller;
    313 
    314     /// CallLoc - The location of the call expression for this call.
    315     SourceLocation CallLoc;
    316 
    317     /// Callee - The function which was called.
    318     const FunctionDecl *Callee;
    319 
    320     /// Index - The call index of this call.
    321     unsigned Index;
    322 
    323     /// This - The binding for the this pointer in this call, if any.
    324     const LValue *This;
    325 
    326     /// Arguments - Parameter bindings for this function call, indexed by
    327     /// parameters' function scope indices.
    328     APValue *Arguments;
    329 
    330     // Note that we intentionally use std::map here so that references to
    331     // values are stable.
    332     typedef std::map<const void*, APValue> MapTy;
    333     typedef MapTy::const_iterator temp_iterator;
    334     /// Temporaries - Temporary lvalues materialized within this stack frame.
    335     MapTy Temporaries;
    336 
    337     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
    338                    const FunctionDecl *Callee, const LValue *This,
    339                    APValue *Arguments);
    340     ~CallStackFrame();
    341 
    342     APValue *getTemporary(const void *Key) {
    343       MapTy::iterator I = Temporaries.find(Key);
    344       return I == Temporaries.end() ? nullptr : &I->second;
    345     }
    346     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
    347   };
    348 
    349   /// Temporarily override 'this'.
    350   class ThisOverrideRAII {
    351   public:
    352     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
    353         : Frame(Frame), OldThis(Frame.This) {
    354       if (Enable)
    355         Frame.This = NewThis;
    356     }
    357     ~ThisOverrideRAII() {
    358       Frame.This = OldThis;
    359     }
    360   private:
    361     CallStackFrame &Frame;
    362     const LValue *OldThis;
    363   };
    364 
    365   /// A partial diagnostic which we might know in advance that we are not going
    366   /// to emit.
    367   class OptionalDiagnostic {
    368     PartialDiagnostic *Diag;
    369 
    370   public:
    371     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
    372       : Diag(Diag) {}
    373 
    374     template<typename T>
    375     OptionalDiagnostic &operator<<(const T &v) {
    376       if (Diag)
    377         *Diag << v;
    378       return *this;
    379     }
    380 
    381     OptionalDiagnostic &operator<<(const APSInt &I) {
    382       if (Diag) {
    383         SmallVector<char, 32> Buffer;
    384         I.toString(Buffer);
    385         *Diag << StringRef(Buffer.data(), Buffer.size());
    386       }
    387       return *this;
    388     }
    389 
    390     OptionalDiagnostic &operator<<(const APFloat &F) {
    391       if (Diag) {
    392         // FIXME: Force the precision of the source value down so we don't
    393         // print digits which are usually useless (we don't really care here if
    394         // we truncate a digit by accident in edge cases).  Ideally,
    395         // APFloat::toString would automatically print the shortest
    396         // representation which rounds to the correct value, but it's a bit
    397         // tricky to implement.
    398         unsigned precision =
    399             llvm::APFloat::semanticsPrecision(F.getSemantics());
    400         precision = (precision * 59 + 195) / 196;
    401         SmallVector<char, 32> Buffer;
    402         F.toString(Buffer, precision);
    403         *Diag << StringRef(Buffer.data(), Buffer.size());
    404       }
    405       return *this;
    406     }
    407   };
    408 
    409   /// A cleanup, and a flag indicating whether it is lifetime-extended.
    410   class Cleanup {
    411     llvm::PointerIntPair<APValue*, 1, bool> Value;
    412 
    413   public:
    414     Cleanup(APValue *Val, bool IsLifetimeExtended)
    415         : Value(Val, IsLifetimeExtended) {}
    416 
    417     bool isLifetimeExtended() const { return Value.getInt(); }
    418     void endLifetime() {
    419       *Value.getPointer() = APValue();
    420     }
    421   };
    422 
    423   /// EvalInfo - This is a private struct used by the evaluator to capture
    424   /// information about a subexpression as it is folded.  It retains information
    425   /// about the AST context, but also maintains information about the folded
    426   /// expression.
    427   ///
    428   /// If an expression could be evaluated, it is still possible it is not a C
    429   /// "integer constant expression" or constant expression.  If not, this struct
    430   /// captures information about how and why not.
    431   ///
    432   /// One bit of information passed *into* the request for constant folding
    433   /// indicates whether the subexpression is "evaluated" or not according to C
    434   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
    435   /// evaluate the expression regardless of what the RHS is, but C only allows
    436   /// certain things in certain situations.
    437   struct EvalInfo {
    438     ASTContext &Ctx;
    439 
    440     /// EvalStatus - Contains information about the evaluation.
    441     Expr::EvalStatus &EvalStatus;
    442 
    443     /// CurrentCall - The top of the constexpr call stack.
    444     CallStackFrame *CurrentCall;
    445 
    446     /// CallStackDepth - The number of calls in the call stack right now.
    447     unsigned CallStackDepth;
    448 
    449     /// NextCallIndex - The next call index to assign.
    450     unsigned NextCallIndex;
    451 
    452     /// StepsLeft - The remaining number of evaluation steps we're permitted
    453     /// to perform. This is essentially a limit for the number of statements
    454     /// we will evaluate.
    455     unsigned StepsLeft;
    456 
    457     /// BottomFrame - The frame in which evaluation started. This must be
    458     /// initialized after CurrentCall and CallStackDepth.
    459     CallStackFrame BottomFrame;
    460 
    461     /// A stack of values whose lifetimes end at the end of some surrounding
    462     /// evaluation frame.
    463     llvm::SmallVector<Cleanup, 16> CleanupStack;
    464 
    465     /// EvaluatingDecl - This is the declaration whose initializer is being
    466     /// evaluated, if any.
    467     APValue::LValueBase EvaluatingDecl;
    468 
    469     /// EvaluatingDeclValue - This is the value being constructed for the
    470     /// declaration whose initializer is being evaluated, if any.
    471     APValue *EvaluatingDeclValue;
    472 
    473     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
    474     /// notes attached to it will also be stored, otherwise they will not be.
    475     bool HasActiveDiagnostic;
    476 
    477     /// \brief Have we emitted a diagnostic explaining why we couldn't constant
    478     /// fold (not just why it's not strictly a constant expression)?
    479     bool HasFoldFailureDiagnostic;
    480 
    481     /// \brief Whether or not we're currently speculatively evaluating.
    482     bool IsSpeculativelyEvaluating;
    483 
    484     enum EvaluationMode {
    485       /// Evaluate as a constant expression. Stop if we find that the expression
    486       /// is not a constant expression.
    487       EM_ConstantExpression,
    488 
    489       /// Evaluate as a potential constant expression. Keep going if we hit a
    490       /// construct that we can't evaluate yet (because we don't yet know the
    491       /// value of something) but stop if we hit something that could never be
    492       /// a constant expression.
    493       EM_PotentialConstantExpression,
    494 
    495       /// Fold the expression to a constant. Stop if we hit a side-effect that
    496       /// we can't model.
    497       EM_ConstantFold,
    498 
    499       /// Evaluate the expression looking for integer overflow and similar
    500       /// issues. Don't worry about side-effects, and try to visit all
    501       /// subexpressions.
    502       EM_EvaluateForOverflow,
    503 
    504       /// Evaluate in any way we know how. Don't worry about side-effects that
    505       /// can't be modeled.
    506       EM_IgnoreSideEffects,
    507 
    508       /// Evaluate as a constant expression. Stop if we find that the expression
    509       /// is not a constant expression. Some expressions can be retried in the
    510       /// optimizer if we don't constant fold them here, but in an unevaluated
    511       /// context we try to fold them immediately since the optimizer never
    512       /// gets a chance to look at it.
    513       EM_ConstantExpressionUnevaluated,
    514 
    515       /// Evaluate as a potential constant expression. Keep going if we hit a
    516       /// construct that we can't evaluate yet (because we don't yet know the
    517       /// value of something) but stop if we hit something that could never be
    518       /// a constant expression. Some expressions can be retried in the
    519       /// optimizer if we don't constant fold them here, but in an unevaluated
    520       /// context we try to fold them immediately since the optimizer never
    521       /// gets a chance to look at it.
    522       EM_PotentialConstantExpressionUnevaluated,
    523 
    524       /// Evaluate as a constant expression. Continue evaluating if we find a
    525       /// MemberExpr with a base that can't be evaluated.
    526       EM_DesignatorFold,
    527     } EvalMode;
    528 
    529     /// Are we checking whether the expression is a potential constant
    530     /// expression?
    531     bool checkingPotentialConstantExpression() const {
    532       return EvalMode == EM_PotentialConstantExpression ||
    533              EvalMode == EM_PotentialConstantExpressionUnevaluated;
    534     }
    535 
    536     /// Are we checking an expression for overflow?
    537     // FIXME: We should check for any kind of undefined or suspicious behavior
    538     // in such constructs, not just overflow.
    539     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
    540 
    541     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
    542       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
    543         CallStackDepth(0), NextCallIndex(1),
    544         StepsLeft(getLangOpts().ConstexprStepLimit),
    545         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
    546         EvaluatingDecl((const ValueDecl *)nullptr),
    547         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
    548         HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
    549         EvalMode(Mode) {}
    550 
    551     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
    552       EvaluatingDecl = Base;
    553       EvaluatingDeclValue = &Value;
    554     }
    555 
    556     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
    557 
    558     bool CheckCallLimit(SourceLocation Loc) {
    559       // Don't perform any constexpr calls (other than the call we're checking)
    560       // when checking a potential constant expression.
    561       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
    562         return false;
    563       if (NextCallIndex == 0) {
    564         // NextCallIndex has wrapped around.
    565         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
    566         return false;
    567       }
    568       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
    569         return true;
    570       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
    571         << getLangOpts().ConstexprCallDepth;
    572       return false;
    573     }
    574 
    575     CallStackFrame *getCallFrame(unsigned CallIndex) {
    576       assert(CallIndex && "no call index in getCallFrame");
    577       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
    578       // be null in this loop.
    579       CallStackFrame *Frame = CurrentCall;
    580       while (Frame->Index > CallIndex)
    581         Frame = Frame->Caller;
    582       return (Frame->Index == CallIndex) ? Frame : nullptr;
    583     }
    584 
    585     bool nextStep(const Stmt *S) {
    586       if (!StepsLeft) {
    587         FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
    588         return false;
    589       }
    590       --StepsLeft;
    591       return true;
    592     }
    593 
    594   private:
    595     /// Add a diagnostic to the diagnostics list.
    596     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
    597       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
    598       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
    599       return EvalStatus.Diag->back().second;
    600     }
    601 
    602     /// Add notes containing a call stack to the current point of evaluation.
    603     void addCallStack(unsigned Limit);
    604 
    605   private:
    606     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
    607                             unsigned ExtraNotes, bool IsCCEDiag) {
    608 
    609       if (EvalStatus.Diag) {
    610         // If we have a prior diagnostic, it will be noting that the expression
    611         // isn't a constant expression. This diagnostic is more important,
    612         // unless we require this evaluation to produce a constant expression.
    613         //
    614         // FIXME: We might want to show both diagnostics to the user in
    615         // EM_ConstantFold mode.
    616         if (!EvalStatus.Diag->empty()) {
    617           switch (EvalMode) {
    618           case EM_ConstantFold:
    619           case EM_IgnoreSideEffects:
    620           case EM_EvaluateForOverflow:
    621             if (!HasFoldFailureDiagnostic)
    622               break;
    623             // We've already failed to fold something. Keep that diagnostic.
    624           case EM_ConstantExpression:
    625           case EM_PotentialConstantExpression:
    626           case EM_ConstantExpressionUnevaluated:
    627           case EM_PotentialConstantExpressionUnevaluated:
    628           case EM_DesignatorFold:
    629             HasActiveDiagnostic = false;
    630             return OptionalDiagnostic();
    631           }
    632         }
    633 
    634         unsigned CallStackNotes = CallStackDepth - 1;
    635         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
    636         if (Limit)
    637           CallStackNotes = std::min(CallStackNotes, Limit + 1);
    638         if (checkingPotentialConstantExpression())
    639           CallStackNotes = 0;
    640 
    641         HasActiveDiagnostic = true;
    642         HasFoldFailureDiagnostic = !IsCCEDiag;
    643         EvalStatus.Diag->clear();
    644         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
    645         addDiag(Loc, DiagId);
    646         if (!checkingPotentialConstantExpression())
    647           addCallStack(Limit);
    648         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
    649       }
    650       HasActiveDiagnostic = false;
    651       return OptionalDiagnostic();
    652     }
    653   public:
    654     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
    655     OptionalDiagnostic
    656     FFDiag(SourceLocation Loc,
    657           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
    658           unsigned ExtraNotes = 0) {
    659       return Diag(Loc, DiagId, ExtraNotes, false);
    660     }
    661 
    662     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
    663                               = diag::note_invalid_subexpr_in_const_expr,
    664                             unsigned ExtraNotes = 0) {
    665       if (EvalStatus.Diag)
    666         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
    667       HasActiveDiagnostic = false;
    668       return OptionalDiagnostic();
    669     }
    670 
    671     /// Diagnose that the evaluation does not produce a C++11 core constant
    672     /// expression.
    673     ///
    674     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
    675     /// EM_PotentialConstantExpression mode and we produce one of these.
    676     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
    677                                  = diag::note_invalid_subexpr_in_const_expr,
    678                                unsigned ExtraNotes = 0) {
    679       // Don't override a previous diagnostic. Don't bother collecting
    680       // diagnostics if we're evaluating for overflow.
    681       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
    682         HasActiveDiagnostic = false;
    683         return OptionalDiagnostic();
    684       }
    685       return Diag(Loc, DiagId, ExtraNotes, true);
    686     }
    687     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
    688                                  = diag::note_invalid_subexpr_in_const_expr,
    689                                unsigned ExtraNotes = 0) {
    690       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
    691     }
    692     /// Add a note to a prior diagnostic.
    693     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
    694       if (!HasActiveDiagnostic)
    695         return OptionalDiagnostic();
    696       return OptionalDiagnostic(&addDiag(Loc, DiagId));
    697     }
    698 
    699     /// Add a stack of notes to a prior diagnostic.
    700     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
    701       if (HasActiveDiagnostic) {
    702         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
    703                                 Diags.begin(), Diags.end());
    704       }
    705     }
    706 
    707     /// Should we continue evaluation after encountering a side-effect that we
    708     /// couldn't model?
    709     bool keepEvaluatingAfterSideEffect() {
    710       switch (EvalMode) {
    711       case EM_PotentialConstantExpression:
    712       case EM_PotentialConstantExpressionUnevaluated:
    713       case EM_EvaluateForOverflow:
    714       case EM_IgnoreSideEffects:
    715         return true;
    716 
    717       case EM_ConstantExpression:
    718       case EM_ConstantExpressionUnevaluated:
    719       case EM_ConstantFold:
    720       case EM_DesignatorFold:
    721         return false;
    722       }
    723       llvm_unreachable("Missed EvalMode case");
    724     }
    725 
    726     /// Note that we have had a side-effect, and determine whether we should
    727     /// keep evaluating.
    728     bool noteSideEffect() {
    729       EvalStatus.HasSideEffects = true;
    730       return keepEvaluatingAfterSideEffect();
    731     }
    732 
    733     /// Should we continue evaluation after encountering undefined behavior?
    734     bool keepEvaluatingAfterUndefinedBehavior() {
    735       switch (EvalMode) {
    736       case EM_EvaluateForOverflow:
    737       case EM_IgnoreSideEffects:
    738       case EM_ConstantFold:
    739       case EM_DesignatorFold:
    740         return true;
    741 
    742       case EM_PotentialConstantExpression:
    743       case EM_PotentialConstantExpressionUnevaluated:
    744       case EM_ConstantExpression:
    745       case EM_ConstantExpressionUnevaluated:
    746         return false;
    747       }
    748       llvm_unreachable("Missed EvalMode case");
    749     }
    750 
    751     /// Note that we hit something that was technically undefined behavior, but
    752     /// that we can evaluate past it (such as signed overflow or floating-point
    753     /// division by zero.)
    754     bool noteUndefinedBehavior() {
    755       EvalStatus.HasUndefinedBehavior = true;
    756       return keepEvaluatingAfterUndefinedBehavior();
    757     }
    758 
    759     /// Should we continue evaluation as much as possible after encountering a
    760     /// construct which can't be reduced to a value?
    761     bool keepEvaluatingAfterFailure() {
    762       if (!StepsLeft)
    763         return false;
    764 
    765       switch (EvalMode) {
    766       case EM_PotentialConstantExpression:
    767       case EM_PotentialConstantExpressionUnevaluated:
    768       case EM_EvaluateForOverflow:
    769         return true;
    770 
    771       case EM_ConstantExpression:
    772       case EM_ConstantExpressionUnevaluated:
    773       case EM_ConstantFold:
    774       case EM_IgnoreSideEffects:
    775       case EM_DesignatorFold:
    776         return false;
    777       }
    778       llvm_unreachable("Missed EvalMode case");
    779     }
    780 
    781     /// Notes that we failed to evaluate an expression that other expressions
    782     /// directly depend on, and determine if we should keep evaluating. This
    783     /// should only be called if we actually intend to keep evaluating.
    784     ///
    785     /// Call noteSideEffect() instead if we may be able to ignore the value that
    786     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
    787     ///
    788     /// (Foo(), 1)      // use noteSideEffect
    789     /// (Foo() || true) // use noteSideEffect
    790     /// Foo() + 1       // use noteFailure
    791     LLVM_ATTRIBUTE_UNUSED_RESULT bool noteFailure() {
    792       // Failure when evaluating some expression often means there is some
    793       // subexpression whose evaluation was skipped. Therefore, (because we
    794       // don't track whether we skipped an expression when unwinding after an
    795       // evaluation failure) every evaluation failure that bubbles up from a
    796       // subexpression implies that a side-effect has potentially happened. We
    797       // skip setting the HasSideEffects flag to true until we decide to
    798       // continue evaluating after that point, which happens here.
    799       bool KeepGoing = keepEvaluatingAfterFailure();
    800       EvalStatus.HasSideEffects |= KeepGoing;
    801       return KeepGoing;
    802     }
    803 
    804     bool allowInvalidBaseExpr() const {
    805       return EvalMode == EM_DesignatorFold;
    806     }
    807   };
    808 
    809   /// Object used to treat all foldable expressions as constant expressions.
    810   struct FoldConstant {
    811     EvalInfo &Info;
    812     bool Enabled;
    813     bool HadNoPriorDiags;
    814     EvalInfo::EvaluationMode OldMode;
    815 
    816     explicit FoldConstant(EvalInfo &Info, bool Enabled)
    817       : Info(Info),
    818         Enabled(Enabled),
    819         HadNoPriorDiags(Info.EvalStatus.Diag &&
    820                         Info.EvalStatus.Diag->empty() &&
    821                         !Info.EvalStatus.HasSideEffects),
    822         OldMode(Info.EvalMode) {
    823       if (Enabled &&
    824           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
    825            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
    826         Info.EvalMode = EvalInfo::EM_ConstantFold;
    827     }
    828     void keepDiagnostics() { Enabled = false; }
    829     ~FoldConstant() {
    830       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
    831           !Info.EvalStatus.HasSideEffects)
    832         Info.EvalStatus.Diag->clear();
    833       Info.EvalMode = OldMode;
    834     }
    835   };
    836 
    837   /// RAII object used to treat the current evaluation as the correct pointer
    838   /// offset fold for the current EvalMode
    839   struct FoldOffsetRAII {
    840     EvalInfo &Info;
    841     EvalInfo::EvaluationMode OldMode;
    842     explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
    843         : Info(Info), OldMode(Info.EvalMode) {
    844       if (!Info.checkingPotentialConstantExpression())
    845         Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
    846                                   : EvalInfo::EM_ConstantFold;
    847     }
    848 
    849     ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
    850   };
    851 
    852   /// RAII object used to optionally suppress diagnostics and side-effects from
    853   /// a speculative evaluation.
    854   class SpeculativeEvaluationRAII {
    855     /// Pair of EvalInfo, and a bit that stores whether or not we were
    856     /// speculatively evaluating when we created this RAII.
    857     llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
    858     Expr::EvalStatus Old;
    859 
    860     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
    861       InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
    862       Old = Other.Old;
    863       Other.InfoAndOldSpecEval.setPointer(nullptr);
    864     }
    865 
    866     void maybeRestoreState() {
    867       EvalInfo *Info = InfoAndOldSpecEval.getPointer();
    868       if (!Info)
    869         return;
    870 
    871       Info->EvalStatus = Old;
    872       Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
    873     }
    874 
    875   public:
    876     SpeculativeEvaluationRAII() = default;
    877 
    878     SpeculativeEvaluationRAII(
    879         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
    880         : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
    881           Old(Info.EvalStatus) {
    882       Info.EvalStatus.Diag = NewDiag;
    883       Info.IsSpeculativelyEvaluating = true;
    884     }
    885 
    886     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
    887     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
    888       moveFromAndCancel(std::move(Other));
    889     }
    890 
    891     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
    892       maybeRestoreState();
    893       moveFromAndCancel(std::move(Other));
    894       return *this;
    895     }
    896 
    897     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
    898   };
    899 
    900   /// RAII object wrapping a full-expression or block scope, and handling
    901   /// the ending of the lifetime of temporaries created within it.
    902   template<bool IsFullExpression>
    903   class ScopeRAII {
    904     EvalInfo &Info;
    905     unsigned OldStackSize;
    906   public:
    907     ScopeRAII(EvalInfo &Info)
    908         : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
    909     ~ScopeRAII() {
    910       // Body moved to a static method to encourage the compiler to inline away
    911       // instances of this class.
    912       cleanup(Info, OldStackSize);
    913     }
    914   private:
    915     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
    916       unsigned NewEnd = OldStackSize;
    917       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
    918            I != N; ++I) {
    919         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
    920           // Full-expression cleanup of a lifetime-extended temporary: nothing
    921           // to do, just move this cleanup to the right place in the stack.
    922           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
    923           ++NewEnd;
    924         } else {
    925           // End the lifetime of the object.
    926           Info.CleanupStack[I].endLifetime();
    927         }
    928       }
    929       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
    930                               Info.CleanupStack.end());
    931     }
    932   };
    933   typedef ScopeRAII<false> BlockScopeRAII;
    934   typedef ScopeRAII<true> FullExpressionRAII;
    935 }
    936 
    937 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
    938                                          CheckSubobjectKind CSK) {
    939   if (Invalid)
    940     return false;
    941   if (isOnePastTheEnd()) {
    942     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
    943       << CSK;
    944     setInvalid();
    945     return false;
    946   }
    947   return true;
    948 }
    949 
    950 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
    951                                                     const Expr *E, uint64_t N) {
    952   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
    953     Info.CCEDiag(E, diag::note_constexpr_array_index)
    954       << static_cast<int>(N) << /*array*/ 0
    955       << static_cast<unsigned>(MostDerivedArraySize);
    956   else
    957     Info.CCEDiag(E, diag::note_constexpr_array_index)
    958       << static_cast<int>(N) << /*non-array*/ 1;
    959   setInvalid();
    960 }
    961 
    962 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
    963                                const FunctionDecl *Callee, const LValue *This,
    964                                APValue *Arguments)
    965     : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
    966       Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
    967   Info.CurrentCall = this;
    968   ++Info.CallStackDepth;
    969 }
    970 
    971 CallStackFrame::~CallStackFrame() {
    972   assert(Info.CurrentCall == this && "calls retired out of order");
    973   --Info.CallStackDepth;
    974   Info.CurrentCall = Caller;
    975 }
    976 
    977 APValue &CallStackFrame::createTemporary(const void *Key,
    978                                          bool IsLifetimeExtended) {
    979   APValue &Result = Temporaries[Key];
    980   assert(Result.isUninit() && "temporary created multiple times");
    981   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
    982   return Result;
    983 }
    984 
    985 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
    986 
    987 void EvalInfo::addCallStack(unsigned Limit) {
    988   // Determine which calls to skip, if any.
    989   unsigned ActiveCalls = CallStackDepth - 1;
    990   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
    991   if (Limit && Limit < ActiveCalls) {
    992     SkipStart = Limit / 2 + Limit % 2;
    993     SkipEnd = ActiveCalls - Limit / 2;
    994   }
    995 
    996   // Walk the call stack and add the diagnostics.
    997   unsigned CallIdx = 0;
    998   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
    999        Frame = Frame->Caller, ++CallIdx) {
   1000     // Skip this call?
   1001     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
   1002       if (CallIdx == SkipStart) {
   1003         // Note that we're skipping calls.
   1004         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
   1005           << unsigned(ActiveCalls - Limit);
   1006       }
   1007       continue;
   1008     }
   1009 
   1010     // Use a different note for an inheriting constructor, because from the
   1011     // user's perspective it's not really a function at all.
   1012     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
   1013       if (CD->isInheritingConstructor()) {
   1014         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
   1015           << CD->getParent();
   1016         continue;
   1017       }
   1018     }
   1019 
   1020     SmallVector<char, 128> Buffer;
   1021     llvm::raw_svector_ostream Out(Buffer);
   1022     describeCall(Frame, Out);
   1023     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
   1024   }
   1025 }
   1026 
   1027 namespace {
   1028   struct ComplexValue {
   1029   private:
   1030     bool IsInt;
   1031 
   1032   public:
   1033     APSInt IntReal, IntImag;
   1034     APFloat FloatReal, FloatImag;
   1035 
   1036     ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
   1037 
   1038     void makeComplexFloat() { IsInt = false; }
   1039     bool isComplexFloat() const { return !IsInt; }
   1040     APFloat &getComplexFloatReal() { return FloatReal; }
   1041     APFloat &getComplexFloatImag() { return FloatImag; }
   1042 
   1043     void makeComplexInt() { IsInt = true; }
   1044     bool isComplexInt() const { return IsInt; }
   1045     APSInt &getComplexIntReal() { return IntReal; }
   1046     APSInt &getComplexIntImag() { return IntImag; }
   1047 
   1048     void moveInto(APValue &v) const {
   1049       if (isComplexFloat())
   1050         v = APValue(FloatReal, FloatImag);
   1051       else
   1052         v = APValue(IntReal, IntImag);
   1053     }
   1054     void setFrom(const APValue &v) {
   1055       assert(v.isComplexFloat() || v.isComplexInt());
   1056       if (v.isComplexFloat()) {
   1057         makeComplexFloat();
   1058         FloatReal = v.getComplexFloatReal();
   1059         FloatImag = v.getComplexFloatImag();
   1060       } else {
   1061         makeComplexInt();
   1062         IntReal = v.getComplexIntReal();
   1063         IntImag = v.getComplexIntImag();
   1064       }
   1065     }
   1066   };
   1067 
   1068   struct LValue {
   1069     APValue::LValueBase Base;
   1070     CharUnits Offset;
   1071     unsigned InvalidBase : 1;
   1072     unsigned CallIndex : 31;
   1073     SubobjectDesignator Designator;
   1074 
   1075     const APValue::LValueBase getLValueBase() const { return Base; }
   1076     CharUnits &getLValueOffset() { return Offset; }
   1077     const CharUnits &getLValueOffset() const { return Offset; }
   1078     unsigned getLValueCallIndex() const { return CallIndex; }
   1079     SubobjectDesignator &getLValueDesignator() { return Designator; }
   1080     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
   1081 
   1082     void moveInto(APValue &V) const {
   1083       if (Designator.Invalid)
   1084         V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
   1085       else
   1086         V = APValue(Base, Offset, Designator.Entries,
   1087                     Designator.IsOnePastTheEnd, CallIndex);
   1088     }
   1089     void setFrom(ASTContext &Ctx, const APValue &V) {
   1090       assert(V.isLValue());
   1091       Base = V.getLValueBase();
   1092       Offset = V.getLValueOffset();
   1093       InvalidBase = false;
   1094       CallIndex = V.getLValueCallIndex();
   1095       Designator = SubobjectDesignator(Ctx, V);
   1096     }
   1097 
   1098     void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
   1099       Base = B;
   1100       Offset = CharUnits::Zero();
   1101       InvalidBase = BInvalid;
   1102       CallIndex = I;
   1103       Designator = SubobjectDesignator(getType(B));
   1104     }
   1105 
   1106     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
   1107       set(B, I, true);
   1108     }
   1109 
   1110     // Check that this LValue is not based on a null pointer. If it is, produce
   1111     // a diagnostic and mark the designator as invalid.
   1112     bool checkNullPointer(EvalInfo &Info, const Expr *E,
   1113                           CheckSubobjectKind CSK) {
   1114       if (Designator.Invalid)
   1115         return false;
   1116       if (!Base) {
   1117         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
   1118           << CSK;
   1119         Designator.setInvalid();
   1120         return false;
   1121       }
   1122       return true;
   1123     }
   1124 
   1125     // Check this LValue refers to an object. If not, set the designator to be
   1126     // invalid and emit a diagnostic.
   1127     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
   1128       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
   1129              Designator.checkSubobject(Info, E, CSK);
   1130     }
   1131 
   1132     void addDecl(EvalInfo &Info, const Expr *E,
   1133                  const Decl *D, bool Virtual = false) {
   1134       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
   1135         Designator.addDeclUnchecked(D, Virtual);
   1136     }
   1137     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
   1138       if (checkSubobject(Info, E, CSK_ArrayToPointer))
   1139         Designator.addArrayUnchecked(CAT);
   1140     }
   1141     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
   1142       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
   1143         Designator.addComplexUnchecked(EltTy, Imag);
   1144     }
   1145     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
   1146       if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
   1147         Designator.adjustIndex(Info, E, N);
   1148     }
   1149   };
   1150 
   1151   struct MemberPtr {
   1152     MemberPtr() {}
   1153     explicit MemberPtr(const ValueDecl *Decl) :
   1154       DeclAndIsDerivedMember(Decl, false), Path() {}
   1155 
   1156     /// The member or (direct or indirect) field referred to by this member
   1157     /// pointer, or 0 if this is a null member pointer.
   1158     const ValueDecl *getDecl() const {
   1159       return DeclAndIsDerivedMember.getPointer();
   1160     }
   1161     /// Is this actually a member of some type derived from the relevant class?
   1162     bool isDerivedMember() const {
   1163       return DeclAndIsDerivedMember.getInt();
   1164     }
   1165     /// Get the class which the declaration actually lives in.
   1166     const CXXRecordDecl *getContainingRecord() const {
   1167       return cast<CXXRecordDecl>(
   1168           DeclAndIsDerivedMember.getPointer()->getDeclContext());
   1169     }
   1170 
   1171     void moveInto(APValue &V) const {
   1172       V = APValue(getDecl(), isDerivedMember(), Path);
   1173     }
   1174     void setFrom(const APValue &V) {
   1175       assert(V.isMemberPointer());
   1176       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
   1177       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
   1178       Path.clear();
   1179       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
   1180       Path.insert(Path.end(), P.begin(), P.end());
   1181     }
   1182 
   1183     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
   1184     /// whether the member is a member of some class derived from the class type
   1185     /// of the member pointer.
   1186     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
   1187     /// Path - The path of base/derived classes from the member declaration's
   1188     /// class (exclusive) to the class type of the member pointer (inclusive).
   1189     SmallVector<const CXXRecordDecl*, 4> Path;
   1190 
   1191     /// Perform a cast towards the class of the Decl (either up or down the
   1192     /// hierarchy).
   1193     bool castBack(const CXXRecordDecl *Class) {
   1194       assert(!Path.empty());
   1195       const CXXRecordDecl *Expected;
   1196       if (Path.size() >= 2)
   1197         Expected = Path[Path.size() - 2];
   1198       else
   1199         Expected = getContainingRecord();
   1200       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
   1201         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
   1202         // if B does not contain the original member and is not a base or
   1203         // derived class of the class containing the original member, the result
   1204         // of the cast is undefined.
   1205         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
   1206         // (D::*). We consider that to be a language defect.
   1207         return false;
   1208       }
   1209       Path.pop_back();
   1210       return true;
   1211     }
   1212     /// Perform a base-to-derived member pointer cast.
   1213     bool castToDerived(const CXXRecordDecl *Derived) {
   1214       if (!getDecl())
   1215         return true;
   1216       if (!isDerivedMember()) {
   1217         Path.push_back(Derived);
   1218         return true;
   1219       }
   1220       if (!castBack(Derived))
   1221         return false;
   1222       if (Path.empty())
   1223         DeclAndIsDerivedMember.setInt(false);
   1224       return true;
   1225     }
   1226     /// Perform a derived-to-base member pointer cast.
   1227     bool castToBase(const CXXRecordDecl *Base) {
   1228       if (!getDecl())
   1229         return true;
   1230       if (Path.empty())
   1231         DeclAndIsDerivedMember.setInt(true);
   1232       if (isDerivedMember()) {
   1233         Path.push_back(Base);
   1234         return true;
   1235       }
   1236       return castBack(Base);
   1237     }
   1238   };
   1239 
   1240   /// Compare two member pointers, which are assumed to be of the same type.
   1241   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
   1242     if (!LHS.getDecl() || !RHS.getDecl())
   1243       return !LHS.getDecl() && !RHS.getDecl();
   1244     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
   1245       return false;
   1246     return LHS.Path == RHS.Path;
   1247   }
   1248 }
   1249 
   1250 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
   1251 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
   1252                             const LValue &This, const Expr *E,
   1253                             bool AllowNonLiteralTypes = false);
   1254 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
   1255 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
   1256 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
   1257                                   EvalInfo &Info);
   1258 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
   1259 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
   1260 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
   1261                                     EvalInfo &Info);
   1262 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
   1263 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
   1264 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
   1265 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
   1266 
   1267 //===----------------------------------------------------------------------===//
   1268 // Misc utilities
   1269 //===----------------------------------------------------------------------===//
   1270 
   1271 /// Produce a string describing the given constexpr call.
   1272 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
   1273   unsigned ArgIndex = 0;
   1274   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
   1275                       !isa<CXXConstructorDecl>(Frame->Callee) &&
   1276                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
   1277 
   1278   if (!IsMemberCall)
   1279     Out << *Frame->Callee << '(';
   1280 
   1281   if (Frame->This && IsMemberCall) {
   1282     APValue Val;
   1283     Frame->This->moveInto(Val);
   1284     Val.printPretty(Out, Frame->Info.Ctx,
   1285                     Frame->This->Designator.MostDerivedType);
   1286     // FIXME: Add parens around Val if needed.
   1287     Out << "->" << *Frame->Callee << '(';
   1288     IsMemberCall = false;
   1289   }
   1290 
   1291   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
   1292        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
   1293     if (ArgIndex > (unsigned)IsMemberCall)
   1294       Out << ", ";
   1295 
   1296     const ParmVarDecl *Param = *I;
   1297     const APValue &Arg = Frame->Arguments[ArgIndex];
   1298     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
   1299 
   1300     if (ArgIndex == 0 && IsMemberCall)
   1301       Out << "->" << *Frame->Callee << '(';
   1302   }
   1303 
   1304   Out << ')';
   1305 }
   1306 
   1307 /// Evaluate an expression to see if it had side-effects, and discard its
   1308 /// result.
   1309 /// \return \c true if the caller should keep evaluating.
   1310 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
   1311   APValue Scratch;
   1312   if (!Evaluate(Scratch, Info, E))
   1313     // We don't need the value, but we might have skipped a side effect here.
   1314     return Info.noteSideEffect();
   1315   return true;
   1316 }
   1317 
   1318 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
   1319 /// return its existing value.
   1320 static int64_t getExtValue(const APSInt &Value) {
   1321   return Value.isSigned() ? Value.getSExtValue()
   1322                           : static_cast<int64_t>(Value.getZExtValue());
   1323 }
   1324 
   1325 /// Should this call expression be treated as a string literal?
   1326 static bool IsStringLiteralCall(const CallExpr *E) {
   1327   unsigned Builtin = E->getBuiltinCallee();
   1328   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
   1329           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
   1330 }
   1331 
   1332 static bool IsGlobalLValue(APValue::LValueBase B) {
   1333   // C++11 [expr.const]p3 An address constant expression is a prvalue core
   1334   // constant expression of pointer type that evaluates to...
   1335 
   1336   // ... a null pointer value, or a prvalue core constant expression of type
   1337   // std::nullptr_t.
   1338   if (!B) return true;
   1339 
   1340   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
   1341     // ... the address of an object with static storage duration,
   1342     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
   1343       return VD->hasGlobalStorage();
   1344     // ... the address of a function,
   1345     return isa<FunctionDecl>(D);
   1346   }
   1347 
   1348   const Expr *E = B.get<const Expr*>();
   1349   switch (E->getStmtClass()) {
   1350   default:
   1351     return false;
   1352   case Expr::CompoundLiteralExprClass: {
   1353     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
   1354     return CLE->isFileScope() && CLE->isLValue();
   1355   }
   1356   case Expr::MaterializeTemporaryExprClass:
   1357     // A materialized temporary might have been lifetime-extended to static
   1358     // storage duration.
   1359     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
   1360   // A string literal has static storage duration.
   1361   case Expr::StringLiteralClass:
   1362   case Expr::PredefinedExprClass:
   1363   case Expr::ObjCStringLiteralClass:
   1364   case Expr::ObjCEncodeExprClass:
   1365   case Expr::CXXTypeidExprClass:
   1366   case Expr::CXXUuidofExprClass:
   1367     return true;
   1368   case Expr::CallExprClass:
   1369     return IsStringLiteralCall(cast<CallExpr>(E));
   1370   // For GCC compatibility, &&label has static storage duration.
   1371   case Expr::AddrLabelExprClass:
   1372     return true;
   1373   // A Block literal expression may be used as the initialization value for
   1374   // Block variables at global or local static scope.
   1375   case Expr::BlockExprClass:
   1376     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
   1377   case Expr::ImplicitValueInitExprClass:
   1378     // FIXME:
   1379     // We can never form an lvalue with an implicit value initialization as its
   1380     // base through expression evaluation, so these only appear in one case: the
   1381     // implicit variable declaration we invent when checking whether a constexpr
   1382     // constructor can produce a constant expression. We must assume that such
   1383     // an expression might be a global lvalue.
   1384     return true;
   1385   }
   1386 }
   1387 
   1388 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
   1389   assert(Base && "no location for a null lvalue");
   1390   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
   1391   if (VD)
   1392     Info.Note(VD->getLocation(), diag::note_declared_at);
   1393   else
   1394     Info.Note(Base.get<const Expr*>()->getExprLoc(),
   1395               diag::note_constexpr_temporary_here);
   1396 }
   1397 
   1398 /// Check that this reference or pointer core constant expression is a valid
   1399 /// value for an address or reference constant expression. Return true if we
   1400 /// can fold this expression, whether or not it's a constant expression.
   1401 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
   1402                                           QualType Type, const LValue &LVal) {
   1403   bool IsReferenceType = Type->isReferenceType();
   1404 
   1405   APValue::LValueBase Base = LVal.getLValueBase();
   1406   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
   1407 
   1408   // Check that the object is a global. Note that the fake 'this' object we
   1409   // manufacture when checking potential constant expressions is conservatively
   1410   // assumed to be global here.
   1411   if (!IsGlobalLValue(Base)) {
   1412     if (Info.getLangOpts().CPlusPlus11) {
   1413       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
   1414       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
   1415         << IsReferenceType << !Designator.Entries.empty()
   1416         << !!VD << VD;
   1417       NoteLValueLocation(Info, Base);
   1418     } else {
   1419       Info.FFDiag(Loc);
   1420     }
   1421     // Don't allow references to temporaries to escape.
   1422     return false;
   1423   }
   1424   assert((Info.checkingPotentialConstantExpression() ||
   1425           LVal.getLValueCallIndex() == 0) &&
   1426          "have call index for global lvalue");
   1427 
   1428   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
   1429     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
   1430       // Check if this is a thread-local variable.
   1431       if (Var->getTLSKind())
   1432         return false;
   1433 
   1434       // A dllimport variable never acts like a constant.
   1435       if (Var->hasAttr<DLLImportAttr>())
   1436         return false;
   1437     }
   1438     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
   1439       // __declspec(dllimport) must be handled very carefully:
   1440       // We must never initialize an expression with the thunk in C++.
   1441       // Doing otherwise would allow the same id-expression to yield
   1442       // different addresses for the same function in different translation
   1443       // units.  However, this means that we must dynamically initialize the
   1444       // expression with the contents of the import address table at runtime.
   1445       //
   1446       // The C language has no notion of ODR; furthermore, it has no notion of
   1447       // dynamic initialization.  This means that we are permitted to
   1448       // perform initialization with the address of the thunk.
   1449       if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
   1450         return false;
   1451     }
   1452   }
   1453 
   1454   // Allow address constant expressions to be past-the-end pointers. This is
   1455   // an extension: the standard requires them to point to an object.
   1456   if (!IsReferenceType)
   1457     return true;
   1458 
   1459   // A reference constant expression must refer to an object.
   1460   if (!Base) {
   1461     // FIXME: diagnostic
   1462     Info.CCEDiag(Loc);
   1463     return true;
   1464   }
   1465 
   1466   // Does this refer one past the end of some object?
   1467   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
   1468     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
   1469     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
   1470       << !Designator.Entries.empty() << !!VD << VD;
   1471     NoteLValueLocation(Info, Base);
   1472   }
   1473 
   1474   return true;
   1475 }
   1476 
   1477 /// Check that this core constant expression is of literal type, and if not,
   1478 /// produce an appropriate diagnostic.
   1479 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
   1480                              const LValue *This = nullptr) {
   1481   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
   1482     return true;
   1483 
   1484   // C++1y: A constant initializer for an object o [...] may also invoke
   1485   // constexpr constructors for o and its subobjects even if those objects
   1486   // are of non-literal class types.
   1487   if (Info.getLangOpts().CPlusPlus14 && This &&
   1488       Info.EvaluatingDecl == This->getLValueBase())
   1489     return true;
   1490 
   1491   // Prvalue constant expressions must be of literal types.
   1492   if (Info.getLangOpts().CPlusPlus11)
   1493     Info.FFDiag(E, diag::note_constexpr_nonliteral)
   1494       << E->getType();
   1495   else
   1496     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   1497   return false;
   1498 }
   1499 
   1500 /// Check that this core constant expression value is a valid value for a
   1501 /// constant expression. If not, report an appropriate diagnostic. Does not
   1502 /// check that the expression is of literal type.
   1503 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
   1504                                     QualType Type, const APValue &Value) {
   1505   if (Value.isUninit()) {
   1506     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
   1507       << true << Type;
   1508     return false;
   1509   }
   1510 
   1511   // We allow _Atomic(T) to be initialized from anything that T can be
   1512   // initialized from.
   1513   if (const AtomicType *AT = Type->getAs<AtomicType>())
   1514     Type = AT->getValueType();
   1515 
   1516   // Core issue 1454: For a literal constant expression of array or class type,
   1517   // each subobject of its value shall have been initialized by a constant
   1518   // expression.
   1519   if (Value.isArray()) {
   1520     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
   1521     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
   1522       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
   1523                                    Value.getArrayInitializedElt(I)))
   1524         return false;
   1525     }
   1526     if (!Value.hasArrayFiller())
   1527       return true;
   1528     return CheckConstantExpression(Info, DiagLoc, EltTy,
   1529                                    Value.getArrayFiller());
   1530   }
   1531   if (Value.isUnion() && Value.getUnionField()) {
   1532     return CheckConstantExpression(Info, DiagLoc,
   1533                                    Value.getUnionField()->getType(),
   1534                                    Value.getUnionValue());
   1535   }
   1536   if (Value.isStruct()) {
   1537     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
   1538     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
   1539       unsigned BaseIndex = 0;
   1540       for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
   1541              End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
   1542         if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
   1543                                      Value.getStructBase(BaseIndex)))
   1544           return false;
   1545       }
   1546     }
   1547     for (const auto *I : RD->fields()) {
   1548       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
   1549                                    Value.getStructField(I->getFieldIndex())))
   1550         return false;
   1551     }
   1552   }
   1553 
   1554   if (Value.isLValue()) {
   1555     LValue LVal;
   1556     LVal.setFrom(Info.Ctx, Value);
   1557     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
   1558   }
   1559 
   1560   // Everything else is fine.
   1561   return true;
   1562 }
   1563 
   1564 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
   1565   return LVal.Base.dyn_cast<const ValueDecl*>();
   1566 }
   1567 
   1568 static bool IsLiteralLValue(const LValue &Value) {
   1569   if (Value.CallIndex)
   1570     return false;
   1571   const Expr *E = Value.Base.dyn_cast<const Expr*>();
   1572   return E && !isa<MaterializeTemporaryExpr>(E);
   1573 }
   1574 
   1575 static bool IsWeakLValue(const LValue &Value) {
   1576   const ValueDecl *Decl = GetLValueBaseDecl(Value);
   1577   return Decl && Decl->isWeak();
   1578 }
   1579 
   1580 static bool isZeroSized(const LValue &Value) {
   1581   const ValueDecl *Decl = GetLValueBaseDecl(Value);
   1582   if (Decl && isa<VarDecl>(Decl)) {
   1583     QualType Ty = Decl->getType();
   1584     if (Ty->isArrayType())
   1585       return Ty->isIncompleteType() ||
   1586              Decl->getASTContext().getTypeSize(Ty) == 0;
   1587   }
   1588   return false;
   1589 }
   1590 
   1591 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
   1592   // A null base expression indicates a null pointer.  These are always
   1593   // evaluatable, and they are false unless the offset is zero.
   1594   if (!Value.getLValueBase()) {
   1595     Result = !Value.getLValueOffset().isZero();
   1596     return true;
   1597   }
   1598 
   1599   // We have a non-null base.  These are generally known to be true, but if it's
   1600   // a weak declaration it can be null at runtime.
   1601   Result = true;
   1602   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
   1603   return !Decl || !Decl->isWeak();
   1604 }
   1605 
   1606 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
   1607   switch (Val.getKind()) {
   1608   case APValue::Uninitialized:
   1609     return false;
   1610   case APValue::Int:
   1611     Result = Val.getInt().getBoolValue();
   1612     return true;
   1613   case APValue::Float:
   1614     Result = !Val.getFloat().isZero();
   1615     return true;
   1616   case APValue::ComplexInt:
   1617     Result = Val.getComplexIntReal().getBoolValue() ||
   1618              Val.getComplexIntImag().getBoolValue();
   1619     return true;
   1620   case APValue::ComplexFloat:
   1621     Result = !Val.getComplexFloatReal().isZero() ||
   1622              !Val.getComplexFloatImag().isZero();
   1623     return true;
   1624   case APValue::LValue:
   1625     return EvalPointerValueAsBool(Val, Result);
   1626   case APValue::MemberPointer:
   1627     Result = Val.getMemberPointerDecl();
   1628     return true;
   1629   case APValue::Vector:
   1630   case APValue::Array:
   1631   case APValue::Struct:
   1632   case APValue::Union:
   1633   case APValue::AddrLabelDiff:
   1634     return false;
   1635   }
   1636 
   1637   llvm_unreachable("unknown APValue kind");
   1638 }
   1639 
   1640 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
   1641                                        EvalInfo &Info) {
   1642   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
   1643   APValue Val;
   1644   if (!Evaluate(Val, Info, E))
   1645     return false;
   1646   return HandleConversionToBool(Val, Result);
   1647 }
   1648 
   1649 template<typename T>
   1650 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
   1651                            const T &SrcValue, QualType DestType) {
   1652   Info.CCEDiag(E, diag::note_constexpr_overflow)
   1653     << SrcValue << DestType;
   1654   return Info.noteUndefinedBehavior();
   1655 }
   1656 
   1657 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
   1658                                  QualType SrcType, const APFloat &Value,
   1659                                  QualType DestType, APSInt &Result) {
   1660   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
   1661   // Determine whether we are converting to unsigned or signed.
   1662   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
   1663 
   1664   Result = APSInt(DestWidth, !DestSigned);
   1665   bool ignored;
   1666   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
   1667       & APFloat::opInvalidOp)
   1668     return HandleOverflow(Info, E, Value, DestType);
   1669   return true;
   1670 }
   1671 
   1672 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
   1673                                    QualType SrcType, QualType DestType,
   1674                                    APFloat &Result) {
   1675   APFloat Value = Result;
   1676   bool ignored;
   1677   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
   1678                      APFloat::rmNearestTiesToEven, &ignored)
   1679       & APFloat::opOverflow)
   1680     return HandleOverflow(Info, E, Value, DestType);
   1681   return true;
   1682 }
   1683 
   1684 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
   1685                                  QualType DestType, QualType SrcType,
   1686                                  const APSInt &Value) {
   1687   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
   1688   APSInt Result = Value;
   1689   // Figure out if this is a truncate, extend or noop cast.
   1690   // If the input is signed, do a sign extend, noop, or truncate.
   1691   Result = Result.extOrTrunc(DestWidth);
   1692   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
   1693   return Result;
   1694 }
   1695 
   1696 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
   1697                                  QualType SrcType, const APSInt &Value,
   1698                                  QualType DestType, APFloat &Result) {
   1699   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
   1700   if (Result.convertFromAPInt(Value, Value.isSigned(),
   1701                               APFloat::rmNearestTiesToEven)
   1702       & APFloat::opOverflow)
   1703     return HandleOverflow(Info, E, Value, DestType);
   1704   return true;
   1705 }
   1706 
   1707 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
   1708                                   APValue &Value, const FieldDecl *FD) {
   1709   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
   1710 
   1711   if (!Value.isInt()) {
   1712     // Trying to store a pointer-cast-to-integer into a bitfield.
   1713     // FIXME: In this case, we should provide the diagnostic for casting
   1714     // a pointer to an integer.
   1715     assert(Value.isLValue() && "integral value neither int nor lvalue?");
   1716     Info.FFDiag(E);
   1717     return false;
   1718   }
   1719 
   1720   APSInt &Int = Value.getInt();
   1721   unsigned OldBitWidth = Int.getBitWidth();
   1722   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
   1723   if (NewBitWidth < OldBitWidth)
   1724     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
   1725   return true;
   1726 }
   1727 
   1728 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
   1729                                   llvm::APInt &Res) {
   1730   APValue SVal;
   1731   if (!Evaluate(SVal, Info, E))
   1732     return false;
   1733   if (SVal.isInt()) {
   1734     Res = SVal.getInt();
   1735     return true;
   1736   }
   1737   if (SVal.isFloat()) {
   1738     Res = SVal.getFloat().bitcastToAPInt();
   1739     return true;
   1740   }
   1741   if (SVal.isVector()) {
   1742     QualType VecTy = E->getType();
   1743     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
   1744     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
   1745     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
   1746     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
   1747     Res = llvm::APInt::getNullValue(VecSize);
   1748     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
   1749       APValue &Elt = SVal.getVectorElt(i);
   1750       llvm::APInt EltAsInt;
   1751       if (Elt.isInt()) {
   1752         EltAsInt = Elt.getInt();
   1753       } else if (Elt.isFloat()) {
   1754         EltAsInt = Elt.getFloat().bitcastToAPInt();
   1755       } else {
   1756         // Don't try to handle vectors of anything other than int or float
   1757         // (not sure if it's possible to hit this case).
   1758         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   1759         return false;
   1760       }
   1761       unsigned BaseEltSize = EltAsInt.getBitWidth();
   1762       if (BigEndian)
   1763         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
   1764       else
   1765         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
   1766     }
   1767     return true;
   1768   }
   1769   // Give up if the input isn't an int, float, or vector.  For example, we
   1770   // reject "(v4i16)(intptr_t)&a".
   1771   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   1772   return false;
   1773 }
   1774 
   1775 /// Perform the given integer operation, which is known to need at most BitWidth
   1776 /// bits, and check for overflow in the original type (if that type was not an
   1777 /// unsigned type).
   1778 template<typename Operation>
   1779 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
   1780                                  const APSInt &LHS, const APSInt &RHS,
   1781                                  unsigned BitWidth, Operation Op,
   1782                                  APSInt &Result) {
   1783   if (LHS.isUnsigned()) {
   1784     Result = Op(LHS, RHS);
   1785     return true;
   1786   }
   1787 
   1788   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
   1789   Result = Value.trunc(LHS.getBitWidth());
   1790   if (Result.extend(BitWidth) != Value) {
   1791     if (Info.checkingForOverflow())
   1792       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
   1793                                        diag::warn_integer_constant_overflow)
   1794           << Result.toString(10) << E->getType();
   1795     else
   1796       return HandleOverflow(Info, E, Value, E->getType());
   1797   }
   1798   return true;
   1799 }
   1800 
   1801 /// Perform the given binary integer operation.
   1802 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
   1803                               BinaryOperatorKind Opcode, APSInt RHS,
   1804                               APSInt &Result) {
   1805   switch (Opcode) {
   1806   default:
   1807     Info.FFDiag(E);
   1808     return false;
   1809   case BO_Mul:
   1810     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
   1811                                 std::multiplies<APSInt>(), Result);
   1812   case BO_Add:
   1813     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
   1814                                 std::plus<APSInt>(), Result);
   1815   case BO_Sub:
   1816     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
   1817                                 std::minus<APSInt>(), Result);
   1818   case BO_And: Result = LHS & RHS; return true;
   1819   case BO_Xor: Result = LHS ^ RHS; return true;
   1820   case BO_Or:  Result = LHS | RHS; return true;
   1821   case BO_Div:
   1822   case BO_Rem:
   1823     if (RHS == 0) {
   1824       Info.FFDiag(E, diag::note_expr_divide_by_zero);
   1825       return false;
   1826     }
   1827     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
   1828     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
   1829     // this operation and gives the two's complement result.
   1830     if (RHS.isNegative() && RHS.isAllOnesValue() &&
   1831         LHS.isSigned() && LHS.isMinSignedValue())
   1832       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
   1833                             E->getType());
   1834     return true;
   1835   case BO_Shl: {
   1836     if (Info.getLangOpts().OpenCL)
   1837       // OpenCL 6.3j: shift values are effectively % word size of LHS.
   1838       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
   1839                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
   1840                     RHS.isUnsigned());
   1841     else if (RHS.isSigned() && RHS.isNegative()) {
   1842       // During constant-folding, a negative shift is an opposite shift. Such
   1843       // a shift is not a constant expression.
   1844       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
   1845       RHS = -RHS;
   1846       goto shift_right;
   1847     }
   1848   shift_left:
   1849     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
   1850     // the shifted type.
   1851     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
   1852     if (SA != RHS) {
   1853       Info.CCEDiag(E, diag::note_constexpr_large_shift)
   1854         << RHS << E->getType() << LHS.getBitWidth();
   1855     } else if (LHS.isSigned()) {
   1856       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
   1857       // operand, and must not overflow the corresponding unsigned type.
   1858       if (LHS.isNegative())
   1859         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
   1860       else if (LHS.countLeadingZeros() < SA)
   1861         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
   1862     }
   1863     Result = LHS << SA;
   1864     return true;
   1865   }
   1866   case BO_Shr: {
   1867     if (Info.getLangOpts().OpenCL)
   1868       // OpenCL 6.3j: shift values are effectively % word size of LHS.
   1869       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
   1870                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
   1871                     RHS.isUnsigned());
   1872     else if (RHS.isSigned() && RHS.isNegative()) {
   1873       // During constant-folding, a negative shift is an opposite shift. Such a
   1874       // shift is not a constant expression.
   1875       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
   1876       RHS = -RHS;
   1877       goto shift_left;
   1878     }
   1879   shift_right:
   1880     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
   1881     // shifted type.
   1882     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
   1883     if (SA != RHS)
   1884       Info.CCEDiag(E, diag::note_constexpr_large_shift)
   1885         << RHS << E->getType() << LHS.getBitWidth();
   1886     Result = LHS >> SA;
   1887     return true;
   1888   }
   1889 
   1890   case BO_LT: Result = LHS < RHS; return true;
   1891   case BO_GT: Result = LHS > RHS; return true;
   1892   case BO_LE: Result = LHS <= RHS; return true;
   1893   case BO_GE: Result = LHS >= RHS; return true;
   1894   case BO_EQ: Result = LHS == RHS; return true;
   1895   case BO_NE: Result = LHS != RHS; return true;
   1896   }
   1897 }
   1898 
   1899 /// Perform the given binary floating-point operation, in-place, on LHS.
   1900 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
   1901                                   APFloat &LHS, BinaryOperatorKind Opcode,
   1902                                   const APFloat &RHS) {
   1903   switch (Opcode) {
   1904   default:
   1905     Info.FFDiag(E);
   1906     return false;
   1907   case BO_Mul:
   1908     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
   1909     break;
   1910   case BO_Add:
   1911     LHS.add(RHS, APFloat::rmNearestTiesToEven);
   1912     break;
   1913   case BO_Sub:
   1914     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
   1915     break;
   1916   case BO_Div:
   1917     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
   1918     break;
   1919   }
   1920 
   1921   if (LHS.isInfinity() || LHS.isNaN()) {
   1922     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
   1923     return Info.noteUndefinedBehavior();
   1924   }
   1925   return true;
   1926 }
   1927 
   1928 /// Cast an lvalue referring to a base subobject to a derived class, by
   1929 /// truncating the lvalue's path to the given length.
   1930 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
   1931                                const RecordDecl *TruncatedType,
   1932                                unsigned TruncatedElements) {
   1933   SubobjectDesignator &D = Result.Designator;
   1934 
   1935   // Check we actually point to a derived class object.
   1936   if (TruncatedElements == D.Entries.size())
   1937     return true;
   1938   assert(TruncatedElements >= D.MostDerivedPathLength &&
   1939          "not casting to a derived class");
   1940   if (!Result.checkSubobject(Info, E, CSK_Derived))
   1941     return false;
   1942 
   1943   // Truncate the path to the subobject, and remove any derived-to-base offsets.
   1944   const RecordDecl *RD = TruncatedType;
   1945   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
   1946     if (RD->isInvalidDecl()) return false;
   1947     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
   1948     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
   1949     if (isVirtualBaseClass(D.Entries[I]))
   1950       Result.Offset -= Layout.getVBaseClassOffset(Base);
   1951     else
   1952       Result.Offset -= Layout.getBaseClassOffset(Base);
   1953     RD = Base;
   1954   }
   1955   D.Entries.resize(TruncatedElements);
   1956   return true;
   1957 }
   1958 
   1959 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
   1960                                    const CXXRecordDecl *Derived,
   1961                                    const CXXRecordDecl *Base,
   1962                                    const ASTRecordLayout *RL = nullptr) {
   1963   if (!RL) {
   1964     if (Derived->isInvalidDecl()) return false;
   1965     RL = &Info.Ctx.getASTRecordLayout(Derived);
   1966   }
   1967 
   1968   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
   1969   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
   1970   return true;
   1971 }
   1972 
   1973 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
   1974                              const CXXRecordDecl *DerivedDecl,
   1975                              const CXXBaseSpecifier *Base) {
   1976   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
   1977 
   1978   if (!Base->isVirtual())
   1979     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
   1980 
   1981   SubobjectDesignator &D = Obj.Designator;
   1982   if (D.Invalid)
   1983     return false;
   1984 
   1985   // Extract most-derived object and corresponding type.
   1986   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
   1987   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
   1988     return false;
   1989 
   1990   // Find the virtual base class.
   1991   if (DerivedDecl->isInvalidDecl()) return false;
   1992   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
   1993   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
   1994   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
   1995   return true;
   1996 }
   1997 
   1998 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
   1999                                  QualType Type, LValue &Result) {
   2000   for (CastExpr::path_const_iterator PathI = E->path_begin(),
   2001                                      PathE = E->path_end();
   2002        PathI != PathE; ++PathI) {
   2003     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
   2004                           *PathI))
   2005       return false;
   2006     Type = (*PathI)->getType();
   2007   }
   2008   return true;
   2009 }
   2010 
   2011 /// Update LVal to refer to the given field, which must be a member of the type
   2012 /// currently described by LVal.
   2013 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
   2014                                const FieldDecl *FD,
   2015                                const ASTRecordLayout *RL = nullptr) {
   2016   if (!RL) {
   2017     if (FD->getParent()->isInvalidDecl()) return false;
   2018     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
   2019   }
   2020 
   2021   unsigned I = FD->getFieldIndex();
   2022   LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
   2023   LVal.addDecl(Info, E, FD);
   2024   return true;
   2025 }
   2026 
   2027 /// Update LVal to refer to the given indirect field.
   2028 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
   2029                                        LValue &LVal,
   2030                                        const IndirectFieldDecl *IFD) {
   2031   for (const auto *C : IFD->chain())
   2032     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
   2033       return false;
   2034   return true;
   2035 }
   2036 
   2037 /// Get the size of the given type in char units.
   2038 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
   2039                          QualType Type, CharUnits &Size) {
   2040   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
   2041   // extension.
   2042   if (Type->isVoidType() || Type->isFunctionType()) {
   2043     Size = CharUnits::One();
   2044     return true;
   2045   }
   2046 
   2047   if (Type->isDependentType()) {
   2048     Info.FFDiag(Loc);
   2049     return false;
   2050   }
   2051 
   2052   if (!Type->isConstantSizeType()) {
   2053     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
   2054     // FIXME: Better diagnostic.
   2055     Info.FFDiag(Loc);
   2056     return false;
   2057   }
   2058 
   2059   Size = Info.Ctx.getTypeSizeInChars(Type);
   2060   return true;
   2061 }
   2062 
   2063 /// Update a pointer value to model pointer arithmetic.
   2064 /// \param Info - Information about the ongoing evaluation.
   2065 /// \param E - The expression being evaluated, for diagnostic purposes.
   2066 /// \param LVal - The pointer value to be updated.
   2067 /// \param EltTy - The pointee type represented by LVal.
   2068 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
   2069 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
   2070                                         LValue &LVal, QualType EltTy,
   2071                                         int64_t Adjustment) {
   2072   CharUnits SizeOfPointee;
   2073   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
   2074     return false;
   2075 
   2076   // Compute the new offset in the appropriate width.
   2077   LVal.Offset += Adjustment * SizeOfPointee;
   2078   LVal.adjustIndex(Info, E, Adjustment);
   2079   return true;
   2080 }
   2081 
   2082 /// Update an lvalue to refer to a component of a complex number.
   2083 /// \param Info - Information about the ongoing evaluation.
   2084 /// \param LVal - The lvalue to be updated.
   2085 /// \param EltTy - The complex number's component type.
   2086 /// \param Imag - False for the real component, true for the imaginary.
   2087 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
   2088                                        LValue &LVal, QualType EltTy,
   2089                                        bool Imag) {
   2090   if (Imag) {
   2091     CharUnits SizeOfComponent;
   2092     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
   2093       return false;
   2094     LVal.Offset += SizeOfComponent;
   2095   }
   2096   LVal.addComplex(Info, E, EltTy, Imag);
   2097   return true;
   2098 }
   2099 
   2100 /// Try to evaluate the initializer for a variable declaration.
   2101 ///
   2102 /// \param Info   Information about the ongoing evaluation.
   2103 /// \param E      An expression to be used when printing diagnostics.
   2104 /// \param VD     The variable whose initializer should be obtained.
   2105 /// \param Frame  The frame in which the variable was created. Must be null
   2106 ///               if this variable is not local to the evaluation.
   2107 /// \param Result Filled in with a pointer to the value of the variable.
   2108 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
   2109                                 const VarDecl *VD, CallStackFrame *Frame,
   2110                                 APValue *&Result) {
   2111   // If this is a parameter to an active constexpr function call, perform
   2112   // argument substitution.
   2113   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
   2114     // Assume arguments of a potential constant expression are unknown
   2115     // constant expressions.
   2116     if (Info.checkingPotentialConstantExpression())
   2117       return false;
   2118     if (!Frame || !Frame->Arguments) {
   2119       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   2120       return false;
   2121     }
   2122     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
   2123     return true;
   2124   }
   2125 
   2126   // If this is a local variable, dig out its value.
   2127   if (Frame) {
   2128     Result = Frame->getTemporary(VD);
   2129     if (!Result) {
   2130       // Assume variables referenced within a lambda's call operator that were
   2131       // not declared within the call operator are captures and during checking
   2132       // of a potential constant expression, assume they are unknown constant
   2133       // expressions.
   2134       assert(isLambdaCallOperator(Frame->Callee) &&
   2135              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
   2136              "missing value for local variable");
   2137       if (Info.checkingPotentialConstantExpression())
   2138         return false;
   2139       // FIXME: implement capture evaluation during constant expr evaluation.
   2140       Info.FFDiag(E->getLocStart(),
   2141            diag::note_unimplemented_constexpr_lambda_feature_ast)
   2142           << "captures not currently allowed";
   2143       return false;
   2144     }
   2145     return true;
   2146   }
   2147 
   2148   // Dig out the initializer, and use the declaration which it's attached to.
   2149   const Expr *Init = VD->getAnyInitializer(VD);
   2150   if (!Init || Init->isValueDependent()) {
   2151     // If we're checking a potential constant expression, the variable could be
   2152     // initialized later.
   2153     if (!Info.checkingPotentialConstantExpression())
   2154       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   2155     return false;
   2156   }
   2157 
   2158   // If we're currently evaluating the initializer of this declaration, use that
   2159   // in-flight value.
   2160   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
   2161     Result = Info.EvaluatingDeclValue;
   2162     return true;
   2163   }
   2164 
   2165   // Never evaluate the initializer of a weak variable. We can't be sure that
   2166   // this is the definition which will be used.
   2167   if (VD->isWeak()) {
   2168     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   2169     return false;
   2170   }
   2171 
   2172   // Check that we can fold the initializer. In C++, we will have already done
   2173   // this in the cases where it matters for conformance.
   2174   SmallVector<PartialDiagnosticAt, 8> Notes;
   2175   if (!VD->evaluateValue(Notes)) {
   2176     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
   2177               Notes.size() + 1) << VD;
   2178     Info.Note(VD->getLocation(), diag::note_declared_at);
   2179     Info.addNotes(Notes);
   2180     return false;
   2181   } else if (!VD->checkInitIsICE()) {
   2182     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
   2183                  Notes.size() + 1) << VD;
   2184     Info.Note(VD->getLocation(), diag::note_declared_at);
   2185     Info.addNotes(Notes);
   2186   }
   2187 
   2188   Result = VD->getEvaluatedValue();
   2189   return true;
   2190 }
   2191 
   2192 static bool IsConstNonVolatile(QualType T) {
   2193   Qualifiers Quals = T.getQualifiers();
   2194   return Quals.hasConst() && !Quals.hasVolatile();
   2195 }
   2196 
   2197 /// Get the base index of the given base class within an APValue representing
   2198 /// the given derived class.
   2199 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
   2200                              const CXXRecordDecl *Base) {
   2201   Base = Base->getCanonicalDecl();
   2202   unsigned Index = 0;
   2203   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
   2204          E = Derived->bases_end(); I != E; ++I, ++Index) {
   2205     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
   2206       return Index;
   2207   }
   2208 
   2209   llvm_unreachable("base class missing from derived class's bases list");
   2210 }
   2211 
   2212 /// Extract the value of a character from a string literal.
   2213 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
   2214                                             uint64_t Index) {
   2215   // FIXME: Support ObjCEncodeExpr, MakeStringConstant
   2216   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
   2217     Lit = PE->getFunctionName();
   2218   const StringLiteral *S = cast<StringLiteral>(Lit);
   2219   const ConstantArrayType *CAT =
   2220       Info.Ctx.getAsConstantArrayType(S->getType());
   2221   assert(CAT && "string literal isn't an array");
   2222   QualType CharType = CAT->getElementType();
   2223   assert(CharType->isIntegerType() && "unexpected character type");
   2224 
   2225   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
   2226                CharType->isUnsignedIntegerType());
   2227   if (Index < S->getLength())
   2228     Value = S->getCodeUnit(Index);
   2229   return Value;
   2230 }
   2231 
   2232 // Expand a string literal into an array of characters.
   2233 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
   2234                                 APValue &Result) {
   2235   const StringLiteral *S = cast<StringLiteral>(Lit);
   2236   const ConstantArrayType *CAT =
   2237       Info.Ctx.getAsConstantArrayType(S->getType());
   2238   assert(CAT && "string literal isn't an array");
   2239   QualType CharType = CAT->getElementType();
   2240   assert(CharType->isIntegerType() && "unexpected character type");
   2241 
   2242   unsigned Elts = CAT->getSize().getZExtValue();
   2243   Result = APValue(APValue::UninitArray(),
   2244                    std::min(S->getLength(), Elts), Elts);
   2245   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
   2246                CharType->isUnsignedIntegerType());
   2247   if (Result.hasArrayFiller())
   2248     Result.getArrayFiller() = APValue(Value);
   2249   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
   2250     Value = S->getCodeUnit(I);
   2251     Result.getArrayInitializedElt(I) = APValue(Value);
   2252   }
   2253 }
   2254 
   2255 // Expand an array so that it has more than Index filled elements.
   2256 static void expandArray(APValue &Array, unsigned Index) {
   2257   unsigned Size = Array.getArraySize();
   2258   assert(Index < Size);
   2259 
   2260   // Always at least double the number of elements for which we store a value.
   2261   unsigned OldElts = Array.getArrayInitializedElts();
   2262   unsigned NewElts = std::max(Index+1, OldElts * 2);
   2263   NewElts = std::min(Size, std::max(NewElts, 8u));
   2264 
   2265   // Copy the data across.
   2266   APValue NewValue(APValue::UninitArray(), NewElts, Size);
   2267   for (unsigned I = 0; I != OldElts; ++I)
   2268     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
   2269   for (unsigned I = OldElts; I != NewElts; ++I)
   2270     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
   2271   if (NewValue.hasArrayFiller())
   2272     NewValue.getArrayFiller() = Array.getArrayFiller();
   2273   Array.swap(NewValue);
   2274 }
   2275 
   2276 /// Determine whether a type would actually be read by an lvalue-to-rvalue
   2277 /// conversion. If it's of class type, we may assume that the copy operation
   2278 /// is trivial. Note that this is never true for a union type with fields
   2279 /// (because the copy always "reads" the active member) and always true for
   2280 /// a non-class type.
   2281 static bool isReadByLvalueToRvalueConversion(QualType T) {
   2282   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
   2283   if (!RD || (RD->isUnion() && !RD->field_empty()))
   2284     return true;
   2285   if (RD->isEmpty())
   2286     return false;
   2287 
   2288   for (auto *Field : RD->fields())
   2289     if (isReadByLvalueToRvalueConversion(Field->getType()))
   2290       return true;
   2291 
   2292   for (auto &BaseSpec : RD->bases())
   2293     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
   2294       return true;
   2295 
   2296   return false;
   2297 }
   2298 
   2299 /// Diagnose an attempt to read from any unreadable field within the specified
   2300 /// type, which might be a class type.
   2301 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
   2302                                      QualType T) {
   2303   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
   2304   if (!RD)
   2305     return false;
   2306 
   2307   if (!RD->hasMutableFields())
   2308     return false;
   2309 
   2310   for (auto *Field : RD->fields()) {
   2311     // If we're actually going to read this field in some way, then it can't
   2312     // be mutable. If we're in a union, then assigning to a mutable field
   2313     // (even an empty one) can change the active member, so that's not OK.
   2314     // FIXME: Add core issue number for the union case.
   2315     if (Field->isMutable() &&
   2316         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
   2317       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
   2318       Info.Note(Field->getLocation(), diag::note_declared_at);
   2319       return true;
   2320     }
   2321 
   2322     if (diagnoseUnreadableFields(Info, E, Field->getType()))
   2323       return true;
   2324   }
   2325 
   2326   for (auto &BaseSpec : RD->bases())
   2327     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
   2328       return true;
   2329 
   2330   // All mutable fields were empty, and thus not actually read.
   2331   return false;
   2332 }
   2333 
   2334 /// Kinds of access we can perform on an object, for diagnostics.
   2335 enum AccessKinds {
   2336   AK_Read,
   2337   AK_Assign,
   2338   AK_Increment,
   2339   AK_Decrement
   2340 };
   2341 
   2342 namespace {
   2343 /// A handle to a complete object (an object that is not a subobject of
   2344 /// another object).
   2345 struct CompleteObject {
   2346   /// The value of the complete object.
   2347   APValue *Value;
   2348   /// The type of the complete object.
   2349   QualType Type;
   2350 
   2351   CompleteObject() : Value(nullptr) {}
   2352   CompleteObject(APValue *Value, QualType Type)
   2353       : Value(Value), Type(Type) {
   2354     assert(Value && "missing value for complete object");
   2355   }
   2356 
   2357   explicit operator bool() const { return Value; }
   2358 };
   2359 } // end anonymous namespace
   2360 
   2361 /// Find the designated sub-object of an rvalue.
   2362 template<typename SubobjectHandler>
   2363 typename SubobjectHandler::result_type
   2364 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
   2365               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
   2366   if (Sub.Invalid)
   2367     // A diagnostic will have already been produced.
   2368     return handler.failed();
   2369   if (Sub.isOnePastTheEnd()) {
   2370     if (Info.getLangOpts().CPlusPlus11)
   2371       Info.FFDiag(E, diag::note_constexpr_access_past_end)
   2372         << handler.AccessKind;
   2373     else
   2374       Info.FFDiag(E);
   2375     return handler.failed();
   2376   }
   2377 
   2378   APValue *O = Obj.Value;
   2379   QualType ObjType = Obj.Type;
   2380   const FieldDecl *LastField = nullptr;
   2381 
   2382   // Walk the designator's path to find the subobject.
   2383   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
   2384     if (O->isUninit()) {
   2385       if (!Info.checkingPotentialConstantExpression())
   2386         Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
   2387       return handler.failed();
   2388     }
   2389 
   2390     if (I == N) {
   2391       // If we are reading an object of class type, there may still be more
   2392       // things we need to check: if there are any mutable subobjects, we
   2393       // cannot perform this read. (This only happens when performing a trivial
   2394       // copy or assignment.)
   2395       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
   2396           diagnoseUnreadableFields(Info, E, ObjType))
   2397         return handler.failed();
   2398 
   2399       if (!handler.found(*O, ObjType))
   2400         return false;
   2401 
   2402       // If we modified a bit-field, truncate it to the right width.
   2403       if (handler.AccessKind != AK_Read &&
   2404           LastField && LastField->isBitField() &&
   2405           !truncateBitfieldValue(Info, E, *O, LastField))
   2406         return false;
   2407 
   2408       return true;
   2409     }
   2410 
   2411     LastField = nullptr;
   2412     if (ObjType->isArrayType()) {
   2413       // Next subobject is an array element.
   2414       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
   2415       assert(CAT && "vla in literal type?");
   2416       uint64_t Index = Sub.Entries[I].ArrayIndex;
   2417       if (CAT->getSize().ule(Index)) {
   2418         // Note, it should not be possible to form a pointer with a valid
   2419         // designator which points more than one past the end of the array.
   2420         if (Info.getLangOpts().CPlusPlus11)
   2421           Info.FFDiag(E, diag::note_constexpr_access_past_end)
   2422             << handler.AccessKind;
   2423         else
   2424           Info.FFDiag(E);
   2425         return handler.failed();
   2426       }
   2427 
   2428       ObjType = CAT->getElementType();
   2429 
   2430       // An array object is represented as either an Array APValue or as an
   2431       // LValue which refers to a string literal.
   2432       if (O->isLValue()) {
   2433         assert(I == N - 1 && "extracting subobject of character?");
   2434         assert(!O->hasLValuePath() || O->getLValuePath().empty());
   2435         if (handler.AccessKind != AK_Read)
   2436           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
   2437                               *O);
   2438         else
   2439           return handler.foundString(*O, ObjType, Index);
   2440       }
   2441 
   2442       if (O->getArrayInitializedElts() > Index)
   2443         O = &O->getArrayInitializedElt(Index);
   2444       else if (handler.AccessKind != AK_Read) {
   2445         expandArray(*O, Index);
   2446         O = &O->getArrayInitializedElt(Index);
   2447       } else
   2448         O = &O->getArrayFiller();
   2449     } else if (ObjType->isAnyComplexType()) {
   2450       // Next subobject is a complex number.
   2451       uint64_t Index = Sub.Entries[I].ArrayIndex;
   2452       if (Index > 1) {
   2453         if (Info.getLangOpts().CPlusPlus11)
   2454           Info.FFDiag(E, diag::note_constexpr_access_past_end)
   2455             << handler.AccessKind;
   2456         else
   2457           Info.FFDiag(E);
   2458         return handler.failed();
   2459       }
   2460 
   2461       bool WasConstQualified = ObjType.isConstQualified();
   2462       ObjType = ObjType->castAs<ComplexType>()->getElementType();
   2463       if (WasConstQualified)
   2464         ObjType.addConst();
   2465 
   2466       assert(I == N - 1 && "extracting subobject of scalar?");
   2467       if (O->isComplexInt()) {
   2468         return handler.found(Index ? O->getComplexIntImag()
   2469                                    : O->getComplexIntReal(), ObjType);
   2470       } else {
   2471         assert(O->isComplexFloat());
   2472         return handler.found(Index ? O->getComplexFloatImag()
   2473                                    : O->getComplexFloatReal(), ObjType);
   2474       }
   2475     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
   2476       if (Field->isMutable() && handler.AccessKind == AK_Read) {
   2477         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
   2478           << Field;
   2479         Info.Note(Field->getLocation(), diag::note_declared_at);
   2480         return handler.failed();
   2481       }
   2482 
   2483       // Next subobject is a class, struct or union field.
   2484       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
   2485       if (RD->isUnion()) {
   2486         const FieldDecl *UnionField = O->getUnionField();
   2487         if (!UnionField ||
   2488             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
   2489           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
   2490             << handler.AccessKind << Field << !UnionField << UnionField;
   2491           return handler.failed();
   2492         }
   2493         O = &O->getUnionValue();
   2494       } else
   2495         O = &O->getStructField(Field->getFieldIndex());
   2496 
   2497       bool WasConstQualified = ObjType.isConstQualified();
   2498       ObjType = Field->getType();
   2499       if (WasConstQualified && !Field->isMutable())
   2500         ObjType.addConst();
   2501 
   2502       if (ObjType.isVolatileQualified()) {
   2503         if (Info.getLangOpts().CPlusPlus) {
   2504           // FIXME: Include a description of the path to the volatile subobject.
   2505           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
   2506             << handler.AccessKind << 2 << Field;
   2507           Info.Note(Field->getLocation(), diag::note_declared_at);
   2508         } else {
   2509           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   2510         }
   2511         return handler.failed();
   2512       }
   2513 
   2514       LastField = Field;
   2515     } else {
   2516       // Next subobject is a base class.
   2517       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
   2518       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
   2519       O = &O->getStructBase(getBaseIndex(Derived, Base));
   2520 
   2521       bool WasConstQualified = ObjType.isConstQualified();
   2522       ObjType = Info.Ctx.getRecordType(Base);
   2523       if (WasConstQualified)
   2524         ObjType.addConst();
   2525     }
   2526   }
   2527 }
   2528 
   2529 namespace {
   2530 struct ExtractSubobjectHandler {
   2531   EvalInfo &Info;
   2532   APValue &Result;
   2533 
   2534   static const AccessKinds AccessKind = AK_Read;
   2535 
   2536   typedef bool result_type;
   2537   bool failed() { return false; }
   2538   bool found(APValue &Subobj, QualType SubobjType) {
   2539     Result = Subobj;
   2540     return true;
   2541   }
   2542   bool found(APSInt &Value, QualType SubobjType) {
   2543     Result = APValue(Value);
   2544     return true;
   2545   }
   2546   bool found(APFloat &Value, QualType SubobjType) {
   2547     Result = APValue(Value);
   2548     return true;
   2549   }
   2550   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
   2551     Result = APValue(extractStringLiteralCharacter(
   2552         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
   2553     return true;
   2554   }
   2555 };
   2556 } // end anonymous namespace
   2557 
   2558 const AccessKinds ExtractSubobjectHandler::AccessKind;
   2559 
   2560 /// Extract the designated sub-object of an rvalue.
   2561 static bool extractSubobject(EvalInfo &Info, const Expr *E,
   2562                              const CompleteObject &Obj,
   2563                              const SubobjectDesignator &Sub,
   2564                              APValue &Result) {
   2565   ExtractSubobjectHandler Handler = { Info, Result };
   2566   return findSubobject(Info, E, Obj, Sub, Handler);
   2567 }
   2568 
   2569 namespace {
   2570 struct ModifySubobjectHandler {
   2571   EvalInfo &Info;
   2572   APValue &NewVal;
   2573   const Expr *E;
   2574 
   2575   typedef bool result_type;
   2576   static const AccessKinds AccessKind = AK_Assign;
   2577 
   2578   bool checkConst(QualType QT) {
   2579     // Assigning to a const object has undefined behavior.
   2580     if (QT.isConstQualified()) {
   2581       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
   2582       return false;
   2583     }
   2584     return true;
   2585   }
   2586 
   2587   bool failed() { return false; }
   2588   bool found(APValue &Subobj, QualType SubobjType) {
   2589     if (!checkConst(SubobjType))
   2590       return false;
   2591     // We've been given ownership of NewVal, so just swap it in.
   2592     Subobj.swap(NewVal);
   2593     return true;
   2594   }
   2595   bool found(APSInt &Value, QualType SubobjType) {
   2596     if (!checkConst(SubobjType))
   2597       return false;
   2598     if (!NewVal.isInt()) {
   2599       // Maybe trying to write a cast pointer value into a complex?
   2600       Info.FFDiag(E);
   2601       return false;
   2602     }
   2603     Value = NewVal.getInt();
   2604     return true;
   2605   }
   2606   bool found(APFloat &Value, QualType SubobjType) {
   2607     if (!checkConst(SubobjType))
   2608       return false;
   2609     Value = NewVal.getFloat();
   2610     return true;
   2611   }
   2612   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
   2613     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
   2614   }
   2615 };
   2616 } // end anonymous namespace
   2617 
   2618 const AccessKinds ModifySubobjectHandler::AccessKind;
   2619 
   2620 /// Update the designated sub-object of an rvalue to the given value.
   2621 static bool modifySubobject(EvalInfo &Info, const Expr *E,
   2622                             const CompleteObject &Obj,
   2623                             const SubobjectDesignator &Sub,
   2624                             APValue &NewVal) {
   2625   ModifySubobjectHandler Handler = { Info, NewVal, E };
   2626   return findSubobject(Info, E, Obj, Sub, Handler);
   2627 }
   2628 
   2629 /// Find the position where two subobject designators diverge, or equivalently
   2630 /// the length of the common initial subsequence.
   2631 static unsigned FindDesignatorMismatch(QualType ObjType,
   2632                                        const SubobjectDesignator &A,
   2633                                        const SubobjectDesignator &B,
   2634                                        bool &WasArrayIndex) {
   2635   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
   2636   for (/**/; I != N; ++I) {
   2637     if (!ObjType.isNull() &&
   2638         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
   2639       // Next subobject is an array element.
   2640       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
   2641         WasArrayIndex = true;
   2642         return I;
   2643       }
   2644       if (ObjType->isAnyComplexType())
   2645         ObjType = ObjType->castAs<ComplexType>()->getElementType();
   2646       else
   2647         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
   2648     } else {
   2649       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
   2650         WasArrayIndex = false;
   2651         return I;
   2652       }
   2653       if (const FieldDecl *FD = getAsField(A.Entries[I]))
   2654         // Next subobject is a field.
   2655         ObjType = FD->getType();
   2656       else
   2657         // Next subobject is a base class.
   2658         ObjType = QualType();
   2659     }
   2660   }
   2661   WasArrayIndex = false;
   2662   return I;
   2663 }
   2664 
   2665 /// Determine whether the given subobject designators refer to elements of the
   2666 /// same array object.
   2667 static bool AreElementsOfSameArray(QualType ObjType,
   2668                                    const SubobjectDesignator &A,
   2669                                    const SubobjectDesignator &B) {
   2670   if (A.Entries.size() != B.Entries.size())
   2671     return false;
   2672 
   2673   bool IsArray = A.MostDerivedIsArrayElement;
   2674   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
   2675     // A is a subobject of the array element.
   2676     return false;
   2677 
   2678   // If A (and B) designates an array element, the last entry will be the array
   2679   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
   2680   // of length 1' case, and the entire path must match.
   2681   bool WasArrayIndex;
   2682   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
   2683   return CommonLength >= A.Entries.size() - IsArray;
   2684 }
   2685 
   2686 /// Find the complete object to which an LValue refers.
   2687 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
   2688                                          AccessKinds AK, const LValue &LVal,
   2689                                          QualType LValType) {
   2690   if (!LVal.Base) {
   2691     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
   2692     return CompleteObject();
   2693   }
   2694 
   2695   CallStackFrame *Frame = nullptr;
   2696   if (LVal.CallIndex) {
   2697     Frame = Info.getCallFrame(LVal.CallIndex);
   2698     if (!Frame) {
   2699       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
   2700         << AK << LVal.Base.is<const ValueDecl*>();
   2701       NoteLValueLocation(Info, LVal.Base);
   2702       return CompleteObject();
   2703     }
   2704   }
   2705 
   2706   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
   2707   // is not a constant expression (even if the object is non-volatile). We also
   2708   // apply this rule to C++98, in order to conform to the expected 'volatile'
   2709   // semantics.
   2710   if (LValType.isVolatileQualified()) {
   2711     if (Info.getLangOpts().CPlusPlus)
   2712       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
   2713         << AK << LValType;
   2714     else
   2715       Info.FFDiag(E);
   2716     return CompleteObject();
   2717   }
   2718 
   2719   // Compute value storage location and type of base object.
   2720   APValue *BaseVal = nullptr;
   2721   QualType BaseType = getType(LVal.Base);
   2722 
   2723   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
   2724     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
   2725     // In C++11, constexpr, non-volatile variables initialized with constant
   2726     // expressions are constant expressions too. Inside constexpr functions,
   2727     // parameters are constant expressions even if they're non-const.
   2728     // In C++1y, objects local to a constant expression (those with a Frame) are
   2729     // both readable and writable inside constant expressions.
   2730     // In C, such things can also be folded, although they are not ICEs.
   2731     const VarDecl *VD = dyn_cast<VarDecl>(D);
   2732     if (VD) {
   2733       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
   2734         VD = VDef;
   2735     }
   2736     if (!VD || VD->isInvalidDecl()) {
   2737       Info.FFDiag(E);
   2738       return CompleteObject();
   2739     }
   2740 
   2741     // Accesses of volatile-qualified objects are not allowed.
   2742     if (BaseType.isVolatileQualified()) {
   2743       if (Info.getLangOpts().CPlusPlus) {
   2744         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
   2745           << AK << 1 << VD;
   2746         Info.Note(VD->getLocation(), diag::note_declared_at);
   2747       } else {
   2748         Info.FFDiag(E);
   2749       }
   2750       return CompleteObject();
   2751     }
   2752 
   2753     // Unless we're looking at a local variable or argument in a constexpr call,
   2754     // the variable we're reading must be const.
   2755     if (!Frame) {
   2756       if (Info.getLangOpts().CPlusPlus14 &&
   2757           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
   2758         // OK, we can read and modify an object if we're in the process of
   2759         // evaluating its initializer, because its lifetime began in this
   2760         // evaluation.
   2761       } else if (AK != AK_Read) {
   2762         // All the remaining cases only permit reading.
   2763         Info.FFDiag(E, diag::note_constexpr_modify_global);
   2764         return CompleteObject();
   2765       } else if (VD->isConstexpr()) {
   2766         // OK, we can read this variable.
   2767       } else if (BaseType->isIntegralOrEnumerationType()) {
   2768         // In OpenCL if a variable is in constant address space it is a const value.
   2769         if (!(BaseType.isConstQualified() ||
   2770               (Info.getLangOpts().OpenCL &&
   2771                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
   2772           if (Info.getLangOpts().CPlusPlus) {
   2773             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
   2774             Info.Note(VD->getLocation(), diag::note_declared_at);
   2775           } else {
   2776             Info.FFDiag(E);
   2777           }
   2778           return CompleteObject();
   2779         }
   2780       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
   2781         // We support folding of const floating-point types, in order to make
   2782         // static const data members of such types (supported as an extension)
   2783         // more useful.
   2784         if (Info.getLangOpts().CPlusPlus11) {
   2785           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
   2786           Info.Note(VD->getLocation(), diag::note_declared_at);
   2787         } else {
   2788           Info.CCEDiag(E);
   2789         }
   2790       } else {
   2791         // FIXME: Allow folding of values of any literal type in all languages.
   2792         if (Info.checkingPotentialConstantExpression() &&
   2793             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
   2794           // The definition of this variable could be constexpr. We can't
   2795           // access it right now, but may be able to in future.
   2796         } else if (Info.getLangOpts().CPlusPlus11) {
   2797           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
   2798           Info.Note(VD->getLocation(), diag::note_declared_at);
   2799         } else {
   2800           Info.FFDiag(E);
   2801         }
   2802         return CompleteObject();
   2803       }
   2804     }
   2805 
   2806     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
   2807       return CompleteObject();
   2808   } else {
   2809     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
   2810 
   2811     if (!Frame) {
   2812       if (const MaterializeTemporaryExpr *MTE =
   2813               dyn_cast<MaterializeTemporaryExpr>(Base)) {
   2814         assert(MTE->getStorageDuration() == SD_Static &&
   2815                "should have a frame for a non-global materialized temporary");
   2816 
   2817         // Per C++1y [expr.const]p2:
   2818         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
   2819         //   - a [...] glvalue of integral or enumeration type that refers to
   2820         //     a non-volatile const object [...]
   2821         //   [...]
   2822         //   - a [...] glvalue of literal type that refers to a non-volatile
   2823         //     object whose lifetime began within the evaluation of e.
   2824         //
   2825         // C++11 misses the 'began within the evaluation of e' check and
   2826         // instead allows all temporaries, including things like:
   2827         //   int &&r = 1;
   2828         //   int x = ++r;
   2829         //   constexpr int k = r;
   2830         // Therefore we use the C++1y rules in C++11 too.
   2831         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
   2832         const ValueDecl *ED = MTE->getExtendingDecl();
   2833         if (!(BaseType.isConstQualified() &&
   2834               BaseType->isIntegralOrEnumerationType()) &&
   2835             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
   2836           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
   2837           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
   2838           return CompleteObject();
   2839         }
   2840 
   2841         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
   2842         assert(BaseVal && "got reference to unevaluated temporary");
   2843       } else {
   2844         Info.FFDiag(E);
   2845         return CompleteObject();
   2846       }
   2847     } else {
   2848       BaseVal = Frame->getTemporary(Base);
   2849       assert(BaseVal && "missing value for temporary");
   2850     }
   2851 
   2852     // Volatile temporary objects cannot be accessed in constant expressions.
   2853     if (BaseType.isVolatileQualified()) {
   2854       if (Info.getLangOpts().CPlusPlus) {
   2855         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
   2856           << AK << 0;
   2857         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
   2858       } else {
   2859         Info.FFDiag(E);
   2860       }
   2861       return CompleteObject();
   2862     }
   2863   }
   2864 
   2865   // During the construction of an object, it is not yet 'const'.
   2866   // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
   2867   // and this doesn't do quite the right thing for const subobjects of the
   2868   // object under construction.
   2869   if (LVal.getLValueBase() == Info.EvaluatingDecl) {
   2870     BaseType = Info.Ctx.getCanonicalType(BaseType);
   2871     BaseType.removeLocalConst();
   2872   }
   2873 
   2874   // In C++1y, we can't safely access any mutable state when we might be
   2875   // evaluating after an unmodeled side effect.
   2876   //
   2877   // FIXME: Not all local state is mutable. Allow local constant subobjects
   2878   // to be read here (but take care with 'mutable' fields).
   2879   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
   2880        Info.EvalStatus.HasSideEffects) ||
   2881       (AK != AK_Read && Info.IsSpeculativelyEvaluating))
   2882     return CompleteObject();
   2883 
   2884   return CompleteObject(BaseVal, BaseType);
   2885 }
   2886 
   2887 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
   2888 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
   2889 /// glvalue referred to by an entity of reference type.
   2890 ///
   2891 /// \param Info - Information about the ongoing evaluation.
   2892 /// \param Conv - The expression for which we are performing the conversion.
   2893 ///               Used for diagnostics.
   2894 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
   2895 ///               case of a non-class type).
   2896 /// \param LVal - The glvalue on which we are attempting to perform this action.
   2897 /// \param RVal - The produced value will be placed here.
   2898 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
   2899                                            QualType Type,
   2900                                            const LValue &LVal, APValue &RVal) {
   2901   if (LVal.Designator.Invalid)
   2902     return false;
   2903 
   2904   // Check for special cases where there is no existing APValue to look at.
   2905   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
   2906   if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
   2907     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
   2908       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
   2909       // initializer until now for such expressions. Such an expression can't be
   2910       // an ICE in C, so this only matters for fold.
   2911       assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
   2912       if (Type.isVolatileQualified()) {
   2913         Info.FFDiag(Conv);
   2914         return false;
   2915       }
   2916       APValue Lit;
   2917       if (!Evaluate(Lit, Info, CLE->getInitializer()))
   2918         return false;
   2919       CompleteObject LitObj(&Lit, Base->getType());
   2920       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
   2921     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
   2922       // We represent a string literal array as an lvalue pointing at the
   2923       // corresponding expression, rather than building an array of chars.
   2924       // FIXME: Support ObjCEncodeExpr, MakeStringConstant
   2925       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
   2926       CompleteObject StrObj(&Str, Base->getType());
   2927       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
   2928     }
   2929   }
   2930 
   2931   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
   2932   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
   2933 }
   2934 
   2935 /// Perform an assignment of Val to LVal. Takes ownership of Val.
   2936 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
   2937                              QualType LValType, APValue &Val) {
   2938   if (LVal.Designator.Invalid)
   2939     return false;
   2940 
   2941   if (!Info.getLangOpts().CPlusPlus14) {
   2942     Info.FFDiag(E);
   2943     return false;
   2944   }
   2945 
   2946   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
   2947   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
   2948 }
   2949 
   2950 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
   2951   return T->isSignedIntegerType() &&
   2952          Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
   2953 }
   2954 
   2955 namespace {
   2956 struct CompoundAssignSubobjectHandler {
   2957   EvalInfo &Info;
   2958   const Expr *E;
   2959   QualType PromotedLHSType;
   2960   BinaryOperatorKind Opcode;
   2961   const APValue &RHS;
   2962 
   2963   static const AccessKinds AccessKind = AK_Assign;
   2964 
   2965   typedef bool result_type;
   2966 
   2967   bool checkConst(QualType QT) {
   2968     // Assigning to a const object has undefined behavior.
   2969     if (QT.isConstQualified()) {
   2970       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
   2971       return false;
   2972     }
   2973     return true;
   2974   }
   2975 
   2976   bool failed() { return false; }
   2977   bool found(APValue &Subobj, QualType SubobjType) {
   2978     switch (Subobj.getKind()) {
   2979     case APValue::Int:
   2980       return found(Subobj.getInt(), SubobjType);
   2981     case APValue::Float:
   2982       return found(Subobj.getFloat(), SubobjType);
   2983     case APValue::ComplexInt:
   2984     case APValue::ComplexFloat:
   2985       // FIXME: Implement complex compound assignment.
   2986       Info.FFDiag(E);
   2987       return false;
   2988     case APValue::LValue:
   2989       return foundPointer(Subobj, SubobjType);
   2990     default:
   2991       // FIXME: can this happen?
   2992       Info.FFDiag(E);
   2993       return false;
   2994     }
   2995   }
   2996   bool found(APSInt &Value, QualType SubobjType) {
   2997     if (!checkConst(SubobjType))
   2998       return false;
   2999 
   3000     if (!SubobjType->isIntegerType() || !RHS.isInt()) {
   3001       // We don't support compound assignment on integer-cast-to-pointer
   3002       // values.
   3003       Info.FFDiag(E);
   3004       return false;
   3005     }
   3006 
   3007     APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
   3008                                     SubobjType, Value);
   3009     if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
   3010       return false;
   3011     Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
   3012     return true;
   3013   }
   3014   bool found(APFloat &Value, QualType SubobjType) {
   3015     return checkConst(SubobjType) &&
   3016            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
   3017                                   Value) &&
   3018            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
   3019            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
   3020   }
   3021   bool foundPointer(APValue &Subobj, QualType SubobjType) {
   3022     if (!checkConst(SubobjType))
   3023       return false;
   3024 
   3025     QualType PointeeType;
   3026     if (const PointerType *PT = SubobjType->getAs<PointerType>())
   3027       PointeeType = PT->getPointeeType();
   3028 
   3029     if (PointeeType.isNull() || !RHS.isInt() ||
   3030         (Opcode != BO_Add && Opcode != BO_Sub)) {
   3031       Info.FFDiag(E);
   3032       return false;
   3033     }
   3034 
   3035     int64_t Offset = getExtValue(RHS.getInt());
   3036     if (Opcode == BO_Sub)
   3037       Offset = -Offset;
   3038 
   3039     LValue LVal;
   3040     LVal.setFrom(Info.Ctx, Subobj);
   3041     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
   3042       return false;
   3043     LVal.moveInto(Subobj);
   3044     return true;
   3045   }
   3046   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
   3047     llvm_unreachable("shouldn't encounter string elements here");
   3048   }
   3049 };
   3050 } // end anonymous namespace
   3051 
   3052 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
   3053 
   3054 /// Perform a compound assignment of LVal <op>= RVal.
   3055 static bool handleCompoundAssignment(
   3056     EvalInfo &Info, const Expr *E,
   3057     const LValue &LVal, QualType LValType, QualType PromotedLValType,
   3058     BinaryOperatorKind Opcode, const APValue &RVal) {
   3059   if (LVal.Designator.Invalid)
   3060     return false;
   3061 
   3062   if (!Info.getLangOpts().CPlusPlus14) {
   3063     Info.FFDiag(E);
   3064     return false;
   3065   }
   3066 
   3067   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
   3068   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
   3069                                              RVal };
   3070   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
   3071 }
   3072 
   3073 namespace {
   3074 struct IncDecSubobjectHandler {
   3075   EvalInfo &Info;
   3076   const Expr *E;
   3077   AccessKinds AccessKind;
   3078   APValue *Old;
   3079 
   3080   typedef bool result_type;
   3081 
   3082   bool checkConst(QualType QT) {
   3083     // Assigning to a const object has undefined behavior.
   3084     if (QT.isConstQualified()) {
   3085       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
   3086       return false;
   3087     }
   3088     return true;
   3089   }
   3090 
   3091   bool failed() { return false; }
   3092   bool found(APValue &Subobj, QualType SubobjType) {
   3093     // Stash the old value. Also clear Old, so we don't clobber it later
   3094     // if we're post-incrementing a complex.
   3095     if (Old) {
   3096       *Old = Subobj;
   3097       Old = nullptr;
   3098     }
   3099 
   3100     switch (Subobj.getKind()) {
   3101     case APValue::Int:
   3102       return found(Subobj.getInt(), SubobjType);
   3103     case APValue::Float:
   3104       return found(Subobj.getFloat(), SubobjType);
   3105     case APValue::ComplexInt:
   3106       return found(Subobj.getComplexIntReal(),
   3107                    SubobjType->castAs<ComplexType>()->getElementType()
   3108                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
   3109     case APValue::ComplexFloat:
   3110       return found(Subobj.getComplexFloatReal(),
   3111                    SubobjType->castAs<ComplexType>()->getElementType()
   3112                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
   3113     case APValue::LValue:
   3114       return foundPointer(Subobj, SubobjType);
   3115     default:
   3116       // FIXME: can this happen?
   3117       Info.FFDiag(E);
   3118       return false;
   3119     }
   3120   }
   3121   bool found(APSInt &Value, QualType SubobjType) {
   3122     if (!checkConst(SubobjType))
   3123       return false;
   3124 
   3125     if (!SubobjType->isIntegerType()) {
   3126       // We don't support increment / decrement on integer-cast-to-pointer
   3127       // values.
   3128       Info.FFDiag(E);
   3129       return false;
   3130     }
   3131 
   3132     if (Old) *Old = APValue(Value);
   3133 
   3134     // bool arithmetic promotes to int, and the conversion back to bool
   3135     // doesn't reduce mod 2^n, so special-case it.
   3136     if (SubobjType->isBooleanType()) {
   3137       if (AccessKind == AK_Increment)
   3138         Value = 1;
   3139       else
   3140         Value = !Value;
   3141       return true;
   3142     }
   3143 
   3144     bool WasNegative = Value.isNegative();
   3145     if (AccessKind == AK_Increment) {
   3146       ++Value;
   3147 
   3148       if (!WasNegative && Value.isNegative() &&
   3149           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
   3150         APSInt ActualValue(Value, /*IsUnsigned*/true);
   3151         return HandleOverflow(Info, E, ActualValue, SubobjType);
   3152       }
   3153     } else {
   3154       --Value;
   3155 
   3156       if (WasNegative && !Value.isNegative() &&
   3157           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
   3158         unsigned BitWidth = Value.getBitWidth();
   3159         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
   3160         ActualValue.setBit(BitWidth);
   3161         return HandleOverflow(Info, E, ActualValue, SubobjType);
   3162       }
   3163     }
   3164     return true;
   3165   }
   3166   bool found(APFloat &Value, QualType SubobjType) {
   3167     if (!checkConst(SubobjType))
   3168       return false;
   3169 
   3170     if (Old) *Old = APValue(Value);
   3171 
   3172     APFloat One(Value.getSemantics(), 1);
   3173     if (AccessKind == AK_Increment)
   3174       Value.add(One, APFloat::rmNearestTiesToEven);
   3175     else
   3176       Value.subtract(One, APFloat::rmNearestTiesToEven);
   3177     return true;
   3178   }
   3179   bool foundPointer(APValue &Subobj, QualType SubobjType) {
   3180     if (!checkConst(SubobjType))
   3181       return false;
   3182 
   3183     QualType PointeeType;
   3184     if (const PointerType *PT = SubobjType->getAs<PointerType>())
   3185       PointeeType = PT->getPointeeType();
   3186     else {
   3187       Info.FFDiag(E);
   3188       return false;
   3189     }
   3190 
   3191     LValue LVal;
   3192     LVal.setFrom(Info.Ctx, Subobj);
   3193     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
   3194                                      AccessKind == AK_Increment ? 1 : -1))
   3195       return false;
   3196     LVal.moveInto(Subobj);
   3197     return true;
   3198   }
   3199   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
   3200     llvm_unreachable("shouldn't encounter string elements here");
   3201   }
   3202 };
   3203 } // end anonymous namespace
   3204 
   3205 /// Perform an increment or decrement on LVal.
   3206 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
   3207                          QualType LValType, bool IsIncrement, APValue *Old) {
   3208   if (LVal.Designator.Invalid)
   3209     return false;
   3210 
   3211   if (!Info.getLangOpts().CPlusPlus14) {
   3212     Info.FFDiag(E);
   3213     return false;
   3214   }
   3215 
   3216   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
   3217   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
   3218   IncDecSubobjectHandler Handler = { Info, E, AK, Old };
   3219   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
   3220 }
   3221 
   3222 /// Build an lvalue for the object argument of a member function call.
   3223 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
   3224                                    LValue &This) {
   3225   if (Object->getType()->isPointerType())
   3226     return EvaluatePointer(Object, This, Info);
   3227 
   3228   if (Object->isGLValue())
   3229     return EvaluateLValue(Object, This, Info);
   3230 
   3231   if (Object->getType()->isLiteralType(Info.Ctx))
   3232     return EvaluateTemporary(Object, This, Info);
   3233 
   3234   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
   3235   return false;
   3236 }
   3237 
   3238 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
   3239 /// lvalue referring to the result.
   3240 ///
   3241 /// \param Info - Information about the ongoing evaluation.
   3242 /// \param LV - An lvalue referring to the base of the member pointer.
   3243 /// \param RHS - The member pointer expression.
   3244 /// \param IncludeMember - Specifies whether the member itself is included in
   3245 ///        the resulting LValue subobject designator. This is not possible when
   3246 ///        creating a bound member function.
   3247 /// \return The field or method declaration to which the member pointer refers,
   3248 ///         or 0 if evaluation fails.
   3249 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
   3250                                                   QualType LVType,
   3251                                                   LValue &LV,
   3252                                                   const Expr *RHS,
   3253                                                   bool IncludeMember = true) {
   3254   MemberPtr MemPtr;
   3255   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
   3256     return nullptr;
   3257 
   3258   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
   3259   // member value, the behavior is undefined.
   3260   if (!MemPtr.getDecl()) {
   3261     // FIXME: Specific diagnostic.
   3262     Info.FFDiag(RHS);
   3263     return nullptr;
   3264   }
   3265 
   3266   if (MemPtr.isDerivedMember()) {
   3267     // This is a member of some derived class. Truncate LV appropriately.
   3268     // The end of the derived-to-base path for the base object must match the
   3269     // derived-to-base path for the member pointer.
   3270     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
   3271         LV.Designator.Entries.size()) {
   3272       Info.FFDiag(RHS);
   3273       return nullptr;
   3274     }
   3275     unsigned PathLengthToMember =
   3276         LV.Designator.Entries.size() - MemPtr.Path.size();
   3277     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
   3278       const CXXRecordDecl *LVDecl = getAsBaseClass(
   3279           LV.Designator.Entries[PathLengthToMember + I]);
   3280       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
   3281       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
   3282         Info.FFDiag(RHS);
   3283         return nullptr;
   3284       }
   3285     }
   3286 
   3287     // Truncate the lvalue to the appropriate derived class.
   3288     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
   3289                             PathLengthToMember))
   3290       return nullptr;
   3291   } else if (!MemPtr.Path.empty()) {
   3292     // Extend the LValue path with the member pointer's path.
   3293     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
   3294                                   MemPtr.Path.size() + IncludeMember);
   3295 
   3296     // Walk down to the appropriate base class.
   3297     if (const PointerType *PT = LVType->getAs<PointerType>())
   3298       LVType = PT->getPointeeType();
   3299     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
   3300     assert(RD && "member pointer access on non-class-type expression");
   3301     // The first class in the path is that of the lvalue.
   3302     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
   3303       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
   3304       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
   3305         return nullptr;
   3306       RD = Base;
   3307     }
   3308     // Finally cast to the class containing the member.
   3309     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
   3310                                 MemPtr.getContainingRecord()))
   3311       return nullptr;
   3312   }
   3313 
   3314   // Add the member. Note that we cannot build bound member functions here.
   3315   if (IncludeMember) {
   3316     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
   3317       if (!HandleLValueMember(Info, RHS, LV, FD))
   3318         return nullptr;
   3319     } else if (const IndirectFieldDecl *IFD =
   3320                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
   3321       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
   3322         return nullptr;
   3323     } else {
   3324       llvm_unreachable("can't construct reference to bound member function");
   3325     }
   3326   }
   3327 
   3328   return MemPtr.getDecl();
   3329 }
   3330 
   3331 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
   3332                                                   const BinaryOperator *BO,
   3333                                                   LValue &LV,
   3334                                                   bool IncludeMember = true) {
   3335   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
   3336 
   3337   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
   3338     if (Info.noteFailure()) {
   3339       MemberPtr MemPtr;
   3340       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
   3341     }
   3342     return nullptr;
   3343   }
   3344 
   3345   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
   3346                                    BO->getRHS(), IncludeMember);
   3347 }
   3348 
   3349 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
   3350 /// the provided lvalue, which currently refers to the base object.
   3351 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
   3352                                     LValue &Result) {
   3353   SubobjectDesignator &D = Result.Designator;
   3354   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
   3355     return false;
   3356 
   3357   QualType TargetQT = E->getType();
   3358   if (const PointerType *PT = TargetQT->getAs<PointerType>())
   3359     TargetQT = PT->getPointeeType();
   3360 
   3361   // Check this cast lands within the final derived-to-base subobject path.
   3362   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
   3363     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
   3364       << D.MostDerivedType << TargetQT;
   3365     return false;
   3366   }
   3367 
   3368   // Check the type of the final cast. We don't need to check the path,
   3369   // since a cast can only be formed if the path is unique.
   3370   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
   3371   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
   3372   const CXXRecordDecl *FinalType;
   3373   if (NewEntriesSize == D.MostDerivedPathLength)
   3374     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
   3375   else
   3376     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
   3377   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
   3378     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
   3379       << D.MostDerivedType << TargetQT;
   3380     return false;
   3381   }
   3382 
   3383   // Truncate the lvalue to the appropriate derived class.
   3384   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
   3385 }
   3386 
   3387 namespace {
   3388 enum EvalStmtResult {
   3389   /// Evaluation failed.
   3390   ESR_Failed,
   3391   /// Hit a 'return' statement.
   3392   ESR_Returned,
   3393   /// Evaluation succeeded.
   3394   ESR_Succeeded,
   3395   /// Hit a 'continue' statement.
   3396   ESR_Continue,
   3397   /// Hit a 'break' statement.
   3398   ESR_Break,
   3399   /// Still scanning for 'case' or 'default' statement.
   3400   ESR_CaseNotFound
   3401 };
   3402 }
   3403 
   3404 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
   3405   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
   3406     // We don't need to evaluate the initializer for a static local.
   3407     if (!VD->hasLocalStorage())
   3408       return true;
   3409 
   3410     LValue Result;
   3411     Result.set(VD, Info.CurrentCall->Index);
   3412     APValue &Val = Info.CurrentCall->createTemporary(VD, true);
   3413 
   3414     const Expr *InitE = VD->getInit();
   3415     if (!InitE) {
   3416       Info.FFDiag(D->getLocStart(), diag::note_constexpr_uninitialized)
   3417         << false << VD->getType();
   3418       Val = APValue();
   3419       return false;
   3420     }
   3421 
   3422     if (InitE->isValueDependent())
   3423       return false;
   3424 
   3425     if (!EvaluateInPlace(Val, Info, Result, InitE)) {
   3426       // Wipe out any partially-computed value, to allow tracking that this
   3427       // evaluation failed.
   3428       Val = APValue();
   3429       return false;
   3430     }
   3431   }
   3432 
   3433   return true;
   3434 }
   3435 
   3436 /// Evaluate a condition (either a variable declaration or an expression).
   3437 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
   3438                          const Expr *Cond, bool &Result) {
   3439   FullExpressionRAII Scope(Info);
   3440   if (CondDecl && !EvaluateDecl(Info, CondDecl))
   3441     return false;
   3442   return EvaluateAsBooleanCondition(Cond, Result, Info);
   3443 }
   3444 
   3445 namespace {
   3446 /// \brief A location where the result (returned value) of evaluating a
   3447 /// statement should be stored.
   3448 struct StmtResult {
   3449   /// The APValue that should be filled in with the returned value.
   3450   APValue &Value;
   3451   /// The location containing the result, if any (used to support RVO).
   3452   const LValue *Slot;
   3453 };
   3454 }
   3455 
   3456 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
   3457                                    const Stmt *S,
   3458                                    const SwitchCase *SC = nullptr);
   3459 
   3460 /// Evaluate the body of a loop, and translate the result as appropriate.
   3461 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
   3462                                        const Stmt *Body,
   3463                                        const SwitchCase *Case = nullptr) {
   3464   BlockScopeRAII Scope(Info);
   3465   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
   3466   case ESR_Break:
   3467     return ESR_Succeeded;
   3468   case ESR_Succeeded:
   3469   case ESR_Continue:
   3470     return ESR_Continue;
   3471   case ESR_Failed:
   3472   case ESR_Returned:
   3473   case ESR_CaseNotFound:
   3474     return ESR;
   3475   }
   3476   llvm_unreachable("Invalid EvalStmtResult!");
   3477 }
   3478 
   3479 /// Evaluate a switch statement.
   3480 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
   3481                                      const SwitchStmt *SS) {
   3482   BlockScopeRAII Scope(Info);
   3483 
   3484   // Evaluate the switch condition.
   3485   APSInt Value;
   3486   {
   3487     FullExpressionRAII Scope(Info);
   3488     if (const Stmt *Init = SS->getInit()) {
   3489       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
   3490       if (ESR != ESR_Succeeded)
   3491         return ESR;
   3492     }
   3493     if (SS->getConditionVariable() &&
   3494         !EvaluateDecl(Info, SS->getConditionVariable()))
   3495       return ESR_Failed;
   3496     if (!EvaluateInteger(SS->getCond(), Value, Info))
   3497       return ESR_Failed;
   3498   }
   3499 
   3500   // Find the switch case corresponding to the value of the condition.
   3501   // FIXME: Cache this lookup.
   3502   const SwitchCase *Found = nullptr;
   3503   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
   3504        SC = SC->getNextSwitchCase()) {
   3505     if (isa<DefaultStmt>(SC)) {
   3506       Found = SC;
   3507       continue;
   3508     }
   3509 
   3510     const CaseStmt *CS = cast<CaseStmt>(SC);
   3511     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
   3512     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
   3513                               : LHS;
   3514     if (LHS <= Value && Value <= RHS) {
   3515       Found = SC;
   3516       break;
   3517     }
   3518   }
   3519 
   3520   if (!Found)
   3521     return ESR_Succeeded;
   3522 
   3523   // Search the switch body for the switch case and evaluate it from there.
   3524   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
   3525   case ESR_Break:
   3526     return ESR_Succeeded;
   3527   case ESR_Succeeded:
   3528   case ESR_Continue:
   3529   case ESR_Failed:
   3530   case ESR_Returned:
   3531     return ESR;
   3532   case ESR_CaseNotFound:
   3533     // This can only happen if the switch case is nested within a statement
   3534     // expression. We have no intention of supporting that.
   3535     Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
   3536     return ESR_Failed;
   3537   }
   3538   llvm_unreachable("Invalid EvalStmtResult!");
   3539 }
   3540 
   3541 // Evaluate a statement.
   3542 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
   3543                                    const Stmt *S, const SwitchCase *Case) {
   3544   if (!Info.nextStep(S))
   3545     return ESR_Failed;
   3546 
   3547   // If we're hunting down a 'case' or 'default' label, recurse through
   3548   // substatements until we hit the label.
   3549   if (Case) {
   3550     // FIXME: We don't start the lifetime of objects whose initialization we
   3551     // jump over. However, such objects must be of class type with a trivial
   3552     // default constructor that initialize all subobjects, so must be empty,
   3553     // so this almost never matters.
   3554     switch (S->getStmtClass()) {
   3555     case Stmt::CompoundStmtClass:
   3556       // FIXME: Precompute which substatement of a compound statement we
   3557       // would jump to, and go straight there rather than performing a
   3558       // linear scan each time.
   3559     case Stmt::LabelStmtClass:
   3560     case Stmt::AttributedStmtClass:
   3561     case Stmt::DoStmtClass:
   3562       break;
   3563 
   3564     case Stmt::CaseStmtClass:
   3565     case Stmt::DefaultStmtClass:
   3566       if (Case == S)
   3567         Case = nullptr;
   3568       break;
   3569 
   3570     case Stmt::IfStmtClass: {
   3571       // FIXME: Precompute which side of an 'if' we would jump to, and go
   3572       // straight there rather than scanning both sides.
   3573       const IfStmt *IS = cast<IfStmt>(S);
   3574 
   3575       // Wrap the evaluation in a block scope, in case it's a DeclStmt
   3576       // preceded by our switch label.
   3577       BlockScopeRAII Scope(Info);
   3578 
   3579       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
   3580       if (ESR != ESR_CaseNotFound || !IS->getElse())
   3581         return ESR;
   3582       return EvaluateStmt(Result, Info, IS->getElse(), Case);
   3583     }
   3584 
   3585     case Stmt::WhileStmtClass: {
   3586       EvalStmtResult ESR =
   3587           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
   3588       if (ESR != ESR_Continue)
   3589         return ESR;
   3590       break;
   3591     }
   3592 
   3593     case Stmt::ForStmtClass: {
   3594       const ForStmt *FS = cast<ForStmt>(S);
   3595       EvalStmtResult ESR =
   3596           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
   3597       if (ESR != ESR_Continue)
   3598         return ESR;
   3599       if (FS->getInc()) {
   3600         FullExpressionRAII IncScope(Info);
   3601         if (!EvaluateIgnoredValue(Info, FS->getInc()))
   3602           return ESR_Failed;
   3603       }
   3604       break;
   3605     }
   3606 
   3607     case Stmt::DeclStmtClass:
   3608       // FIXME: If the variable has initialization that can't be jumped over,
   3609       // bail out of any immediately-surrounding compound-statement too.
   3610     default:
   3611       return ESR_CaseNotFound;
   3612     }
   3613   }
   3614 
   3615   switch (S->getStmtClass()) {
   3616   default:
   3617     if (const Expr *E = dyn_cast<Expr>(S)) {
   3618       // Don't bother evaluating beyond an expression-statement which couldn't
   3619       // be evaluated.
   3620       FullExpressionRAII Scope(Info);
   3621       if (!EvaluateIgnoredValue(Info, E))
   3622         return ESR_Failed;
   3623       return ESR_Succeeded;
   3624     }
   3625 
   3626     Info.FFDiag(S->getLocStart());
   3627     return ESR_Failed;
   3628 
   3629   case Stmt::NullStmtClass:
   3630     return ESR_Succeeded;
   3631 
   3632   case Stmt::DeclStmtClass: {
   3633     const DeclStmt *DS = cast<DeclStmt>(S);
   3634     for (const auto *DclIt : DS->decls()) {
   3635       // Each declaration initialization is its own full-expression.
   3636       // FIXME: This isn't quite right; if we're performing aggregate
   3637       // initialization, each braced subexpression is its own full-expression.
   3638       FullExpressionRAII Scope(Info);
   3639       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
   3640         return ESR_Failed;
   3641     }
   3642     return ESR_Succeeded;
   3643   }
   3644 
   3645   case Stmt::ReturnStmtClass: {
   3646     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
   3647     FullExpressionRAII Scope(Info);
   3648     if (RetExpr &&
   3649         !(Result.Slot
   3650               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
   3651               : Evaluate(Result.Value, Info, RetExpr)))
   3652       return ESR_Failed;
   3653     return ESR_Returned;
   3654   }
   3655 
   3656   case Stmt::CompoundStmtClass: {
   3657     BlockScopeRAII Scope(Info);
   3658 
   3659     const CompoundStmt *CS = cast<CompoundStmt>(S);
   3660     for (const auto *BI : CS->body()) {
   3661       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
   3662       if (ESR == ESR_Succeeded)
   3663         Case = nullptr;
   3664       else if (ESR != ESR_CaseNotFound)
   3665         return ESR;
   3666     }
   3667     return Case ? ESR_CaseNotFound : ESR_Succeeded;
   3668   }
   3669 
   3670   case Stmt::IfStmtClass: {
   3671     const IfStmt *IS = cast<IfStmt>(S);
   3672 
   3673     // Evaluate the condition, as either a var decl or as an expression.
   3674     BlockScopeRAII Scope(Info);
   3675     if (const Stmt *Init = IS->getInit()) {
   3676       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
   3677       if (ESR != ESR_Succeeded)
   3678         return ESR;
   3679     }
   3680     bool Cond;
   3681     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
   3682       return ESR_Failed;
   3683 
   3684     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
   3685       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
   3686       if (ESR != ESR_Succeeded)
   3687         return ESR;
   3688     }
   3689     return ESR_Succeeded;
   3690   }
   3691 
   3692   case Stmt::WhileStmtClass: {
   3693     const WhileStmt *WS = cast<WhileStmt>(S);
   3694     while (true) {
   3695       BlockScopeRAII Scope(Info);
   3696       bool Continue;
   3697       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
   3698                         Continue))
   3699         return ESR_Failed;
   3700       if (!Continue)
   3701         break;
   3702 
   3703       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
   3704       if (ESR != ESR_Continue)
   3705         return ESR;
   3706     }
   3707     return ESR_Succeeded;
   3708   }
   3709 
   3710   case Stmt::DoStmtClass: {
   3711     const DoStmt *DS = cast<DoStmt>(S);
   3712     bool Continue;
   3713     do {
   3714       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
   3715       if (ESR != ESR_Continue)
   3716         return ESR;
   3717       Case = nullptr;
   3718 
   3719       FullExpressionRAII CondScope(Info);
   3720       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
   3721         return ESR_Failed;
   3722     } while (Continue);
   3723     return ESR_Succeeded;
   3724   }
   3725 
   3726   case Stmt::ForStmtClass: {
   3727     const ForStmt *FS = cast<ForStmt>(S);
   3728     BlockScopeRAII Scope(Info);
   3729     if (FS->getInit()) {
   3730       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
   3731       if (ESR != ESR_Succeeded)
   3732         return ESR;
   3733     }
   3734     while (true) {
   3735       BlockScopeRAII Scope(Info);
   3736       bool Continue = true;
   3737       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
   3738                                          FS->getCond(), Continue))
   3739         return ESR_Failed;
   3740       if (!Continue)
   3741         break;
   3742 
   3743       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
   3744       if (ESR != ESR_Continue)
   3745         return ESR;
   3746 
   3747       if (FS->getInc()) {
   3748         FullExpressionRAII IncScope(Info);
   3749         if (!EvaluateIgnoredValue(Info, FS->getInc()))
   3750           return ESR_Failed;
   3751       }
   3752     }
   3753     return ESR_Succeeded;
   3754   }
   3755 
   3756   case Stmt::CXXForRangeStmtClass: {
   3757     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
   3758     BlockScopeRAII Scope(Info);
   3759 
   3760     // Initialize the __range variable.
   3761     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
   3762     if (ESR != ESR_Succeeded)
   3763       return ESR;
   3764 
   3765     // Create the __begin and __end iterators.
   3766     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
   3767     if (ESR != ESR_Succeeded)
   3768       return ESR;
   3769     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
   3770     if (ESR != ESR_Succeeded)
   3771       return ESR;
   3772 
   3773     while (true) {
   3774       // Condition: __begin != __end.
   3775       {
   3776         bool Continue = true;
   3777         FullExpressionRAII CondExpr(Info);
   3778         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
   3779           return ESR_Failed;
   3780         if (!Continue)
   3781           break;
   3782       }
   3783 
   3784       // User's variable declaration, initialized by *__begin.
   3785       BlockScopeRAII InnerScope(Info);
   3786       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
   3787       if (ESR != ESR_Succeeded)
   3788         return ESR;
   3789 
   3790       // Loop body.
   3791       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
   3792       if (ESR != ESR_Continue)
   3793         return ESR;
   3794 
   3795       // Increment: ++__begin
   3796       if (!EvaluateIgnoredValue(Info, FS->getInc()))
   3797         return ESR_Failed;
   3798     }
   3799 
   3800     return ESR_Succeeded;
   3801   }
   3802 
   3803   case Stmt::SwitchStmtClass:
   3804     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
   3805 
   3806   case Stmt::ContinueStmtClass:
   3807     return ESR_Continue;
   3808 
   3809   case Stmt::BreakStmtClass:
   3810     return ESR_Break;
   3811 
   3812   case Stmt::LabelStmtClass:
   3813     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
   3814 
   3815   case Stmt::AttributedStmtClass:
   3816     // As a general principle, C++11 attributes can be ignored without
   3817     // any semantic impact.
   3818     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
   3819                         Case);
   3820 
   3821   case Stmt::CaseStmtClass:
   3822   case Stmt::DefaultStmtClass:
   3823     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
   3824   }
   3825 }
   3826 
   3827 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
   3828 /// default constructor. If so, we'll fold it whether or not it's marked as
   3829 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
   3830 /// so we need special handling.
   3831 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
   3832                                            const CXXConstructorDecl *CD,
   3833                                            bool IsValueInitialization) {
   3834   if (!CD->isTrivial() || !CD->isDefaultConstructor())
   3835     return false;
   3836 
   3837   // Value-initialization does not call a trivial default constructor, so such a
   3838   // call is a core constant expression whether or not the constructor is
   3839   // constexpr.
   3840   if (!CD->isConstexpr() && !IsValueInitialization) {
   3841     if (Info.getLangOpts().CPlusPlus11) {
   3842       // FIXME: If DiagDecl is an implicitly-declared special member function,
   3843       // we should be much more explicit about why it's not constexpr.
   3844       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
   3845         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
   3846       Info.Note(CD->getLocation(), diag::note_declared_at);
   3847     } else {
   3848       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
   3849     }
   3850   }
   3851   return true;
   3852 }
   3853 
   3854 /// CheckConstexprFunction - Check that a function can be called in a constant
   3855 /// expression.
   3856 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
   3857                                    const FunctionDecl *Declaration,
   3858                                    const FunctionDecl *Definition,
   3859                                    const Stmt *Body) {
   3860   // Potential constant expressions can contain calls to declared, but not yet
   3861   // defined, constexpr functions.
   3862   if (Info.checkingPotentialConstantExpression() && !Definition &&
   3863       Declaration->isConstexpr())
   3864     return false;
   3865 
   3866   // Bail out with no diagnostic if the function declaration itself is invalid.
   3867   // We will have produced a relevant diagnostic while parsing it.
   3868   if (Declaration->isInvalidDecl())
   3869     return false;
   3870 
   3871   // Can we evaluate this function call?
   3872   if (Definition && Definition->isConstexpr() &&
   3873       !Definition->isInvalidDecl() && Body)
   3874     return true;
   3875 
   3876   if (Info.getLangOpts().CPlusPlus11) {
   3877     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
   3878 
   3879     // If this function is not constexpr because it is an inherited
   3880     // non-constexpr constructor, diagnose that directly.
   3881     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
   3882     if (CD && CD->isInheritingConstructor()) {
   3883       auto *Inherited = CD->getInheritedConstructor().getConstructor();
   3884       if (!Inherited->isConstexpr())
   3885         DiagDecl = CD = Inherited;
   3886     }
   3887 
   3888     // FIXME: If DiagDecl is an implicitly-declared special member function
   3889     // or an inheriting constructor, we should be much more explicit about why
   3890     // it's not constexpr.
   3891     if (CD && CD->isInheritingConstructor())
   3892       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
   3893         << CD->getInheritedConstructor().getConstructor()->getParent();
   3894     else
   3895       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
   3896         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
   3897     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
   3898   } else {
   3899     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
   3900   }
   3901   return false;
   3902 }
   3903 
   3904 /// Determine if a class has any fields that might need to be copied by a
   3905 /// trivial copy or move operation.
   3906 static bool hasFields(const CXXRecordDecl *RD) {
   3907   if (!RD || RD->isEmpty())
   3908     return false;
   3909   for (auto *FD : RD->fields()) {
   3910     if (FD->isUnnamedBitfield())
   3911       continue;
   3912     return true;
   3913   }
   3914   for (auto &Base : RD->bases())
   3915     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
   3916       return true;
   3917   return false;
   3918 }
   3919 
   3920 namespace {
   3921 typedef SmallVector<APValue, 8> ArgVector;
   3922 }
   3923 
   3924 /// EvaluateArgs - Evaluate the arguments to a function call.
   3925 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
   3926                          EvalInfo &Info) {
   3927   bool Success = true;
   3928   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
   3929        I != E; ++I) {
   3930     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
   3931       // If we're checking for a potential constant expression, evaluate all
   3932       // initializers even if some of them fail.
   3933       if (!Info.noteFailure())
   3934         return false;
   3935       Success = false;
   3936     }
   3937   }
   3938   return Success;
   3939 }
   3940 
   3941 /// Evaluate a function call.
   3942 static bool HandleFunctionCall(SourceLocation CallLoc,
   3943                                const FunctionDecl *Callee, const LValue *This,
   3944                                ArrayRef<const Expr*> Args, const Stmt *Body,
   3945                                EvalInfo &Info, APValue &Result,
   3946                                const LValue *ResultSlot) {
   3947   ArgVector ArgValues(Args.size());
   3948   if (!EvaluateArgs(Args, ArgValues, Info))
   3949     return false;
   3950 
   3951   if (!Info.CheckCallLimit(CallLoc))
   3952     return false;
   3953 
   3954   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
   3955 
   3956   // For a trivial copy or move assignment, perform an APValue copy. This is
   3957   // essential for unions, where the operations performed by the assignment
   3958   // operator cannot be represented as statements.
   3959   //
   3960   // Skip this for non-union classes with no fields; in that case, the defaulted
   3961   // copy/move does not actually read the object.
   3962   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
   3963   if (MD && MD->isDefaulted() &&
   3964       (MD->getParent()->isUnion() ||
   3965        (MD->isTrivial() && hasFields(MD->getParent())))) {
   3966     assert(This &&
   3967            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
   3968     LValue RHS;
   3969     RHS.setFrom(Info.Ctx, ArgValues[0]);
   3970     APValue RHSValue;
   3971     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
   3972                                         RHS, RHSValue))
   3973       return false;
   3974     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
   3975                           RHSValue))
   3976       return false;
   3977     This->moveInto(Result);
   3978     return true;
   3979   }
   3980 
   3981   StmtResult Ret = {Result, ResultSlot};
   3982   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
   3983   if (ESR == ESR_Succeeded) {
   3984     if (Callee->getReturnType()->isVoidType())
   3985       return true;
   3986     Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
   3987   }
   3988   return ESR == ESR_Returned;
   3989 }
   3990 
   3991 /// Evaluate a constructor call.
   3992 static bool HandleConstructorCall(const Expr *E, const LValue &This,
   3993                                   APValue *ArgValues,
   3994                                   const CXXConstructorDecl *Definition,
   3995                                   EvalInfo &Info, APValue &Result) {
   3996   SourceLocation CallLoc = E->getExprLoc();
   3997   if (!Info.CheckCallLimit(CallLoc))
   3998     return false;
   3999 
   4000   const CXXRecordDecl *RD = Definition->getParent();
   4001   if (RD->getNumVBases()) {
   4002     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
   4003     return false;
   4004   }
   4005 
   4006   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
   4007 
   4008   // FIXME: Creating an APValue just to hold a nonexistent return value is
   4009   // wasteful.
   4010   APValue RetVal;
   4011   StmtResult Ret = {RetVal, nullptr};
   4012 
   4013   // If it's a delegating constructor, delegate.
   4014   if (Definition->isDelegatingConstructor()) {
   4015     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
   4016     {
   4017       FullExpressionRAII InitScope(Info);
   4018       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
   4019         return false;
   4020     }
   4021     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
   4022   }
   4023 
   4024   // For a trivial copy or move constructor, perform an APValue copy. This is
   4025   // essential for unions (or classes with anonymous union members), where the
   4026   // operations performed by the constructor cannot be represented by
   4027   // ctor-initializers.
   4028   //
   4029   // Skip this for empty non-union classes; we should not perform an
   4030   // lvalue-to-rvalue conversion on them because their copy constructor does not
   4031   // actually read them.
   4032   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
   4033       (Definition->getParent()->isUnion() ||
   4034        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
   4035     LValue RHS;
   4036     RHS.setFrom(Info.Ctx, ArgValues[0]);
   4037     return handleLValueToRValueConversion(
   4038         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
   4039         RHS, Result);
   4040   }
   4041 
   4042   // Reserve space for the struct members.
   4043   if (!RD->isUnion() && Result.isUninit())
   4044     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
   4045                      std::distance(RD->field_begin(), RD->field_end()));
   4046 
   4047   if (RD->isInvalidDecl()) return false;
   4048   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
   4049 
   4050   // A scope for temporaries lifetime-extended by reference members.
   4051   BlockScopeRAII LifetimeExtendedScope(Info);
   4052 
   4053   bool Success = true;
   4054   unsigned BasesSeen = 0;
   4055 #ifndef NDEBUG
   4056   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
   4057 #endif
   4058   for (const auto *I : Definition->inits()) {
   4059     LValue Subobject = This;
   4060     APValue *Value = &Result;
   4061 
   4062     // Determine the subobject to initialize.
   4063     FieldDecl *FD = nullptr;
   4064     if (I->isBaseInitializer()) {
   4065       QualType BaseType(I->getBaseClass(), 0);
   4066 #ifndef NDEBUG
   4067       // Non-virtual base classes are initialized in the order in the class
   4068       // definition. We have already checked for virtual base classes.
   4069       assert(!BaseIt->isVirtual() && "virtual base for literal type");
   4070       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
   4071              "base class initializers not in expected order");
   4072       ++BaseIt;
   4073 #endif
   4074       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
   4075                                   BaseType->getAsCXXRecordDecl(), &Layout))
   4076         return false;
   4077       Value = &Result.getStructBase(BasesSeen++);
   4078     } else if ((FD = I->getMember())) {
   4079       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
   4080         return false;
   4081       if (RD->isUnion()) {
   4082         Result = APValue(FD);
   4083         Value = &Result.getUnionValue();
   4084       } else {
   4085         Value = &Result.getStructField(FD->getFieldIndex());
   4086       }
   4087     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
   4088       // Walk the indirect field decl's chain to find the object to initialize,
   4089       // and make sure we've initialized every step along it.
   4090       for (auto *C : IFD->chain()) {
   4091         FD = cast<FieldDecl>(C);
   4092         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
   4093         // Switch the union field if it differs. This happens if we had
   4094         // preceding zero-initialization, and we're now initializing a union
   4095         // subobject other than the first.
   4096         // FIXME: In this case, the values of the other subobjects are
   4097         // specified, since zero-initialization sets all padding bits to zero.
   4098         if (Value->isUninit() ||
   4099             (Value->isUnion() && Value->getUnionField() != FD)) {
   4100           if (CD->isUnion())
   4101             *Value = APValue(FD);
   4102           else
   4103             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
   4104                              std::distance(CD->field_begin(), CD->field_end()));
   4105         }
   4106         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
   4107           return false;
   4108         if (CD->isUnion())
   4109           Value = &Value->getUnionValue();
   4110         else
   4111           Value = &Value->getStructField(FD->getFieldIndex());
   4112       }
   4113     } else {
   4114       llvm_unreachable("unknown base initializer kind");
   4115     }
   4116 
   4117     FullExpressionRAII InitScope(Info);
   4118     if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
   4119         (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
   4120                                                           *Value, FD))) {
   4121       // If we're checking for a potential constant expression, evaluate all
   4122       // initializers even if some of them fail.
   4123       if (!Info.noteFailure())
   4124         return false;
   4125       Success = false;
   4126     }
   4127   }
   4128 
   4129   return Success &&
   4130          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
   4131 }
   4132 
   4133 static bool HandleConstructorCall(const Expr *E, const LValue &This,
   4134                                   ArrayRef<const Expr*> Args,
   4135                                   const CXXConstructorDecl *Definition,
   4136                                   EvalInfo &Info, APValue &Result) {
   4137   ArgVector ArgValues(Args.size());
   4138   if (!EvaluateArgs(Args, ArgValues, Info))
   4139     return false;
   4140 
   4141   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
   4142                                Info, Result);
   4143 }
   4144 
   4145 //===----------------------------------------------------------------------===//
   4146 // Generic Evaluation
   4147 //===----------------------------------------------------------------------===//
   4148 namespace {
   4149 
   4150 template <class Derived>
   4151 class ExprEvaluatorBase
   4152   : public ConstStmtVisitor<Derived, bool> {
   4153 private:
   4154   Derived &getDerived() { return static_cast<Derived&>(*this); }
   4155   bool DerivedSuccess(const APValue &V, const Expr *E) {
   4156     return getDerived().Success(V, E);
   4157   }
   4158   bool DerivedZeroInitialization(const Expr *E) {
   4159     return getDerived().ZeroInitialization(E);
   4160   }
   4161 
   4162   // Check whether a conditional operator with a non-constant condition is a
   4163   // potential constant expression. If neither arm is a potential constant
   4164   // expression, then the conditional operator is not either.
   4165   template<typename ConditionalOperator>
   4166   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
   4167     assert(Info.checkingPotentialConstantExpression());
   4168 
   4169     // Speculatively evaluate both arms.
   4170     SmallVector<PartialDiagnosticAt, 8> Diag;
   4171     {
   4172       SpeculativeEvaluationRAII Speculate(Info, &Diag);
   4173       StmtVisitorTy::Visit(E->getFalseExpr());
   4174       if (Diag.empty())
   4175         return;
   4176     }
   4177 
   4178     {
   4179       SpeculativeEvaluationRAII Speculate(Info, &Diag);
   4180       Diag.clear();
   4181       StmtVisitorTy::Visit(E->getTrueExpr());
   4182       if (Diag.empty())
   4183         return;
   4184     }
   4185 
   4186     Error(E, diag::note_constexpr_conditional_never_const);
   4187   }
   4188 
   4189 
   4190   template<typename ConditionalOperator>
   4191   bool HandleConditionalOperator(const ConditionalOperator *E) {
   4192     bool BoolResult;
   4193     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
   4194       if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
   4195         CheckPotentialConstantConditional(E);
   4196       return false;
   4197     }
   4198 
   4199     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
   4200     return StmtVisitorTy::Visit(EvalExpr);
   4201   }
   4202 
   4203 protected:
   4204   EvalInfo &Info;
   4205   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
   4206   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
   4207 
   4208   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
   4209     return Info.CCEDiag(E, D);
   4210   }
   4211 
   4212   bool ZeroInitialization(const Expr *E) { return Error(E); }
   4213 
   4214 public:
   4215   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
   4216 
   4217   EvalInfo &getEvalInfo() { return Info; }
   4218 
   4219   /// Report an evaluation error. This should only be called when an error is
   4220   /// first discovered. When propagating an error, just return false.
   4221   bool Error(const Expr *E, diag::kind D) {
   4222     Info.FFDiag(E, D);
   4223     return false;
   4224   }
   4225   bool Error(const Expr *E) {
   4226     return Error(E, diag::note_invalid_subexpr_in_const_expr);
   4227   }
   4228 
   4229   bool VisitStmt(const Stmt *) {
   4230     llvm_unreachable("Expression evaluator should not be called on stmts");
   4231   }
   4232   bool VisitExpr(const Expr *E) {
   4233     return Error(E);
   4234   }
   4235 
   4236   bool VisitParenExpr(const ParenExpr *E)
   4237     { return StmtVisitorTy::Visit(E->getSubExpr()); }
   4238   bool VisitUnaryExtension(const UnaryOperator *E)
   4239     { return StmtVisitorTy::Visit(E->getSubExpr()); }
   4240   bool VisitUnaryPlus(const UnaryOperator *E)
   4241     { return StmtVisitorTy::Visit(E->getSubExpr()); }
   4242   bool VisitChooseExpr(const ChooseExpr *E)
   4243     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
   4244   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
   4245     { return StmtVisitorTy::Visit(E->getResultExpr()); }
   4246   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
   4247     { return StmtVisitorTy::Visit(E->getReplacement()); }
   4248   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
   4249     { return StmtVisitorTy::Visit(E->getExpr()); }
   4250   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
   4251     // The initializer may not have been parsed yet, or might be erroneous.
   4252     if (!E->getExpr())
   4253       return Error(E);
   4254     return StmtVisitorTy::Visit(E->getExpr());
   4255   }
   4256   // We cannot create any objects for which cleanups are required, so there is
   4257   // nothing to do here; all cleanups must come from unevaluated subexpressions.
   4258   bool VisitExprWithCleanups(const ExprWithCleanups *E)
   4259     { return StmtVisitorTy::Visit(E->getSubExpr()); }
   4260 
   4261   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
   4262     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
   4263     return static_cast<Derived*>(this)->VisitCastExpr(E);
   4264   }
   4265   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
   4266     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
   4267     return static_cast<Derived*>(this)->VisitCastExpr(E);
   4268   }
   4269 
   4270   bool VisitBinaryOperator(const BinaryOperator *E) {
   4271     switch (E->getOpcode()) {
   4272     default:
   4273       return Error(E);
   4274 
   4275     case BO_Comma:
   4276       VisitIgnoredValue(E->getLHS());
   4277       return StmtVisitorTy::Visit(E->getRHS());
   4278 
   4279     case BO_PtrMemD:
   4280     case BO_PtrMemI: {
   4281       LValue Obj;
   4282       if (!HandleMemberPointerAccess(Info, E, Obj))
   4283         return false;
   4284       APValue Result;
   4285       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
   4286         return false;
   4287       return DerivedSuccess(Result, E);
   4288     }
   4289     }
   4290   }
   4291 
   4292   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
   4293     // Evaluate and cache the common expression. We treat it as a temporary,
   4294     // even though it's not quite the same thing.
   4295     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
   4296                   Info, E->getCommon()))
   4297       return false;
   4298 
   4299     return HandleConditionalOperator(E);
   4300   }
   4301 
   4302   bool VisitConditionalOperator(const ConditionalOperator *E) {
   4303     bool IsBcpCall = false;
   4304     // If the condition (ignoring parens) is a __builtin_constant_p call,
   4305     // the result is a constant expression if it can be folded without
   4306     // side-effects. This is an important GNU extension. See GCC PR38377
   4307     // for discussion.
   4308     if (const CallExpr *CallCE =
   4309           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
   4310       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
   4311         IsBcpCall = true;
   4312 
   4313     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
   4314     // constant expression; we can't check whether it's potentially foldable.
   4315     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
   4316       return false;
   4317 
   4318     FoldConstant Fold(Info, IsBcpCall);
   4319     if (!HandleConditionalOperator(E)) {
   4320       Fold.keepDiagnostics();
   4321       return false;
   4322     }
   4323 
   4324     return true;
   4325   }
   4326 
   4327   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
   4328     if (APValue *Value = Info.CurrentCall->getTemporary(E))
   4329       return DerivedSuccess(*Value, E);
   4330 
   4331     const Expr *Source = E->getSourceExpr();
   4332     if (!Source)
   4333       return Error(E);
   4334     if (Source == E) { // sanity checking.
   4335       assert(0 && "OpaqueValueExpr recursively refers to itself");
   4336       return Error(E);
   4337     }
   4338     return StmtVisitorTy::Visit(Source);
   4339   }
   4340 
   4341   bool VisitCallExpr(const CallExpr *E) {
   4342     APValue Result;
   4343     if (!handleCallExpr(E, Result, nullptr))
   4344       return false;
   4345     return DerivedSuccess(Result, E);
   4346   }
   4347 
   4348   bool handleCallExpr(const CallExpr *E, APValue &Result,
   4349                      const LValue *ResultSlot) {
   4350     const Expr *Callee = E->getCallee()->IgnoreParens();
   4351     QualType CalleeType = Callee->getType();
   4352 
   4353     const FunctionDecl *FD = nullptr;
   4354     LValue *This = nullptr, ThisVal;
   4355     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
   4356     bool HasQualifier = false;
   4357 
   4358     // Extract function decl and 'this' pointer from the callee.
   4359     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
   4360       const ValueDecl *Member = nullptr;
   4361       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
   4362         // Explicit bound member calls, such as x.f() or p->g();
   4363         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
   4364           return false;
   4365         Member = ME->getMemberDecl();
   4366         This = &ThisVal;
   4367         HasQualifier = ME->hasQualifier();
   4368       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
   4369         // Indirect bound member calls ('.*' or '->*').
   4370         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
   4371         if (!Member) return false;
   4372         This = &ThisVal;
   4373       } else
   4374         return Error(Callee);
   4375 
   4376       FD = dyn_cast<FunctionDecl>(Member);
   4377       if (!FD)
   4378         return Error(Callee);
   4379     } else if (CalleeType->isFunctionPointerType()) {
   4380       LValue Call;
   4381       if (!EvaluatePointer(Callee, Call, Info))
   4382         return false;
   4383 
   4384       if (!Call.getLValueOffset().isZero())
   4385         return Error(Callee);
   4386       FD = dyn_cast_or_null<FunctionDecl>(
   4387                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
   4388       if (!FD)
   4389         return Error(Callee);
   4390 
   4391       // Overloaded operator calls to member functions are represented as normal
   4392       // calls with '*this' as the first argument.
   4393       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
   4394       if (MD && !MD->isStatic()) {
   4395         // FIXME: When selecting an implicit conversion for an overloaded
   4396         // operator delete, we sometimes try to evaluate calls to conversion
   4397         // operators without a 'this' parameter!
   4398         if (Args.empty())
   4399           return Error(E);
   4400 
   4401         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
   4402           return false;
   4403         This = &ThisVal;
   4404         Args = Args.slice(1);
   4405       }
   4406 
   4407       // Don't call function pointers which have been cast to some other type.
   4408       if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
   4409         return Error(E);
   4410     } else
   4411       return Error(E);
   4412 
   4413     if (This && !This->checkSubobject(Info, E, CSK_This))
   4414       return false;
   4415 
   4416     // DR1358 allows virtual constexpr functions in some cases. Don't allow
   4417     // calls to such functions in constant expressions.
   4418     if (This && !HasQualifier &&
   4419         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
   4420       return Error(E, diag::note_constexpr_virtual_call);
   4421 
   4422     const FunctionDecl *Definition = nullptr;
   4423     Stmt *Body = FD->getBody(Definition);
   4424 
   4425     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
   4426         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
   4427                             Result, ResultSlot))
   4428       return false;
   4429 
   4430     return true;
   4431   }
   4432 
   4433   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   4434     return StmtVisitorTy::Visit(E->getInitializer());
   4435   }
   4436   bool VisitInitListExpr(const InitListExpr *E) {
   4437     if (E->getNumInits() == 0)
   4438       return DerivedZeroInitialization(E);
   4439     if (E->getNumInits() == 1)
   4440       return StmtVisitorTy::Visit(E->getInit(0));
   4441     return Error(E);
   4442   }
   4443   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
   4444     return DerivedZeroInitialization(E);
   4445   }
   4446   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
   4447     return DerivedZeroInitialization(E);
   4448   }
   4449   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
   4450     return DerivedZeroInitialization(E);
   4451   }
   4452 
   4453   /// A member expression where the object is a prvalue is itself a prvalue.
   4454   bool VisitMemberExpr(const MemberExpr *E) {
   4455     assert(!E->isArrow() && "missing call to bound member function?");
   4456 
   4457     APValue Val;
   4458     if (!Evaluate(Val, Info, E->getBase()))
   4459       return false;
   4460 
   4461     QualType BaseTy = E->getBase()->getType();
   4462 
   4463     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
   4464     if (!FD) return Error(E);
   4465     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
   4466     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
   4467            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
   4468 
   4469     CompleteObject Obj(&Val, BaseTy);
   4470     SubobjectDesignator Designator(BaseTy);
   4471     Designator.addDeclUnchecked(FD);
   4472 
   4473     APValue Result;
   4474     return extractSubobject(Info, E, Obj, Designator, Result) &&
   4475            DerivedSuccess(Result, E);
   4476   }
   4477 
   4478   bool VisitCastExpr(const CastExpr *E) {
   4479     switch (E->getCastKind()) {
   4480     default:
   4481       break;
   4482 
   4483     case CK_AtomicToNonAtomic: {
   4484       APValue AtomicVal;
   4485       if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
   4486         return false;
   4487       return DerivedSuccess(AtomicVal, E);
   4488     }
   4489 
   4490     case CK_NoOp:
   4491     case CK_UserDefinedConversion:
   4492       return StmtVisitorTy::Visit(E->getSubExpr());
   4493 
   4494     case CK_LValueToRValue: {
   4495       LValue LVal;
   4496       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
   4497         return false;
   4498       APValue RVal;
   4499       // Note, we use the subexpression's type in order to retain cv-qualifiers.
   4500       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
   4501                                           LVal, RVal))
   4502         return false;
   4503       return DerivedSuccess(RVal, E);
   4504     }
   4505     }
   4506 
   4507     return Error(E);
   4508   }
   4509 
   4510   bool VisitUnaryPostInc(const UnaryOperator *UO) {
   4511     return VisitUnaryPostIncDec(UO);
   4512   }
   4513   bool VisitUnaryPostDec(const UnaryOperator *UO) {
   4514     return VisitUnaryPostIncDec(UO);
   4515   }
   4516   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
   4517     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
   4518       return Error(UO);
   4519 
   4520     LValue LVal;
   4521     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
   4522       return false;
   4523     APValue RVal;
   4524     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
   4525                       UO->isIncrementOp(), &RVal))
   4526       return false;
   4527     return DerivedSuccess(RVal, UO);
   4528   }
   4529 
   4530   bool VisitStmtExpr(const StmtExpr *E) {
   4531     // We will have checked the full-expressions inside the statement expression
   4532     // when they were completed, and don't need to check them again now.
   4533     if (Info.checkingForOverflow())
   4534       return Error(E);
   4535 
   4536     BlockScopeRAII Scope(Info);
   4537     const CompoundStmt *CS = E->getSubStmt();
   4538     if (CS->body_empty())
   4539       return true;
   4540 
   4541     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
   4542                                            BE = CS->body_end();
   4543          /**/; ++BI) {
   4544       if (BI + 1 == BE) {
   4545         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
   4546         if (!FinalExpr) {
   4547           Info.FFDiag((*BI)->getLocStart(),
   4548                     diag::note_constexpr_stmt_expr_unsupported);
   4549           return false;
   4550         }
   4551         return this->Visit(FinalExpr);
   4552       }
   4553 
   4554       APValue ReturnValue;
   4555       StmtResult Result = { ReturnValue, nullptr };
   4556       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
   4557       if (ESR != ESR_Succeeded) {
   4558         // FIXME: If the statement-expression terminated due to 'return',
   4559         // 'break', or 'continue', it would be nice to propagate that to
   4560         // the outer statement evaluation rather than bailing out.
   4561         if (ESR != ESR_Failed)
   4562           Info.FFDiag((*BI)->getLocStart(),
   4563                     diag::note_constexpr_stmt_expr_unsupported);
   4564         return false;
   4565       }
   4566     }
   4567 
   4568     llvm_unreachable("Return from function from the loop above.");
   4569   }
   4570 
   4571   /// Visit a value which is evaluated, but whose value is ignored.
   4572   void VisitIgnoredValue(const Expr *E) {
   4573     EvaluateIgnoredValue(Info, E);
   4574   }
   4575 
   4576   /// Potentially visit a MemberExpr's base expression.
   4577   void VisitIgnoredBaseExpression(const Expr *E) {
   4578     // While MSVC doesn't evaluate the base expression, it does diagnose the
   4579     // presence of side-effecting behavior.
   4580     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
   4581       return;
   4582     VisitIgnoredValue(E);
   4583   }
   4584 };
   4585 
   4586 }
   4587 
   4588 //===----------------------------------------------------------------------===//
   4589 // Common base class for lvalue and temporary evaluation.
   4590 //===----------------------------------------------------------------------===//
   4591 namespace {
   4592 template<class Derived>
   4593 class LValueExprEvaluatorBase
   4594   : public ExprEvaluatorBase<Derived> {
   4595 protected:
   4596   LValue &Result;
   4597   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
   4598   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
   4599 
   4600   bool Success(APValue::LValueBase B) {
   4601     Result.set(B);
   4602     return true;
   4603   }
   4604 
   4605 public:
   4606   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
   4607     ExprEvaluatorBaseTy(Info), Result(Result) {}
   4608 
   4609   bool Success(const APValue &V, const Expr *E) {
   4610     Result.setFrom(this->Info.Ctx, V);
   4611     return true;
   4612   }
   4613 
   4614   bool VisitMemberExpr(const MemberExpr *E) {
   4615     // Handle non-static data members.
   4616     QualType BaseTy;
   4617     bool EvalOK;
   4618     if (E->isArrow()) {
   4619       EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
   4620       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
   4621     } else if (E->getBase()->isRValue()) {
   4622       assert(E->getBase()->getType()->isRecordType());
   4623       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
   4624       BaseTy = E->getBase()->getType();
   4625     } else {
   4626       EvalOK = this->Visit(E->getBase());
   4627       BaseTy = E->getBase()->getType();
   4628     }
   4629     if (!EvalOK) {
   4630       if (!this->Info.allowInvalidBaseExpr())
   4631         return false;
   4632       Result.setInvalid(E);
   4633       return true;
   4634     }
   4635 
   4636     const ValueDecl *MD = E->getMemberDecl();
   4637     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
   4638       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
   4639              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
   4640       (void)BaseTy;
   4641       if (!HandleLValueMember(this->Info, E, Result, FD))
   4642         return false;
   4643     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
   4644       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
   4645         return false;
   4646     } else
   4647       return this->Error(E);
   4648 
   4649     if (MD->getType()->isReferenceType()) {
   4650       APValue RefValue;
   4651       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
   4652                                           RefValue))
   4653         return false;
   4654       return Success(RefValue, E);
   4655     }
   4656     return true;
   4657   }
   4658 
   4659   bool VisitBinaryOperator(const BinaryOperator *E) {
   4660     switch (E->getOpcode()) {
   4661     default:
   4662       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
   4663 
   4664     case BO_PtrMemD:
   4665     case BO_PtrMemI:
   4666       return HandleMemberPointerAccess(this->Info, E, Result);
   4667     }
   4668   }
   4669 
   4670   bool VisitCastExpr(const CastExpr *E) {
   4671     switch (E->getCastKind()) {
   4672     default:
   4673       return ExprEvaluatorBaseTy::VisitCastExpr(E);
   4674 
   4675     case CK_DerivedToBase:
   4676     case CK_UncheckedDerivedToBase:
   4677       if (!this->Visit(E->getSubExpr()))
   4678         return false;
   4679 
   4680       // Now figure out the necessary offset to add to the base LV to get from
   4681       // the derived class to the base class.
   4682       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
   4683                                   Result);
   4684     }
   4685   }
   4686 };
   4687 }
   4688 
   4689 //===----------------------------------------------------------------------===//
   4690 // LValue Evaluation
   4691 //
   4692 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
   4693 // function designators (in C), decl references to void objects (in C), and
   4694 // temporaries (if building with -Wno-address-of-temporary).
   4695 //
   4696 // LValue evaluation produces values comprising a base expression of one of the
   4697 // following types:
   4698 // - Declarations
   4699 //  * VarDecl
   4700 //  * FunctionDecl
   4701 // - Literals
   4702 //  * CompoundLiteralExpr in C
   4703 //  * StringLiteral
   4704 //  * CXXTypeidExpr
   4705 //  * PredefinedExpr
   4706 //  * ObjCStringLiteralExpr
   4707 //  * ObjCEncodeExpr
   4708 //  * AddrLabelExpr
   4709 //  * BlockExpr
   4710 //  * CallExpr for a MakeStringConstant builtin
   4711 // - Locals and temporaries
   4712 //  * MaterializeTemporaryExpr
   4713 //  * Any Expr, with a CallIndex indicating the function in which the temporary
   4714 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
   4715 //    from the AST (FIXME).
   4716 //  * A MaterializeTemporaryExpr that has static storage duration, with no
   4717 //    CallIndex, for a lifetime-extended temporary.
   4718 // plus an offset in bytes.
   4719 //===----------------------------------------------------------------------===//
   4720 namespace {
   4721 class LValueExprEvaluator
   4722   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
   4723 public:
   4724   LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
   4725     LValueExprEvaluatorBaseTy(Info, Result) {}
   4726 
   4727   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
   4728   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
   4729 
   4730   bool VisitDeclRefExpr(const DeclRefExpr *E);
   4731   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
   4732   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
   4733   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
   4734   bool VisitMemberExpr(const MemberExpr *E);
   4735   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
   4736   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
   4737   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
   4738   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
   4739   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
   4740   bool VisitUnaryDeref(const UnaryOperator *E);
   4741   bool VisitUnaryReal(const UnaryOperator *E);
   4742   bool VisitUnaryImag(const UnaryOperator *E);
   4743   bool VisitUnaryPreInc(const UnaryOperator *UO) {
   4744     return VisitUnaryPreIncDec(UO);
   4745   }
   4746   bool VisitUnaryPreDec(const UnaryOperator *UO) {
   4747     return VisitUnaryPreIncDec(UO);
   4748   }
   4749   bool VisitBinAssign(const BinaryOperator *BO);
   4750   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
   4751 
   4752   bool VisitCastExpr(const CastExpr *E) {
   4753     switch (E->getCastKind()) {
   4754     default:
   4755       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
   4756 
   4757     case CK_LValueBitCast:
   4758       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
   4759       if (!Visit(E->getSubExpr()))
   4760         return false;
   4761       Result.Designator.setInvalid();
   4762       return true;
   4763 
   4764     case CK_BaseToDerived:
   4765       if (!Visit(E->getSubExpr()))
   4766         return false;
   4767       return HandleBaseToDerivedCast(Info, E, Result);
   4768     }
   4769   }
   4770 };
   4771 } // end anonymous namespace
   4772 
   4773 /// Evaluate an expression as an lvalue. This can be legitimately called on
   4774 /// expressions which are not glvalues, in three cases:
   4775 ///  * function designators in C, and
   4776 ///  * "extern void" objects
   4777 ///  * @selector() expressions in Objective-C
   4778 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
   4779   assert(E->isGLValue() || E->getType()->isFunctionType() ||
   4780          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
   4781   return LValueExprEvaluator(Info, Result).Visit(E);
   4782 }
   4783 
   4784 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
   4785   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
   4786     return Success(FD);
   4787   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
   4788     return VisitVarDecl(E, VD);
   4789   return Error(E);
   4790 }
   4791 
   4792 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
   4793   CallStackFrame *Frame = nullptr;
   4794   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
   4795     Frame = Info.CurrentCall;
   4796 
   4797   if (!VD->getType()->isReferenceType()) {
   4798     if (Frame) {
   4799       Result.set(VD, Frame->Index);
   4800       return true;
   4801     }
   4802     return Success(VD);
   4803   }
   4804 
   4805   APValue *V;
   4806   if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
   4807     return false;
   4808   if (V->isUninit()) {
   4809     if (!Info.checkingPotentialConstantExpression())
   4810       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
   4811     return false;
   4812   }
   4813   return Success(*V, E);
   4814 }
   4815 
   4816 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
   4817     const MaterializeTemporaryExpr *E) {
   4818   // Walk through the expression to find the materialized temporary itself.
   4819   SmallVector<const Expr *, 2> CommaLHSs;
   4820   SmallVector<SubobjectAdjustment, 2> Adjustments;
   4821   const Expr *Inner = E->GetTemporaryExpr()->
   4822       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
   4823 
   4824   // If we passed any comma operators, evaluate their LHSs.
   4825   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
   4826     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
   4827       return false;
   4828 
   4829   // A materialized temporary with static storage duration can appear within the
   4830   // result of a constant expression evaluation, so we need to preserve its
   4831   // value for use outside this evaluation.
   4832   APValue *Value;
   4833   if (E->getStorageDuration() == SD_Static) {
   4834     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
   4835     *Value = APValue();
   4836     Result.set(E);
   4837   } else {
   4838     Value = &Info.CurrentCall->
   4839         createTemporary(E, E->getStorageDuration() == SD_Automatic);
   4840     Result.set(E, Info.CurrentCall->Index);
   4841   }
   4842 
   4843   QualType Type = Inner->getType();
   4844 
   4845   // Materialize the temporary itself.
   4846   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
   4847       (E->getStorageDuration() == SD_Static &&
   4848        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
   4849     *Value = APValue();
   4850     return false;
   4851   }
   4852 
   4853   // Adjust our lvalue to refer to the desired subobject.
   4854   for (unsigned I = Adjustments.size(); I != 0; /**/) {
   4855     --I;
   4856     switch (Adjustments[I].Kind) {
   4857     case SubobjectAdjustment::DerivedToBaseAdjustment:
   4858       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
   4859                                 Type, Result))
   4860         return false;
   4861       Type = Adjustments[I].DerivedToBase.BasePath->getType();
   4862       break;
   4863 
   4864     case SubobjectAdjustment::FieldAdjustment:
   4865       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
   4866         return false;
   4867       Type = Adjustments[I].Field->getType();
   4868       break;
   4869 
   4870     case SubobjectAdjustment::MemberPointerAdjustment:
   4871       if (!HandleMemberPointerAccess(this->Info, Type, Result,
   4872                                      Adjustments[I].Ptr.RHS))
   4873         return false;
   4874       Type = Adjustments[I].Ptr.MPT->getPointeeType();
   4875       break;
   4876     }
   4877   }
   4878 
   4879   return true;
   4880 }
   4881 
   4882 bool
   4883 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   4884   assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
   4885   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
   4886   // only see this when folding in C, so there's no standard to follow here.
   4887   return Success(E);
   4888 }
   4889 
   4890 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
   4891   if (!E->isPotentiallyEvaluated())
   4892     return Success(E);
   4893 
   4894   Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
   4895     << E->getExprOperand()->getType()
   4896     << E->getExprOperand()->getSourceRange();
   4897   return false;
   4898 }
   4899 
   4900 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
   4901   return Success(E);
   4902 }
   4903 
   4904 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
   4905   // Handle static data members.
   4906   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
   4907     VisitIgnoredBaseExpression(E->getBase());
   4908     return VisitVarDecl(E, VD);
   4909   }
   4910 
   4911   // Handle static member functions.
   4912   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
   4913     if (MD->isStatic()) {
   4914       VisitIgnoredBaseExpression(E->getBase());
   4915       return Success(MD);
   4916     }
   4917   }
   4918 
   4919   // Handle non-static data members.
   4920   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
   4921 }
   4922 
   4923 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
   4924   // FIXME: Deal with vectors as array subscript bases.
   4925   if (E->getBase()->getType()->isVectorType())
   4926     return Error(E);
   4927 
   4928   if (!EvaluatePointer(E->getBase(), Result, Info))
   4929     return false;
   4930 
   4931   APSInt Index;
   4932   if (!EvaluateInteger(E->getIdx(), Index, Info))
   4933     return false;
   4934 
   4935   return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
   4936                                      getExtValue(Index));
   4937 }
   4938 
   4939 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
   4940   return EvaluatePointer(E->getSubExpr(), Result, Info);
   4941 }
   4942 
   4943 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
   4944   if (!Visit(E->getSubExpr()))
   4945     return false;
   4946   // __real is a no-op on scalar lvalues.
   4947   if (E->getSubExpr()->getType()->isAnyComplexType())
   4948     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
   4949   return true;
   4950 }
   4951 
   4952 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   4953   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
   4954          "lvalue __imag__ on scalar?");
   4955   if (!Visit(E->getSubExpr()))
   4956     return false;
   4957   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
   4958   return true;
   4959 }
   4960 
   4961 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
   4962   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
   4963     return Error(UO);
   4964 
   4965   if (!this->Visit(UO->getSubExpr()))
   4966     return false;
   4967 
   4968   return handleIncDec(
   4969       this->Info, UO, Result, UO->getSubExpr()->getType(),
   4970       UO->isIncrementOp(), nullptr);
   4971 }
   4972 
   4973 bool LValueExprEvaluator::VisitCompoundAssignOperator(
   4974     const CompoundAssignOperator *CAO) {
   4975   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
   4976     return Error(CAO);
   4977 
   4978   APValue RHS;
   4979 
   4980   // The overall lvalue result is the result of evaluating the LHS.
   4981   if (!this->Visit(CAO->getLHS())) {
   4982     if (Info.noteFailure())
   4983       Evaluate(RHS, this->Info, CAO->getRHS());
   4984     return false;
   4985   }
   4986 
   4987   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
   4988     return false;
   4989 
   4990   return handleCompoundAssignment(
   4991       this->Info, CAO,
   4992       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
   4993       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
   4994 }
   4995 
   4996 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
   4997   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
   4998     return Error(E);
   4999 
   5000   APValue NewVal;
   5001 
   5002   if (!this->Visit(E->getLHS())) {
   5003     if (Info.noteFailure())
   5004       Evaluate(NewVal, this->Info, E->getRHS());
   5005     return false;
   5006   }
   5007 
   5008   if (!Evaluate(NewVal, this->Info, E->getRHS()))
   5009     return false;
   5010 
   5011   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
   5012                           NewVal);
   5013 }
   5014 
   5015 //===----------------------------------------------------------------------===//
   5016 // Pointer Evaluation
   5017 //===----------------------------------------------------------------------===//
   5018 
   5019 namespace {
   5020 class PointerExprEvaluator
   5021   : public ExprEvaluatorBase<PointerExprEvaluator> {
   5022   LValue &Result;
   5023 
   5024   bool Success(const Expr *E) {
   5025     Result.set(E);
   5026     return true;
   5027   }
   5028 public:
   5029 
   5030   PointerExprEvaluator(EvalInfo &info, LValue &Result)
   5031     : ExprEvaluatorBaseTy(info), Result(Result) {}
   5032 
   5033   bool Success(const APValue &V, const Expr *E) {
   5034     Result.setFrom(Info.Ctx, V);
   5035     return true;
   5036   }
   5037   bool ZeroInitialization(const Expr *E) {
   5038     return Success((Expr*)nullptr);
   5039   }
   5040 
   5041   bool VisitBinaryOperator(const BinaryOperator *E);
   5042   bool VisitCastExpr(const CastExpr* E);
   5043   bool VisitUnaryAddrOf(const UnaryOperator *E);
   5044   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
   5045       { return Success(E); }
   5046   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
   5047       { return Success(E); }
   5048   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
   5049       { return Success(E); }
   5050   bool VisitCallExpr(const CallExpr *E);
   5051   bool VisitBlockExpr(const BlockExpr *E) {
   5052     if (!E->getBlockDecl()->hasCaptures())
   5053       return Success(E);
   5054     return Error(E);
   5055   }
   5056   bool VisitCXXThisExpr(const CXXThisExpr *E) {
   5057     // Can't look at 'this' when checking a potential constant expression.
   5058     if (Info.checkingPotentialConstantExpression())
   5059       return false;
   5060     if (!Info.CurrentCall->This) {
   5061       if (Info.getLangOpts().CPlusPlus11)
   5062         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
   5063       else
   5064         Info.FFDiag(E);
   5065       return false;
   5066     }
   5067     Result = *Info.CurrentCall->This;
   5068     return true;
   5069   }
   5070 
   5071   // FIXME: Missing: @protocol, @selector
   5072 };
   5073 } // end anonymous namespace
   5074 
   5075 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
   5076   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
   5077   return PointerExprEvaluator(Info, Result).Visit(E);
   5078 }
   5079 
   5080 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   5081   if (E->getOpcode() != BO_Add &&
   5082       E->getOpcode() != BO_Sub)
   5083     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
   5084 
   5085   const Expr *PExp = E->getLHS();
   5086   const Expr *IExp = E->getRHS();
   5087   if (IExp->getType()->isPointerType())
   5088     std::swap(PExp, IExp);
   5089 
   5090   bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
   5091   if (!EvalPtrOK && !Info.noteFailure())
   5092     return false;
   5093 
   5094   llvm::APSInt Offset;
   5095   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
   5096     return false;
   5097 
   5098   int64_t AdditionalOffset = getExtValue(Offset);
   5099   if (E->getOpcode() == BO_Sub)
   5100     AdditionalOffset = -AdditionalOffset;
   5101 
   5102   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
   5103   return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
   5104                                      AdditionalOffset);
   5105 }
   5106 
   5107 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
   5108   return EvaluateLValue(E->getSubExpr(), Result, Info);
   5109 }
   5110 
   5111 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
   5112   const Expr* SubExpr = E->getSubExpr();
   5113 
   5114   switch (E->getCastKind()) {
   5115   default:
   5116     break;
   5117 
   5118   case CK_BitCast:
   5119   case CK_CPointerToObjCPointerCast:
   5120   case CK_BlockPointerToObjCPointerCast:
   5121   case CK_AnyPointerToBlockPointerCast:
   5122   case CK_AddressSpaceConversion:
   5123     if (!Visit(SubExpr))
   5124       return false;
   5125     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
   5126     // permitted in constant expressions in C++11. Bitcasts from cv void* are
   5127     // also static_casts, but we disallow them as a resolution to DR1312.
   5128     if (!E->getType()->isVoidPointerType()) {
   5129       Result.Designator.setInvalid();
   5130       if (SubExpr->getType()->isVoidPointerType())
   5131         CCEDiag(E, diag::note_constexpr_invalid_cast)
   5132           << 3 << SubExpr->getType();
   5133       else
   5134         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
   5135     }
   5136     return true;
   5137 
   5138   case CK_DerivedToBase:
   5139   case CK_UncheckedDerivedToBase:
   5140     if (!EvaluatePointer(E->getSubExpr(), Result, Info))
   5141       return false;
   5142     if (!Result.Base && Result.Offset.isZero())
   5143       return true;
   5144 
   5145     // Now figure out the necessary offset to add to the base LV to get from
   5146     // the derived class to the base class.
   5147     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
   5148                                   castAs<PointerType>()->getPointeeType(),
   5149                                 Result);
   5150 
   5151   case CK_BaseToDerived:
   5152     if (!Visit(E->getSubExpr()))
   5153       return false;
   5154     if (!Result.Base && Result.Offset.isZero())
   5155       return true;
   5156     return HandleBaseToDerivedCast(Info, E, Result);
   5157 
   5158   case CK_NullToPointer:
   5159     VisitIgnoredValue(E->getSubExpr());
   5160     return ZeroInitialization(E);
   5161 
   5162   case CK_IntegralToPointer: {
   5163     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
   5164 
   5165     APValue Value;
   5166     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
   5167       break;
   5168 
   5169     if (Value.isInt()) {
   5170       unsigned Size = Info.Ctx.getTypeSize(E->getType());
   5171       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
   5172       Result.Base = (Expr*)nullptr;
   5173       Result.InvalidBase = false;
   5174       Result.Offset = CharUnits::fromQuantity(N);
   5175       Result.CallIndex = 0;
   5176       Result.Designator.setInvalid();
   5177       return true;
   5178     } else {
   5179       // Cast is of an lvalue, no need to change value.
   5180       Result.setFrom(Info.Ctx, Value);
   5181       return true;
   5182     }
   5183   }
   5184   case CK_ArrayToPointerDecay:
   5185     if (SubExpr->isGLValue()) {
   5186       if (!EvaluateLValue(SubExpr, Result, Info))
   5187         return false;
   5188     } else {
   5189       Result.set(SubExpr, Info.CurrentCall->Index);
   5190       if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
   5191                            Info, Result, SubExpr))
   5192         return false;
   5193     }
   5194     // The result is a pointer to the first element of the array.
   5195     if (const ConstantArrayType *CAT
   5196           = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
   5197       Result.addArray(Info, E, CAT);
   5198     else
   5199       Result.Designator.setInvalid();
   5200     return true;
   5201 
   5202   case CK_FunctionToPointerDecay:
   5203     return EvaluateLValue(SubExpr, Result, Info);
   5204   }
   5205 
   5206   return ExprEvaluatorBaseTy::VisitCastExpr(E);
   5207 }
   5208 
   5209 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
   5210   // C++ [expr.alignof]p3:
   5211   //     When alignof is applied to a reference type, the result is the
   5212   //     alignment of the referenced type.
   5213   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
   5214     T = Ref->getPointeeType();
   5215 
   5216   // __alignof is defined to return the preferred alignment.
   5217   return Info.Ctx.toCharUnitsFromBits(
   5218     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
   5219 }
   5220 
   5221 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
   5222   E = E->IgnoreParens();
   5223 
   5224   // The kinds of expressions that we have special-case logic here for
   5225   // should be kept up to date with the special checks for those
   5226   // expressions in Sema.
   5227 
   5228   // alignof decl is always accepted, even if it doesn't make sense: we default
   5229   // to 1 in those cases.
   5230   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
   5231     return Info.Ctx.getDeclAlign(DRE->getDecl(),
   5232                                  /*RefAsPointee*/true);
   5233 
   5234   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
   5235     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
   5236                                  /*RefAsPointee*/true);
   5237 
   5238   return GetAlignOfType(Info, E->getType());
   5239 }
   5240 
   5241 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
   5242   if (IsStringLiteralCall(E))
   5243     return Success(E);
   5244 
   5245   switch (E->getBuiltinCallee()) {
   5246   case Builtin::BI__builtin_addressof:
   5247     return EvaluateLValue(E->getArg(0), Result, Info);
   5248   case Builtin::BI__builtin_assume_aligned: {
   5249     // We need to be very careful here because: if the pointer does not have the
   5250     // asserted alignment, then the behavior is undefined, and undefined
   5251     // behavior is non-constant.
   5252     if (!EvaluatePointer(E->getArg(0), Result, Info))
   5253       return false;
   5254 
   5255     LValue OffsetResult(Result);
   5256     APSInt Alignment;
   5257     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
   5258       return false;
   5259     CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
   5260 
   5261     if (E->getNumArgs() > 2) {
   5262       APSInt Offset;
   5263       if (!EvaluateInteger(E->getArg(2), Offset, Info))
   5264         return false;
   5265 
   5266       int64_t AdditionalOffset = -getExtValue(Offset);
   5267       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
   5268     }
   5269 
   5270     // If there is a base object, then it must have the correct alignment.
   5271     if (OffsetResult.Base) {
   5272       CharUnits BaseAlignment;
   5273       if (const ValueDecl *VD =
   5274           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
   5275         BaseAlignment = Info.Ctx.getDeclAlign(VD);
   5276       } else {
   5277         BaseAlignment =
   5278           GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
   5279       }
   5280 
   5281       if (BaseAlignment < Align) {
   5282         Result.Designator.setInvalid();
   5283 	// FIXME: Quantities here cast to integers because the plural modifier
   5284 	// does not work on APSInts yet.
   5285         CCEDiag(E->getArg(0),
   5286                 diag::note_constexpr_baa_insufficient_alignment) << 0
   5287           << (int) BaseAlignment.getQuantity()
   5288           << (unsigned) getExtValue(Alignment);
   5289         return false;
   5290       }
   5291     }
   5292 
   5293     // The offset must also have the correct alignment.
   5294     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
   5295       Result.Designator.setInvalid();
   5296       APSInt Offset(64, false);
   5297       Offset = OffsetResult.Offset.getQuantity();
   5298 
   5299       if (OffsetResult.Base)
   5300         CCEDiag(E->getArg(0),
   5301                 diag::note_constexpr_baa_insufficient_alignment) << 1
   5302           << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
   5303       else
   5304         CCEDiag(E->getArg(0),
   5305                 diag::note_constexpr_baa_value_insufficient_alignment)
   5306           << Offset << (unsigned) getExtValue(Alignment);
   5307 
   5308       return false;
   5309     }
   5310 
   5311     return true;
   5312   }
   5313   default:
   5314     return ExprEvaluatorBaseTy::VisitCallExpr(E);
   5315   }
   5316 }
   5317 
   5318 //===----------------------------------------------------------------------===//
   5319 // Member Pointer Evaluation
   5320 //===----------------------------------------------------------------------===//
   5321 
   5322 namespace {
   5323 class MemberPointerExprEvaluator
   5324   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
   5325   MemberPtr &Result;
   5326 
   5327   bool Success(const ValueDecl *D) {
   5328     Result = MemberPtr(D);
   5329     return true;
   5330   }
   5331 public:
   5332 
   5333   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
   5334     : ExprEvaluatorBaseTy(Info), Result(Result) {}
   5335 
   5336   bool Success(const APValue &V, const Expr *E) {
   5337     Result.setFrom(V);
   5338     return true;
   5339   }
   5340   bool ZeroInitialization(const Expr *E) {
   5341     return Success((const ValueDecl*)nullptr);
   5342   }
   5343 
   5344   bool VisitCastExpr(const CastExpr *E);
   5345   bool VisitUnaryAddrOf(const UnaryOperator *E);
   5346 };
   5347 } // end anonymous namespace
   5348 
   5349 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
   5350                                   EvalInfo &Info) {
   5351   assert(E->isRValue() && E->getType()->isMemberPointerType());
   5352   return MemberPointerExprEvaluator(Info, Result).Visit(E);
   5353 }
   5354 
   5355 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
   5356   switch (E->getCastKind()) {
   5357   default:
   5358     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   5359 
   5360   case CK_NullToMemberPointer:
   5361     VisitIgnoredValue(E->getSubExpr());
   5362     return ZeroInitialization(E);
   5363 
   5364   case CK_BaseToDerivedMemberPointer: {
   5365     if (!Visit(E->getSubExpr()))
   5366       return false;
   5367     if (E->path_empty())
   5368       return true;
   5369     // Base-to-derived member pointer casts store the path in derived-to-base
   5370     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
   5371     // the wrong end of the derived->base arc, so stagger the path by one class.
   5372     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
   5373     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
   5374          PathI != PathE; ++PathI) {
   5375       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
   5376       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
   5377       if (!Result.castToDerived(Derived))
   5378         return Error(E);
   5379     }
   5380     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
   5381     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
   5382       return Error(E);
   5383     return true;
   5384   }
   5385 
   5386   case CK_DerivedToBaseMemberPointer:
   5387     if (!Visit(E->getSubExpr()))
   5388       return false;
   5389     for (CastExpr::path_const_iterator PathI = E->path_begin(),
   5390          PathE = E->path_end(); PathI != PathE; ++PathI) {
   5391       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
   5392       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
   5393       if (!Result.castToBase(Base))
   5394         return Error(E);
   5395     }
   5396     return true;
   5397   }
   5398 }
   5399 
   5400 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
   5401   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
   5402   // member can be formed.
   5403   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
   5404 }
   5405 
   5406 //===----------------------------------------------------------------------===//
   5407 // Record Evaluation
   5408 //===----------------------------------------------------------------------===//
   5409 
   5410 namespace {
   5411   class RecordExprEvaluator
   5412   : public ExprEvaluatorBase<RecordExprEvaluator> {
   5413     const LValue &This;
   5414     APValue &Result;
   5415   public:
   5416 
   5417     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
   5418       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
   5419 
   5420     bool Success(const APValue &V, const Expr *E) {
   5421       Result = V;
   5422       return true;
   5423     }
   5424     bool ZeroInitialization(const Expr *E) {
   5425       return ZeroInitialization(E, E->getType());
   5426     }
   5427     bool ZeroInitialization(const Expr *E, QualType T);
   5428 
   5429     bool VisitCallExpr(const CallExpr *E) {
   5430       return handleCallExpr(E, Result, &This);
   5431     }
   5432     bool VisitCastExpr(const CastExpr *E);
   5433     bool VisitInitListExpr(const InitListExpr *E);
   5434     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
   5435       return VisitCXXConstructExpr(E, E->getType());
   5436     }
   5437     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
   5438     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
   5439     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
   5440   };
   5441 }
   5442 
   5443 /// Perform zero-initialization on an object of non-union class type.
   5444 /// C++11 [dcl.init]p5:
   5445 ///  To zero-initialize an object or reference of type T means:
   5446 ///    [...]
   5447 ///    -- if T is a (possibly cv-qualified) non-union class type,
   5448 ///       each non-static data member and each base-class subobject is
   5449 ///       zero-initialized
   5450 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
   5451                                           const RecordDecl *RD,
   5452                                           const LValue &This, APValue &Result) {
   5453   assert(!RD->isUnion() && "Expected non-union class type");
   5454   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
   5455   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
   5456                    std::distance(RD->field_begin(), RD->field_end()));
   5457 
   5458   if (RD->isInvalidDecl()) return false;
   5459   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
   5460 
   5461   if (CD) {
   5462     unsigned Index = 0;
   5463     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
   5464            End = CD->bases_end(); I != End; ++I, ++Index) {
   5465       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
   5466       LValue Subobject = This;
   5467       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
   5468         return false;
   5469       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
   5470                                          Result.getStructBase(Index)))
   5471         return false;
   5472     }
   5473   }
   5474 
   5475   for (const auto *I : RD->fields()) {
   5476     // -- if T is a reference type, no initialization is performed.
   5477     if (I->getType()->isReferenceType())
   5478       continue;
   5479 
   5480     LValue Subobject = This;
   5481     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
   5482       return false;
   5483 
   5484     ImplicitValueInitExpr VIE(I->getType());
   5485     if (!EvaluateInPlace(
   5486           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
   5487       return false;
   5488   }
   5489 
   5490   return true;
   5491 }
   5492 
   5493 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
   5494   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
   5495   if (RD->isInvalidDecl()) return false;
   5496   if (RD->isUnion()) {
   5497     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
   5498     // object's first non-static named data member is zero-initialized
   5499     RecordDecl::field_iterator I = RD->field_begin();
   5500     if (I == RD->field_end()) {
   5501       Result = APValue((const FieldDecl*)nullptr);
   5502       return true;
   5503     }
   5504 
   5505     LValue Subobject = This;
   5506     if (!HandleLValueMember(Info, E, Subobject, *I))
   5507       return false;
   5508     Result = APValue(*I);
   5509     ImplicitValueInitExpr VIE(I->getType());
   5510     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
   5511   }
   5512 
   5513   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
   5514     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
   5515     return false;
   5516   }
   5517 
   5518   return HandleClassZeroInitialization(Info, E, RD, This, Result);
   5519 }
   5520 
   5521 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
   5522   switch (E->getCastKind()) {
   5523   default:
   5524     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   5525 
   5526   case CK_ConstructorConversion:
   5527     return Visit(E->getSubExpr());
   5528 
   5529   case CK_DerivedToBase:
   5530   case CK_UncheckedDerivedToBase: {
   5531     APValue DerivedObject;
   5532     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
   5533       return false;
   5534     if (!DerivedObject.isStruct())
   5535       return Error(E->getSubExpr());
   5536 
   5537     // Derived-to-base rvalue conversion: just slice off the derived part.
   5538     APValue *Value = &DerivedObject;
   5539     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
   5540     for (CastExpr::path_const_iterator PathI = E->path_begin(),
   5541          PathE = E->path_end(); PathI != PathE; ++PathI) {
   5542       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
   5543       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
   5544       Value = &Value->getStructBase(getBaseIndex(RD, Base));
   5545       RD = Base;
   5546     }
   5547     Result = *Value;
   5548     return true;
   5549   }
   5550   }
   5551 }
   5552 
   5553 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
   5554   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
   5555   if (RD->isInvalidDecl()) return false;
   5556   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
   5557 
   5558   if (RD->isUnion()) {
   5559     const FieldDecl *Field = E->getInitializedFieldInUnion();
   5560     Result = APValue(Field);
   5561     if (!Field)
   5562       return true;
   5563 
   5564     // If the initializer list for a union does not contain any elements, the
   5565     // first element of the union is value-initialized.
   5566     // FIXME: The element should be initialized from an initializer list.
   5567     //        Is this difference ever observable for initializer lists which
   5568     //        we don't build?
   5569     ImplicitValueInitExpr VIE(Field->getType());
   5570     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
   5571 
   5572     LValue Subobject = This;
   5573     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
   5574       return false;
   5575 
   5576     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
   5577     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
   5578                                   isa<CXXDefaultInitExpr>(InitExpr));
   5579 
   5580     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
   5581   }
   5582 
   5583   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
   5584   if (Result.isUninit())
   5585     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
   5586                      std::distance(RD->field_begin(), RD->field_end()));
   5587   unsigned ElementNo = 0;
   5588   bool Success = true;
   5589 
   5590   // Initialize base classes.
   5591   if (CXXRD) {
   5592     for (const auto &Base : CXXRD->bases()) {
   5593       assert(ElementNo < E->getNumInits() && "missing init for base class");
   5594       const Expr *Init = E->getInit(ElementNo);
   5595 
   5596       LValue Subobject = This;
   5597       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
   5598         return false;
   5599 
   5600       APValue &FieldVal = Result.getStructBase(ElementNo);
   5601       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
   5602         if (!Info.noteFailure())
   5603           return false;
   5604         Success = false;
   5605       }
   5606       ++ElementNo;
   5607     }
   5608   }
   5609 
   5610   // Initialize members.
   5611   for (const auto *Field : RD->fields()) {
   5612     // Anonymous bit-fields are not considered members of the class for
   5613     // purposes of aggregate initialization.
   5614     if (Field->isUnnamedBitfield())
   5615       continue;
   5616 
   5617     LValue Subobject = This;
   5618 
   5619     bool HaveInit = ElementNo < E->getNumInits();
   5620 
   5621     // FIXME: Diagnostics here should point to the end of the initializer
   5622     // list, not the start.
   5623     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
   5624                             Subobject, Field, &Layout))
   5625       return false;
   5626 
   5627     // Perform an implicit value-initialization for members beyond the end of
   5628     // the initializer list.
   5629     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
   5630     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
   5631 
   5632     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
   5633     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
   5634                                   isa<CXXDefaultInitExpr>(Init));
   5635 
   5636     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
   5637     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
   5638         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
   5639                                                        FieldVal, Field))) {
   5640       if (!Info.noteFailure())
   5641         return false;
   5642       Success = false;
   5643     }
   5644   }
   5645 
   5646   return Success;
   5647 }
   5648 
   5649 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
   5650                                                 QualType T) {
   5651   // Note that E's type is not necessarily the type of our class here; we might
   5652   // be initializing an array element instead.
   5653   const CXXConstructorDecl *FD = E->getConstructor();
   5654   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
   5655 
   5656   bool ZeroInit = E->requiresZeroInitialization();
   5657   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
   5658     // If we've already performed zero-initialization, we're already done.
   5659     if (!Result.isUninit())
   5660       return true;
   5661 
   5662     // We can get here in two different ways:
   5663     //  1) We're performing value-initialization, and should zero-initialize
   5664     //     the object, or
   5665     //  2) We're performing default-initialization of an object with a trivial
   5666     //     constexpr default constructor, in which case we should start the
   5667     //     lifetimes of all the base subobjects (there can be no data member
   5668     //     subobjects in this case) per [basic.life]p1.
   5669     // Either way, ZeroInitialization is appropriate.
   5670     return ZeroInitialization(E, T);
   5671   }
   5672 
   5673   const FunctionDecl *Definition = nullptr;
   5674   auto Body = FD->getBody(Definition);
   5675 
   5676   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
   5677     return false;
   5678 
   5679   // Avoid materializing a temporary for an elidable copy/move constructor.
   5680   if (E->isElidable() && !ZeroInit)
   5681     if (const MaterializeTemporaryExpr *ME
   5682           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
   5683       return Visit(ME->GetTemporaryExpr());
   5684 
   5685   if (ZeroInit && !ZeroInitialization(E, T))
   5686     return false;
   5687 
   5688   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
   5689   return HandleConstructorCall(E, This, Args,
   5690                                cast<CXXConstructorDecl>(Definition), Info,
   5691                                Result);
   5692 }
   5693 
   5694 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
   5695     const CXXInheritedCtorInitExpr *E) {
   5696   if (!Info.CurrentCall) {
   5697     assert(Info.checkingPotentialConstantExpression());
   5698     return false;
   5699   }
   5700 
   5701   const CXXConstructorDecl *FD = E->getConstructor();
   5702   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
   5703     return false;
   5704 
   5705   const FunctionDecl *Definition = nullptr;
   5706   auto Body = FD->getBody(Definition);
   5707 
   5708   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
   5709     return false;
   5710 
   5711   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
   5712                                cast<CXXConstructorDecl>(Definition), Info,
   5713                                Result);
   5714 }
   5715 
   5716 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
   5717     const CXXStdInitializerListExpr *E) {
   5718   const ConstantArrayType *ArrayType =
   5719       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
   5720 
   5721   LValue Array;
   5722   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
   5723     return false;
   5724 
   5725   // Get a pointer to the first element of the array.
   5726   Array.addArray(Info, E, ArrayType);
   5727 
   5728   // FIXME: Perform the checks on the field types in SemaInit.
   5729   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
   5730   RecordDecl::field_iterator Field = Record->field_begin();
   5731   if (Field == Record->field_end())
   5732     return Error(E);
   5733 
   5734   // Start pointer.
   5735   if (!Field->getType()->isPointerType() ||
   5736       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
   5737                             ArrayType->getElementType()))
   5738     return Error(E);
   5739 
   5740   // FIXME: What if the initializer_list type has base classes, etc?
   5741   Result = APValue(APValue::UninitStruct(), 0, 2);
   5742   Array.moveInto(Result.getStructField(0));
   5743 
   5744   if (++Field == Record->field_end())
   5745     return Error(E);
   5746 
   5747   if (Field->getType()->isPointerType() &&
   5748       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
   5749                            ArrayType->getElementType())) {
   5750     // End pointer.
   5751     if (!HandleLValueArrayAdjustment(Info, E, Array,
   5752                                      ArrayType->getElementType(),
   5753                                      ArrayType->getSize().getZExtValue()))
   5754       return false;
   5755     Array.moveInto(Result.getStructField(1));
   5756   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
   5757     // Length.
   5758     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
   5759   else
   5760     return Error(E);
   5761 
   5762   if (++Field != Record->field_end())
   5763     return Error(E);
   5764 
   5765   return true;
   5766 }
   5767 
   5768 static bool EvaluateRecord(const Expr *E, const LValue &This,
   5769                            APValue &Result, EvalInfo &Info) {
   5770   assert(E->isRValue() && E->getType()->isRecordType() &&
   5771          "can't evaluate expression as a record rvalue");
   5772   return RecordExprEvaluator(Info, This, Result).Visit(E);
   5773 }
   5774 
   5775 //===----------------------------------------------------------------------===//
   5776 // Temporary Evaluation
   5777 //
   5778 // Temporaries are represented in the AST as rvalues, but generally behave like
   5779 // lvalues. The full-object of which the temporary is a subobject is implicitly
   5780 // materialized so that a reference can bind to it.
   5781 //===----------------------------------------------------------------------===//
   5782 namespace {
   5783 class TemporaryExprEvaluator
   5784   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
   5785 public:
   5786   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
   5787     LValueExprEvaluatorBaseTy(Info, Result) {}
   5788 
   5789   /// Visit an expression which constructs the value of this temporary.
   5790   bool VisitConstructExpr(const Expr *E) {
   5791     Result.set(E, Info.CurrentCall->Index);
   5792     return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
   5793                            Info, Result, E);
   5794   }
   5795 
   5796   bool VisitCastExpr(const CastExpr *E) {
   5797     switch (E->getCastKind()) {
   5798     default:
   5799       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
   5800 
   5801     case CK_ConstructorConversion:
   5802       return VisitConstructExpr(E->getSubExpr());
   5803     }
   5804   }
   5805   bool VisitInitListExpr(const InitListExpr *E) {
   5806     return VisitConstructExpr(E);
   5807   }
   5808   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
   5809     return VisitConstructExpr(E);
   5810   }
   5811   bool VisitCallExpr(const CallExpr *E) {
   5812     return VisitConstructExpr(E);
   5813   }
   5814   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
   5815     return VisitConstructExpr(E);
   5816   }
   5817 };
   5818 } // end anonymous namespace
   5819 
   5820 /// Evaluate an expression of record type as a temporary.
   5821 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
   5822   assert(E->isRValue() && E->getType()->isRecordType());
   5823   return TemporaryExprEvaluator(Info, Result).Visit(E);
   5824 }
   5825 
   5826 //===----------------------------------------------------------------------===//
   5827 // Vector Evaluation
   5828 //===----------------------------------------------------------------------===//
   5829 
   5830 namespace {
   5831   class VectorExprEvaluator
   5832   : public ExprEvaluatorBase<VectorExprEvaluator> {
   5833     APValue &Result;
   5834   public:
   5835 
   5836     VectorExprEvaluator(EvalInfo &info, APValue &Result)
   5837       : ExprEvaluatorBaseTy(info), Result(Result) {}
   5838 
   5839     bool Success(ArrayRef<APValue> V, const Expr *E) {
   5840       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
   5841       // FIXME: remove this APValue copy.
   5842       Result = APValue(V.data(), V.size());
   5843       return true;
   5844     }
   5845     bool Success(const APValue &V, const Expr *E) {
   5846       assert(V.isVector());
   5847       Result = V;
   5848       return true;
   5849     }
   5850     bool ZeroInitialization(const Expr *E);
   5851 
   5852     bool VisitUnaryReal(const UnaryOperator *E)
   5853       { return Visit(E->getSubExpr()); }
   5854     bool VisitCastExpr(const CastExpr* E);
   5855     bool VisitInitListExpr(const InitListExpr *E);
   5856     bool VisitUnaryImag(const UnaryOperator *E);
   5857     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
   5858     //                 binary comparisons, binary and/or/xor,
   5859     //                 shufflevector, ExtVectorElementExpr
   5860   };
   5861 } // end anonymous namespace
   5862 
   5863 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
   5864   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
   5865   return VectorExprEvaluator(Info, Result).Visit(E);
   5866 }
   5867 
   5868 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
   5869   const VectorType *VTy = E->getType()->castAs<VectorType>();
   5870   unsigned NElts = VTy->getNumElements();
   5871 
   5872   const Expr *SE = E->getSubExpr();
   5873   QualType SETy = SE->getType();
   5874 
   5875   switch (E->getCastKind()) {
   5876   case CK_VectorSplat: {
   5877     APValue Val = APValue();
   5878     if (SETy->isIntegerType()) {
   5879       APSInt IntResult;
   5880       if (!EvaluateInteger(SE, IntResult, Info))
   5881         return false;
   5882       Val = APValue(std::move(IntResult));
   5883     } else if (SETy->isRealFloatingType()) {
   5884       APFloat FloatResult(0.0);
   5885       if (!EvaluateFloat(SE, FloatResult, Info))
   5886         return false;
   5887       Val = APValue(std::move(FloatResult));
   5888     } else {
   5889       return Error(E);
   5890     }
   5891 
   5892     // Splat and create vector APValue.
   5893     SmallVector<APValue, 4> Elts(NElts, Val);
   5894     return Success(Elts, E);
   5895   }
   5896   case CK_BitCast: {
   5897     // Evaluate the operand into an APInt we can extract from.
   5898     llvm::APInt SValInt;
   5899     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
   5900       return false;
   5901     // Extract the elements
   5902     QualType EltTy = VTy->getElementType();
   5903     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
   5904     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
   5905     SmallVector<APValue, 4> Elts;
   5906     if (EltTy->isRealFloatingType()) {
   5907       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
   5908       unsigned FloatEltSize = EltSize;
   5909       if (&Sem == &APFloat::x87DoubleExtended)
   5910         FloatEltSize = 80;
   5911       for (unsigned i = 0; i < NElts; i++) {
   5912         llvm::APInt Elt;
   5913         if (BigEndian)
   5914           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
   5915         else
   5916           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
   5917         Elts.push_back(APValue(APFloat(Sem, Elt)));
   5918       }
   5919     } else if (EltTy->isIntegerType()) {
   5920       for (unsigned i = 0; i < NElts; i++) {
   5921         llvm::APInt Elt;
   5922         if (BigEndian)
   5923           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
   5924         else
   5925           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
   5926         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
   5927       }
   5928     } else {
   5929       return Error(E);
   5930     }
   5931     return Success(Elts, E);
   5932   }
   5933   default:
   5934     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   5935   }
   5936 }
   5937 
   5938 bool
   5939 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
   5940   const VectorType *VT = E->getType()->castAs<VectorType>();
   5941   unsigned NumInits = E->getNumInits();
   5942   unsigned NumElements = VT->getNumElements();
   5943 
   5944   QualType EltTy = VT->getElementType();
   5945   SmallVector<APValue, 4> Elements;
   5946 
   5947   // The number of initializers can be less than the number of
   5948   // vector elements. For OpenCL, this can be due to nested vector
   5949   // initialization. For GCC compatibility, missing trailing elements
   5950   // should be initialized with zeroes.
   5951   unsigned CountInits = 0, CountElts = 0;
   5952   while (CountElts < NumElements) {
   5953     // Handle nested vector initialization.
   5954     if (CountInits < NumInits
   5955         && E->getInit(CountInits)->getType()->isVectorType()) {
   5956       APValue v;
   5957       if (!EvaluateVector(E->getInit(CountInits), v, Info))
   5958         return Error(E);
   5959       unsigned vlen = v.getVectorLength();
   5960       for (unsigned j = 0; j < vlen; j++)
   5961         Elements.push_back(v.getVectorElt(j));
   5962       CountElts += vlen;
   5963     } else if (EltTy->isIntegerType()) {
   5964       llvm::APSInt sInt(32);
   5965       if (CountInits < NumInits) {
   5966         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
   5967           return false;
   5968       } else // trailing integer zero.
   5969         sInt = Info.Ctx.MakeIntValue(0, EltTy);
   5970       Elements.push_back(APValue(sInt));
   5971       CountElts++;
   5972     } else {
   5973       llvm::APFloat f(0.0);
   5974       if (CountInits < NumInits) {
   5975         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
   5976           return false;
   5977       } else // trailing float zero.
   5978         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
   5979       Elements.push_back(APValue(f));
   5980       CountElts++;
   5981     }
   5982     CountInits++;
   5983   }
   5984   return Success(Elements, E);
   5985 }
   5986 
   5987 bool
   5988 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
   5989   const VectorType *VT = E->getType()->getAs<VectorType>();
   5990   QualType EltTy = VT->getElementType();
   5991   APValue ZeroElement;
   5992   if (EltTy->isIntegerType())
   5993     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
   5994   else
   5995     ZeroElement =
   5996         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
   5997 
   5998   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
   5999   return Success(Elements, E);
   6000 }
   6001 
   6002 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   6003   VisitIgnoredValue(E->getSubExpr());
   6004   return ZeroInitialization(E);
   6005 }
   6006 
   6007 //===----------------------------------------------------------------------===//
   6008 // Array Evaluation
   6009 //===----------------------------------------------------------------------===//
   6010 
   6011 namespace {
   6012   class ArrayExprEvaluator
   6013   : public ExprEvaluatorBase<ArrayExprEvaluator> {
   6014     const LValue &This;
   6015     APValue &Result;
   6016   public:
   6017 
   6018     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
   6019       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
   6020 
   6021     bool Success(const APValue &V, const Expr *E) {
   6022       assert((V.isArray() || V.isLValue()) &&
   6023              "expected array or string literal");
   6024       Result = V;
   6025       return true;
   6026     }
   6027 
   6028     bool ZeroInitialization(const Expr *E) {
   6029       const ConstantArrayType *CAT =
   6030           Info.Ctx.getAsConstantArrayType(E->getType());
   6031       if (!CAT)
   6032         return Error(E);
   6033 
   6034       Result = APValue(APValue::UninitArray(), 0,
   6035                        CAT->getSize().getZExtValue());
   6036       if (!Result.hasArrayFiller()) return true;
   6037 
   6038       // Zero-initialize all elements.
   6039       LValue Subobject = This;
   6040       Subobject.addArray(Info, E, CAT);
   6041       ImplicitValueInitExpr VIE(CAT->getElementType());
   6042       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
   6043     }
   6044 
   6045     bool VisitCallExpr(const CallExpr *E) {
   6046       return handleCallExpr(E, Result, &This);
   6047     }
   6048     bool VisitInitListExpr(const InitListExpr *E);
   6049     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
   6050     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
   6051                                const LValue &Subobject,
   6052                                APValue *Value, QualType Type);
   6053   };
   6054 } // end anonymous namespace
   6055 
   6056 static bool EvaluateArray(const Expr *E, const LValue &This,
   6057                           APValue &Result, EvalInfo &Info) {
   6058   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
   6059   return ArrayExprEvaluator(Info, This, Result).Visit(E);
   6060 }
   6061 
   6062 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
   6063   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
   6064   if (!CAT)
   6065     return Error(E);
   6066 
   6067   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
   6068   // an appropriately-typed string literal enclosed in braces.
   6069   if (E->isStringLiteralInit()) {
   6070     LValue LV;
   6071     if (!EvaluateLValue(E->getInit(0), LV, Info))
   6072       return false;
   6073     APValue Val;
   6074     LV.moveInto(Val);
   6075     return Success(Val, E);
   6076   }
   6077 
   6078   bool Success = true;
   6079 
   6080   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
   6081          "zero-initialized array shouldn't have any initialized elts");
   6082   APValue Filler;
   6083   if (Result.isArray() && Result.hasArrayFiller())
   6084     Filler = Result.getArrayFiller();
   6085 
   6086   unsigned NumEltsToInit = E->getNumInits();
   6087   unsigned NumElts = CAT->getSize().getZExtValue();
   6088   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
   6089 
   6090   // If the initializer might depend on the array index, run it for each
   6091   // array element. For now, just whitelist non-class value-initialization.
   6092   if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
   6093     NumEltsToInit = NumElts;
   6094 
   6095   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
   6096 
   6097   // If the array was previously zero-initialized, preserve the
   6098   // zero-initialized values.
   6099   if (!Filler.isUninit()) {
   6100     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
   6101       Result.getArrayInitializedElt(I) = Filler;
   6102     if (Result.hasArrayFiller())
   6103       Result.getArrayFiller() = Filler;
   6104   }
   6105 
   6106   LValue Subobject = This;
   6107   Subobject.addArray(Info, E, CAT);
   6108   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
   6109     const Expr *Init =
   6110         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
   6111     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
   6112                          Info, Subobject, Init) ||
   6113         !HandleLValueArrayAdjustment(Info, Init, Subobject,
   6114                                      CAT->getElementType(), 1)) {
   6115       if (!Info.noteFailure())
   6116         return false;
   6117       Success = false;
   6118     }
   6119   }
   6120 
   6121   if (!Result.hasArrayFiller())
   6122     return Success;
   6123 
   6124   // If we get here, we have a trivial filler, which we can just evaluate
   6125   // once and splat over the rest of the array elements.
   6126   assert(FillerExpr && "no array filler for incomplete init list");
   6127   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
   6128                          FillerExpr) && Success;
   6129 }
   6130 
   6131 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
   6132   return VisitCXXConstructExpr(E, This, &Result, E->getType());
   6133 }
   6134 
   6135 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
   6136                                                const LValue &Subobject,
   6137                                                APValue *Value,
   6138                                                QualType Type) {
   6139   bool HadZeroInit = !Value->isUninit();
   6140 
   6141   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
   6142     unsigned N = CAT->getSize().getZExtValue();
   6143 
   6144     // Preserve the array filler if we had prior zero-initialization.
   6145     APValue Filler =
   6146       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
   6147                                              : APValue();
   6148 
   6149     *Value = APValue(APValue::UninitArray(), N, N);
   6150 
   6151     if (HadZeroInit)
   6152       for (unsigned I = 0; I != N; ++I)
   6153         Value->getArrayInitializedElt(I) = Filler;
   6154 
   6155     // Initialize the elements.
   6156     LValue ArrayElt = Subobject;
   6157     ArrayElt.addArray(Info, E, CAT);
   6158     for (unsigned I = 0; I != N; ++I)
   6159       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
   6160                                  CAT->getElementType()) ||
   6161           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
   6162                                        CAT->getElementType(), 1))
   6163         return false;
   6164 
   6165     return true;
   6166   }
   6167 
   6168   if (!Type->isRecordType())
   6169     return Error(E);
   6170 
   6171   return RecordExprEvaluator(Info, Subobject, *Value)
   6172              .VisitCXXConstructExpr(E, Type);
   6173 }
   6174 
   6175 //===----------------------------------------------------------------------===//
   6176 // Integer Evaluation
   6177 //
   6178 // As a GNU extension, we support casting pointers to sufficiently-wide integer
   6179 // types and back in constant folding. Integer values are thus represented
   6180 // either as an integer-valued APValue, or as an lvalue-valued APValue.
   6181 //===----------------------------------------------------------------------===//
   6182 
   6183 namespace {
   6184 class IntExprEvaluator
   6185   : public ExprEvaluatorBase<IntExprEvaluator> {
   6186   APValue &Result;
   6187 public:
   6188   IntExprEvaluator(EvalInfo &info, APValue &result)
   6189     : ExprEvaluatorBaseTy(info), Result(result) {}
   6190 
   6191   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
   6192     assert(E->getType()->isIntegralOrEnumerationType() &&
   6193            "Invalid evaluation result.");
   6194     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
   6195            "Invalid evaluation result.");
   6196     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
   6197            "Invalid evaluation result.");
   6198     Result = APValue(SI);
   6199     return true;
   6200   }
   6201   bool Success(const llvm::APSInt &SI, const Expr *E) {
   6202     return Success(SI, E, Result);
   6203   }
   6204 
   6205   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
   6206     assert(E->getType()->isIntegralOrEnumerationType() &&
   6207            "Invalid evaluation result.");
   6208     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
   6209            "Invalid evaluation result.");
   6210     Result = APValue(APSInt(I));
   6211     Result.getInt().setIsUnsigned(
   6212                             E->getType()->isUnsignedIntegerOrEnumerationType());
   6213     return true;
   6214   }
   6215   bool Success(const llvm::APInt &I, const Expr *E) {
   6216     return Success(I, E, Result);
   6217   }
   6218 
   6219   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
   6220     assert(E->getType()->isIntegralOrEnumerationType() &&
   6221            "Invalid evaluation result.");
   6222     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
   6223     return true;
   6224   }
   6225   bool Success(uint64_t Value, const Expr *E) {
   6226     return Success(Value, E, Result);
   6227   }
   6228 
   6229   bool Success(CharUnits Size, const Expr *E) {
   6230     return Success(Size.getQuantity(), E);
   6231   }
   6232 
   6233   bool Success(const APValue &V, const Expr *E) {
   6234     if (V.isLValue() || V.isAddrLabelDiff()) {
   6235       Result = V;
   6236       return true;
   6237     }
   6238     return Success(V.getInt(), E);
   6239   }
   6240 
   6241   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
   6242 
   6243   //===--------------------------------------------------------------------===//
   6244   //                            Visitor Methods
   6245   //===--------------------------------------------------------------------===//
   6246 
   6247   bool VisitIntegerLiteral(const IntegerLiteral *E) {
   6248     return Success(E->getValue(), E);
   6249   }
   6250   bool VisitCharacterLiteral(const CharacterLiteral *E) {
   6251     return Success(E->getValue(), E);
   6252   }
   6253 
   6254   bool CheckReferencedDecl(const Expr *E, const Decl *D);
   6255   bool VisitDeclRefExpr(const DeclRefExpr *E) {
   6256     if (CheckReferencedDecl(E, E->getDecl()))
   6257       return true;
   6258 
   6259     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
   6260   }
   6261   bool VisitMemberExpr(const MemberExpr *E) {
   6262     if (CheckReferencedDecl(E, E->getMemberDecl())) {
   6263       VisitIgnoredBaseExpression(E->getBase());
   6264       return true;
   6265     }
   6266 
   6267     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
   6268   }
   6269 
   6270   bool VisitCallExpr(const CallExpr *E);
   6271   bool VisitBinaryOperator(const BinaryOperator *E);
   6272   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
   6273   bool VisitUnaryOperator(const UnaryOperator *E);
   6274 
   6275   bool VisitCastExpr(const CastExpr* E);
   6276   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
   6277 
   6278   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
   6279     return Success(E->getValue(), E);
   6280   }
   6281 
   6282   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
   6283     return Success(E->getValue(), E);
   6284   }
   6285 
   6286   // Note, GNU defines __null as an integer, not a pointer.
   6287   bool VisitGNUNullExpr(const GNUNullExpr *E) {
   6288     return ZeroInitialization(E);
   6289   }
   6290 
   6291   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
   6292     return Success(E->getValue(), E);
   6293   }
   6294 
   6295   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
   6296     return Success(E->getValue(), E);
   6297   }
   6298 
   6299   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
   6300     return Success(E->getValue(), E);
   6301   }
   6302 
   6303   bool VisitUnaryReal(const UnaryOperator *E);
   6304   bool VisitUnaryImag(const UnaryOperator *E);
   6305 
   6306   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
   6307   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
   6308 
   6309 private:
   6310   bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
   6311   // FIXME: Missing: array subscript of vector, member of vector
   6312 };
   6313 } // end anonymous namespace
   6314 
   6315 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
   6316 /// produce either the integer value or a pointer.
   6317 ///
   6318 /// GCC has a heinous extension which folds casts between pointer types and
   6319 /// pointer-sized integral types. We support this by allowing the evaluation of
   6320 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
   6321 /// Some simple arithmetic on such values is supported (they are treated much
   6322 /// like char*).
   6323 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
   6324                                     EvalInfo &Info) {
   6325   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
   6326   return IntExprEvaluator(Info, Result).Visit(E);
   6327 }
   6328 
   6329 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
   6330   APValue Val;
   6331   if (!EvaluateIntegerOrLValue(E, Val, Info))
   6332     return false;
   6333   if (!Val.isInt()) {
   6334     // FIXME: It would be better to produce the diagnostic for casting
   6335     //        a pointer to an integer.
   6336     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   6337     return false;
   6338   }
   6339   Result = Val.getInt();
   6340   return true;
   6341 }
   6342 
   6343 /// Check whether the given declaration can be directly converted to an integral
   6344 /// rvalue. If not, no diagnostic is produced; there are other things we can
   6345 /// try.
   6346 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
   6347   // Enums are integer constant exprs.
   6348   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
   6349     // Check for signedness/width mismatches between E type and ECD value.
   6350     bool SameSign = (ECD->getInitVal().isSigned()
   6351                      == E->getType()->isSignedIntegerOrEnumerationType());
   6352     bool SameWidth = (ECD->getInitVal().getBitWidth()
   6353                       == Info.Ctx.getIntWidth(E->getType()));
   6354     if (SameSign && SameWidth)
   6355       return Success(ECD->getInitVal(), E);
   6356     else {
   6357       // Get rid of mismatch (otherwise Success assertions will fail)
   6358       // by computing a new value matching the type of E.
   6359       llvm::APSInt Val = ECD->getInitVal();
   6360       if (!SameSign)
   6361         Val.setIsSigned(!ECD->getInitVal().isSigned());
   6362       if (!SameWidth)
   6363         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
   6364       return Success(Val, E);
   6365     }
   6366   }
   6367   return false;
   6368 }
   6369 
   6370 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
   6371 /// as GCC.
   6372 static int EvaluateBuiltinClassifyType(const CallExpr *E,
   6373                                        const LangOptions &LangOpts) {
   6374   // The following enum mimics the values returned by GCC.
   6375   // FIXME: Does GCC differ between lvalue and rvalue references here?
   6376   enum gcc_type_class {
   6377     no_type_class = -1,
   6378     void_type_class, integer_type_class, char_type_class,
   6379     enumeral_type_class, boolean_type_class,
   6380     pointer_type_class, reference_type_class, offset_type_class,
   6381     real_type_class, complex_type_class,
   6382     function_type_class, method_type_class,
   6383     record_type_class, union_type_class,
   6384     array_type_class, string_type_class,
   6385     lang_type_class
   6386   };
   6387 
   6388   // If no argument was supplied, default to "no_type_class". This isn't
   6389   // ideal, however it is what gcc does.
   6390   if (E->getNumArgs() == 0)
   6391     return no_type_class;
   6392 
   6393   QualType CanTy = E->getArg(0)->getType().getCanonicalType();
   6394   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
   6395 
   6396   switch (CanTy->getTypeClass()) {
   6397 #define TYPE(ID, BASE)
   6398 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
   6399 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
   6400 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
   6401 #include "clang/AST/TypeNodes.def"
   6402       llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
   6403 
   6404   case Type::Builtin:
   6405     switch (BT->getKind()) {
   6406 #define BUILTIN_TYPE(ID, SINGLETON_ID)
   6407 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
   6408 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
   6409 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
   6410 #include "clang/AST/BuiltinTypes.def"
   6411     case BuiltinType::Void:
   6412       return void_type_class;
   6413 
   6414     case BuiltinType::Bool:
   6415       return boolean_type_class;
   6416 
   6417     case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
   6418     case BuiltinType::UChar:
   6419     case BuiltinType::UShort:
   6420     case BuiltinType::UInt:
   6421     case BuiltinType::ULong:
   6422     case BuiltinType::ULongLong:
   6423     case BuiltinType::UInt128:
   6424       return integer_type_class;
   6425 
   6426     case BuiltinType::NullPtr:
   6427       return pointer_type_class;
   6428 
   6429     case BuiltinType::WChar_U:
   6430     case BuiltinType::Char16:
   6431     case BuiltinType::Char32:
   6432     case BuiltinType::ObjCId:
   6433     case BuiltinType::ObjCClass:
   6434     case BuiltinType::ObjCSel:
   6435 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
   6436     case BuiltinType::Id:
   6437 #include "clang/Basic/OpenCLImageTypes.def"
   6438     case BuiltinType::OCLSampler:
   6439     case BuiltinType::OCLEvent:
   6440     case BuiltinType::OCLClkEvent:
   6441     case BuiltinType::OCLQueue:
   6442     case BuiltinType::OCLNDRange:
   6443     case BuiltinType::OCLReserveID:
   6444     case BuiltinType::Dependent:
   6445       llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
   6446     };
   6447 
   6448   case Type::Enum:
   6449     return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
   6450     break;
   6451 
   6452   case Type::Pointer:
   6453     return pointer_type_class;
   6454     break;
   6455 
   6456   case Type::MemberPointer:
   6457     if (CanTy->isMemberDataPointerType())
   6458       return offset_type_class;
   6459     else {
   6460       // We expect member pointers to be either data or function pointers,
   6461       // nothing else.
   6462       assert(CanTy->isMemberFunctionPointerType());
   6463       return method_type_class;
   6464     }
   6465 
   6466   case Type::Complex:
   6467     return complex_type_class;
   6468 
   6469   case Type::FunctionNoProto:
   6470   case Type::FunctionProto:
   6471     return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
   6472 
   6473   case Type::Record:
   6474     if (const RecordType *RT = CanTy->getAs<RecordType>()) {
   6475       switch (RT->getDecl()->getTagKind()) {
   6476       case TagTypeKind::TTK_Struct:
   6477       case TagTypeKind::TTK_Class:
   6478       case TagTypeKind::TTK_Interface:
   6479         return record_type_class;
   6480 
   6481       case TagTypeKind::TTK_Enum:
   6482         return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
   6483 
   6484       case TagTypeKind::TTK_Union:
   6485         return union_type_class;
   6486       }
   6487     }
   6488     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
   6489 
   6490   case Type::ConstantArray:
   6491   case Type::VariableArray:
   6492   case Type::IncompleteArray:
   6493     return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
   6494 
   6495   case Type::BlockPointer:
   6496   case Type::LValueReference:
   6497   case Type::RValueReference:
   6498   case Type::Vector:
   6499   case Type::ExtVector:
   6500   case Type::Auto:
   6501   case Type::ObjCObject:
   6502   case Type::ObjCInterface:
   6503   case Type::ObjCObjectPointer:
   6504   case Type::Pipe:
   6505   case Type::Atomic:
   6506     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
   6507   }
   6508 
   6509   llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
   6510 }
   6511 
   6512 /// EvaluateBuiltinConstantPForLValue - Determine the result of
   6513 /// __builtin_constant_p when applied to the given lvalue.
   6514 ///
   6515 /// An lvalue is only "constant" if it is a pointer or reference to the first
   6516 /// character of a string literal.
   6517 template<typename LValue>
   6518 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
   6519   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
   6520   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
   6521 }
   6522 
   6523 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
   6524 /// GCC as we can manage.
   6525 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
   6526   QualType ArgType = Arg->getType();
   6527 
   6528   // __builtin_constant_p always has one operand. The rules which gcc follows
   6529   // are not precisely documented, but are as follows:
   6530   //
   6531   //  - If the operand is of integral, floating, complex or enumeration type,
   6532   //    and can be folded to a known value of that type, it returns 1.
   6533   //  - If the operand and can be folded to a pointer to the first character
   6534   //    of a string literal (or such a pointer cast to an integral type), it
   6535   //    returns 1.
   6536   //
   6537   // Otherwise, it returns 0.
   6538   //
   6539   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
   6540   // its support for this does not currently work.
   6541   if (ArgType->isIntegralOrEnumerationType()) {
   6542     Expr::EvalResult Result;
   6543     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
   6544       return false;
   6545 
   6546     APValue &V = Result.Val;
   6547     if (V.getKind() == APValue::Int)
   6548       return true;
   6549     if (V.getKind() == APValue::LValue)
   6550       return EvaluateBuiltinConstantPForLValue(V);
   6551   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
   6552     return Arg->isEvaluatable(Ctx);
   6553   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
   6554     LValue LV;
   6555     Expr::EvalStatus Status;
   6556     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
   6557     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
   6558                           : EvaluatePointer(Arg, LV, Info)) &&
   6559         !Status.HasSideEffects)
   6560       return EvaluateBuiltinConstantPForLValue(LV);
   6561   }
   6562 
   6563   // Anything else isn't considered to be sufficiently constant.
   6564   return false;
   6565 }
   6566 
   6567 /// Retrieves the "underlying object type" of the given expression,
   6568 /// as used by __builtin_object_size.
   6569 static QualType getObjectType(APValue::LValueBase B) {
   6570   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
   6571     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
   6572       return VD->getType();
   6573   } else if (const Expr *E = B.get<const Expr*>()) {
   6574     if (isa<CompoundLiteralExpr>(E))
   6575       return E->getType();
   6576   }
   6577 
   6578   return QualType();
   6579 }
   6580 
   6581 /// A more selective version of E->IgnoreParenCasts for
   6582 /// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
   6583 /// to change the type of E.
   6584 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
   6585 ///
   6586 /// Always returns an RValue with a pointer representation.
   6587 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
   6588   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
   6589 
   6590   auto *NoParens = E->IgnoreParens();
   6591   auto *Cast = dyn_cast<CastExpr>(NoParens);
   6592   if (Cast == nullptr)
   6593     return NoParens;
   6594 
   6595   // We only conservatively allow a few kinds of casts, because this code is
   6596   // inherently a simple solution that seeks to support the common case.
   6597   auto CastKind = Cast->getCastKind();
   6598   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
   6599       CastKind != CK_AddressSpaceConversion)
   6600     return NoParens;
   6601 
   6602   auto *SubExpr = Cast->getSubExpr();
   6603   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
   6604     return NoParens;
   6605   return ignorePointerCastsAndParens(SubExpr);
   6606 }
   6607 
   6608 /// Checks to see if the given LValue's Designator is at the end of the LValue's
   6609 /// record layout. e.g.
   6610 ///   struct { struct { int a, b; } fst, snd; } obj;
   6611 ///   obj.fst   // no
   6612 ///   obj.snd   // yes
   6613 ///   obj.fst.a // no
   6614 ///   obj.fst.b // no
   6615 ///   obj.snd.a // no
   6616 ///   obj.snd.b // yes
   6617 ///
   6618 /// Please note: this function is specialized for how __builtin_object_size
   6619 /// views "objects".
   6620 ///
   6621 /// If this encounters an invalid RecordDecl, it will always return true.
   6622 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
   6623   assert(!LVal.Designator.Invalid);
   6624 
   6625   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
   6626     const RecordDecl *Parent = FD->getParent();
   6627     Invalid = Parent->isInvalidDecl();
   6628     if (Invalid || Parent->isUnion())
   6629       return true;
   6630     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
   6631     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
   6632   };
   6633 
   6634   auto &Base = LVal.getLValueBase();
   6635   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
   6636     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
   6637       bool Invalid;
   6638       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
   6639         return Invalid;
   6640     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
   6641       for (auto *FD : IFD->chain()) {
   6642         bool Invalid;
   6643         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
   6644           return Invalid;
   6645       }
   6646     }
   6647   }
   6648 
   6649   QualType BaseType = getType(Base);
   6650   for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
   6651     if (BaseType->isArrayType()) {
   6652       // Because __builtin_object_size treats arrays as objects, we can ignore
   6653       // the index iff this is the last array in the Designator.
   6654       if (I + 1 == E)
   6655         return true;
   6656       auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
   6657       uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
   6658       if (Index + 1 != CAT->getSize())
   6659         return false;
   6660       BaseType = CAT->getElementType();
   6661     } else if (BaseType->isAnyComplexType()) {
   6662       auto *CT = BaseType->castAs<ComplexType>();
   6663       uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
   6664       if (Index != 1)
   6665         return false;
   6666       BaseType = CT->getElementType();
   6667     } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
   6668       bool Invalid;
   6669       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
   6670         return Invalid;
   6671       BaseType = FD->getType();
   6672     } else {
   6673       assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
   6674              "Expecting cast to a base class");
   6675       return false;
   6676     }
   6677   }
   6678   return true;
   6679 }
   6680 
   6681 /// Tests to see if the LValue has a designator (that isn't necessarily valid).
   6682 static bool refersToCompleteObject(const LValue &LVal) {
   6683   if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
   6684     return false;
   6685 
   6686   if (!LVal.InvalidBase)
   6687     return true;
   6688 
   6689   auto *E = LVal.Base.dyn_cast<const Expr *>();
   6690   (void)E;
   6691   assert(E != nullptr && isa<MemberExpr>(E));
   6692   return false;
   6693 }
   6694 
   6695 /// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
   6696 /// true and stores the result in @p Size.
   6697 ///
   6698 /// If @p WasError is non-null, this will report whether the failure to evaluate
   6699 /// is to be treated as an Error in IntExprEvaluator.
   6700 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
   6701                                          EvalInfo &Info, uint64_t &Size,
   6702                                          bool *WasError = nullptr) {
   6703   if (WasError != nullptr)
   6704     *WasError = false;
   6705 
   6706   auto Error = [&](const Expr *E) {
   6707     if (WasError != nullptr)
   6708       *WasError = true;
   6709     return false;
   6710   };
   6711 
   6712   auto Success = [&](uint64_t S, const Expr *E) {
   6713     Size = S;
   6714     return true;
   6715   };
   6716 
   6717   // Determine the denoted object.
   6718   LValue Base;
   6719   {
   6720     // The operand of __builtin_object_size is never evaluated for side-effects.
   6721     // If there are any, but we can determine the pointed-to object anyway, then
   6722     // ignore the side-effects.
   6723     SpeculativeEvaluationRAII SpeculativeEval(Info);
   6724     FoldOffsetRAII Fold(Info, Type & 1);
   6725 
   6726     if (E->isGLValue()) {
   6727       // It's possible for us to be given GLValues if we're called via
   6728       // Expr::tryEvaluateObjectSize.
   6729       APValue RVal;
   6730       if (!EvaluateAsRValue(Info, E, RVal))
   6731         return false;
   6732       Base.setFrom(Info.Ctx, RVal);
   6733     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
   6734       return false;
   6735   }
   6736 
   6737   CharUnits BaseOffset = Base.getLValueOffset();
   6738   // If we point to before the start of the object, there are no accessible
   6739   // bytes.
   6740   if (BaseOffset.isNegative())
   6741     return Success(0, E);
   6742 
   6743   // In the case where we're not dealing with a subobject, we discard the
   6744   // subobject bit.
   6745   bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
   6746 
   6747   // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
   6748   // exist. If we can't verify the base, then we can't do that.
   6749   //
   6750   // As a special case, we produce a valid object size for an unknown object
   6751   // with a known designator if Type & 1 is 1. For instance:
   6752   //
   6753   //   extern struct X { char buff[32]; int a, b, c; } *p;
   6754   //   int a = __builtin_object_size(p->buff + 4, 3); // returns 28
   6755   //   int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
   6756   //
   6757   // This matches GCC's behavior.
   6758   if (Base.InvalidBase && !SubobjectOnly)
   6759     return Error(E);
   6760 
   6761   // If we're not examining only the subobject, then we reset to a complete
   6762   // object designator
   6763   //
   6764   // If Type is 1 and we've lost track of the subobject, just find the complete
   6765   // object instead. (If Type is 3, that's not correct behavior and we should
   6766   // return 0 instead.)
   6767   LValue End = Base;
   6768   if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
   6769     QualType T = getObjectType(End.getLValueBase());
   6770     if (T.isNull())
   6771       End.Designator.setInvalid();
   6772     else {
   6773       End.Designator = SubobjectDesignator(T);
   6774       End.Offset = CharUnits::Zero();
   6775     }
   6776   }
   6777 
   6778   // If it is not possible to determine which objects ptr points to at compile
   6779   // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
   6780   // and (size_t) 0 for type 2 or 3.
   6781   if (End.Designator.Invalid)
   6782     return false;
   6783 
   6784   // According to the GCC documentation, we want the size of the subobject
   6785   // denoted by the pointer. But that's not quite right -- what we actually
   6786   // want is the size of the immediately-enclosing array, if there is one.
   6787   int64_t AmountToAdd = 1;
   6788   if (End.Designator.MostDerivedIsArrayElement &&
   6789       End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
   6790     // We got a pointer to an array. Step to its end.
   6791     AmountToAdd = End.Designator.MostDerivedArraySize -
   6792                   End.Designator.Entries.back().ArrayIndex;
   6793   } else if (End.Designator.isOnePastTheEnd()) {
   6794     // We're already pointing at the end of the object.
   6795     AmountToAdd = 0;
   6796   }
   6797 
   6798   QualType PointeeType = End.Designator.MostDerivedType;
   6799   assert(!PointeeType.isNull());
   6800   if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
   6801     return Error(E);
   6802 
   6803   if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
   6804                                    AmountToAdd))
   6805     return false;
   6806 
   6807   auto EndOffset = End.getLValueOffset();
   6808 
   6809   // The following is a moderately common idiom in C:
   6810   //
   6811   // struct Foo { int a; char c[1]; };
   6812   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
   6813   // strcpy(&F->c[0], Bar);
   6814   //
   6815   // So, if we see that we're examining a 1-length (or 0-length) array at the
   6816   // end of a struct with an unknown base, we give up instead of breaking code
   6817   // that behaves this way. Note that we only do this when Type=1, because
   6818   // Type=3 is a lower bound, so answering conservatively is fine.
   6819   if (End.InvalidBase && SubobjectOnly && Type == 1 &&
   6820       End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
   6821       End.Designator.MostDerivedIsArrayElement &&
   6822       End.Designator.MostDerivedArraySize < 2 &&
   6823       isDesignatorAtObjectEnd(Info.Ctx, End))
   6824     return false;
   6825 
   6826   if (BaseOffset > EndOffset)
   6827     return Success(0, E);
   6828 
   6829   return Success((EndOffset - BaseOffset).getQuantity(), E);
   6830 }
   6831 
   6832 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
   6833                                                     unsigned Type) {
   6834   uint64_t Size;
   6835   bool WasError;
   6836   if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
   6837     return Success(Size, E);
   6838   if (WasError)
   6839     return Error(E);
   6840   return false;
   6841 }
   6842 
   6843 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
   6844   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
   6845   default:
   6846     return ExprEvaluatorBaseTy::VisitCallExpr(E);
   6847 
   6848   case Builtin::BI__builtin_object_size: {
   6849     // The type was checked when we built the expression.
   6850     unsigned Type =
   6851         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
   6852     assert(Type <= 3 && "unexpected type");
   6853 
   6854     if (TryEvaluateBuiltinObjectSize(E, Type))
   6855       return true;
   6856 
   6857     if (E->getArg(0)->HasSideEffects(Info.Ctx))
   6858       return Success((Type & 2) ? 0 : -1, E);
   6859 
   6860     // Expression had no side effects, but we couldn't statically determine the
   6861     // size of the referenced object.
   6862     switch (Info.EvalMode) {
   6863     case EvalInfo::EM_ConstantExpression:
   6864     case EvalInfo::EM_PotentialConstantExpression:
   6865     case EvalInfo::EM_ConstantFold:
   6866     case EvalInfo::EM_EvaluateForOverflow:
   6867     case EvalInfo::EM_IgnoreSideEffects:
   6868     case EvalInfo::EM_DesignatorFold:
   6869       // Leave it to IR generation.
   6870       return Error(E);
   6871     case EvalInfo::EM_ConstantExpressionUnevaluated:
   6872     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
   6873       // Reduce it to a constant now.
   6874       return Success((Type & 2) ? 0 : -1, E);
   6875     }
   6876   }
   6877 
   6878   case Builtin::BI__builtin_bswap16:
   6879   case Builtin::BI__builtin_bswap32:
   6880   case Builtin::BI__builtin_bswap64: {
   6881     APSInt Val;
   6882     if (!EvaluateInteger(E->getArg(0), Val, Info))
   6883       return false;
   6884 
   6885     return Success(Val.byteSwap(), E);
   6886   }
   6887 
   6888   case Builtin::BI__builtin_classify_type:
   6889     return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
   6890 
   6891   // FIXME: BI__builtin_clrsb
   6892   // FIXME: BI__builtin_clrsbl
   6893   // FIXME: BI__builtin_clrsbll
   6894 
   6895   case Builtin::BI__builtin_clz:
   6896   case Builtin::BI__builtin_clzl:
   6897   case Builtin::BI__builtin_clzll:
   6898   case Builtin::BI__builtin_clzs: {
   6899     APSInt Val;
   6900     if (!EvaluateInteger(E->getArg(0), Val, Info))
   6901       return false;
   6902     if (!Val)
   6903       return Error(E);
   6904 
   6905     return Success(Val.countLeadingZeros(), E);
   6906   }
   6907 
   6908   case Builtin::BI__builtin_constant_p:
   6909     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
   6910 
   6911   case Builtin::BI__builtin_ctz:
   6912   case Builtin::BI__builtin_ctzl:
   6913   case Builtin::BI__builtin_ctzll:
   6914   case Builtin::BI__builtin_ctzs: {
   6915     APSInt Val;
   6916     if (!EvaluateInteger(E->getArg(0), Val, Info))
   6917       return false;
   6918     if (!Val)
   6919       return Error(E);
   6920 
   6921     return Success(Val.countTrailingZeros(), E);
   6922   }
   6923 
   6924   case Builtin::BI__builtin_eh_return_data_regno: {
   6925     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
   6926     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
   6927     return Success(Operand, E);
   6928   }
   6929 
   6930   case Builtin::BI__builtin_expect:
   6931     return Visit(E->getArg(0));
   6932 
   6933   case Builtin::BI__builtin_ffs:
   6934   case Builtin::BI__builtin_ffsl:
   6935   case Builtin::BI__builtin_ffsll: {
   6936     APSInt Val;
   6937     if (!EvaluateInteger(E->getArg(0), Val, Info))
   6938       return false;
   6939 
   6940     unsigned N = Val.countTrailingZeros();
   6941     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
   6942   }
   6943 
   6944   case Builtin::BI__builtin_fpclassify: {
   6945     APFloat Val(0.0);
   6946     if (!EvaluateFloat(E->getArg(5), Val, Info))
   6947       return false;
   6948     unsigned Arg;
   6949     switch (Val.getCategory()) {
   6950     case APFloat::fcNaN: Arg = 0; break;
   6951     case APFloat::fcInfinity: Arg = 1; break;
   6952     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
   6953     case APFloat::fcZero: Arg = 4; break;
   6954     }
   6955     return Visit(E->getArg(Arg));
   6956   }
   6957 
   6958   case Builtin::BI__builtin_isinf_sign: {
   6959     APFloat Val(0.0);
   6960     return EvaluateFloat(E->getArg(0), Val, Info) &&
   6961            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
   6962   }
   6963 
   6964   case Builtin::BI__builtin_isinf: {
   6965     APFloat Val(0.0);
   6966     return EvaluateFloat(E->getArg(0), Val, Info) &&
   6967            Success(Val.isInfinity() ? 1 : 0, E);
   6968   }
   6969 
   6970   case Builtin::BI__builtin_isfinite: {
   6971     APFloat Val(0.0);
   6972     return EvaluateFloat(E->getArg(0), Val, Info) &&
   6973            Success(Val.isFinite() ? 1 : 0, E);
   6974   }
   6975 
   6976   case Builtin::BI__builtin_isnan: {
   6977     APFloat Val(0.0);
   6978     return EvaluateFloat(E->getArg(0), Val, Info) &&
   6979            Success(Val.isNaN() ? 1 : 0, E);
   6980   }
   6981 
   6982   case Builtin::BI__builtin_isnormal: {
   6983     APFloat Val(0.0);
   6984     return EvaluateFloat(E->getArg(0), Val, Info) &&
   6985            Success(Val.isNormal() ? 1 : 0, E);
   6986   }
   6987 
   6988   case Builtin::BI__builtin_parity:
   6989   case Builtin::BI__builtin_parityl:
   6990   case Builtin::BI__builtin_parityll: {
   6991     APSInt Val;
   6992     if (!EvaluateInteger(E->getArg(0), Val, Info))
   6993       return false;
   6994 
   6995     return Success(Val.countPopulation() % 2, E);
   6996   }
   6997 
   6998   case Builtin::BI__builtin_popcount:
   6999   case Builtin::BI__builtin_popcountl:
   7000   case Builtin::BI__builtin_popcountll: {
   7001     APSInt Val;
   7002     if (!EvaluateInteger(E->getArg(0), Val, Info))
   7003       return false;
   7004 
   7005     return Success(Val.countPopulation(), E);
   7006   }
   7007 
   7008   case Builtin::BIstrlen:
   7009     // A call to strlen is not a constant expression.
   7010     if (Info.getLangOpts().CPlusPlus11)
   7011       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
   7012         << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
   7013     else
   7014       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
   7015     // Fall through.
   7016   case Builtin::BI__builtin_strlen: {
   7017     // As an extension, we support __builtin_strlen() as a constant expression,
   7018     // and support folding strlen() to a constant.
   7019     LValue String;
   7020     if (!EvaluatePointer(E->getArg(0), String, Info))
   7021       return false;
   7022 
   7023     // Fast path: if it's a string literal, search the string value.
   7024     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
   7025             String.getLValueBase().dyn_cast<const Expr *>())) {
   7026       // The string literal may have embedded null characters. Find the first
   7027       // one and truncate there.
   7028       StringRef Str = S->getBytes();
   7029       int64_t Off = String.Offset.getQuantity();
   7030       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
   7031           S->getCharByteWidth() == 1) {
   7032         Str = Str.substr(Off);
   7033 
   7034         StringRef::size_type Pos = Str.find(0);
   7035         if (Pos != StringRef::npos)
   7036           Str = Str.substr(0, Pos);
   7037 
   7038         return Success(Str.size(), E);
   7039       }
   7040 
   7041       // Fall through to slow path to issue appropriate diagnostic.
   7042     }
   7043 
   7044     // Slow path: scan the bytes of the string looking for the terminating 0.
   7045     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
   7046     for (uint64_t Strlen = 0; /**/; ++Strlen) {
   7047       APValue Char;
   7048       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
   7049           !Char.isInt())
   7050         return false;
   7051       if (!Char.getInt())
   7052         return Success(Strlen, E);
   7053       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
   7054         return false;
   7055     }
   7056   }
   7057 
   7058   case Builtin::BI__atomic_always_lock_free:
   7059   case Builtin::BI__atomic_is_lock_free:
   7060   case Builtin::BI__c11_atomic_is_lock_free: {
   7061     APSInt SizeVal;
   7062     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
   7063       return false;
   7064 
   7065     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
   7066     // of two less than the maximum inline atomic width, we know it is
   7067     // lock-free.  If the size isn't a power of two, or greater than the
   7068     // maximum alignment where we promote atomics, we know it is not lock-free
   7069     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
   7070     // the answer can only be determined at runtime; for example, 16-byte
   7071     // atomics have lock-free implementations on some, but not all,
   7072     // x86-64 processors.
   7073 
   7074     // Check power-of-two.
   7075     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
   7076     if (Size.isPowerOfTwo()) {
   7077       // Check against inlining width.
   7078       unsigned InlineWidthBits =
   7079           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
   7080       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
   7081         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
   7082             Size == CharUnits::One() ||
   7083             E->getArg(1)->isNullPointerConstant(Info.Ctx,
   7084                                                 Expr::NPC_NeverValueDependent))
   7085           // OK, we will inline appropriately-aligned operations of this size,
   7086           // and _Atomic(T) is appropriately-aligned.
   7087           return Success(1, E);
   7088 
   7089         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
   7090           castAs<PointerType>()->getPointeeType();
   7091         if (!PointeeType->isIncompleteType() &&
   7092             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
   7093           // OK, we will inline operations on this object.
   7094           return Success(1, E);
   7095         }
   7096       }
   7097     }
   7098 
   7099     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
   7100         Success(0, E) : Error(E);
   7101   }
   7102   }
   7103 }
   7104 
   7105 static bool HasSameBase(const LValue &A, const LValue &B) {
   7106   if (!A.getLValueBase())
   7107     return !B.getLValueBase();
   7108   if (!B.getLValueBase())
   7109     return false;
   7110 
   7111   if (A.getLValueBase().getOpaqueValue() !=
   7112       B.getLValueBase().getOpaqueValue()) {
   7113     const Decl *ADecl = GetLValueBaseDecl(A);
   7114     if (!ADecl)
   7115       return false;
   7116     const Decl *BDecl = GetLValueBaseDecl(B);
   7117     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
   7118       return false;
   7119   }
   7120 
   7121   return IsGlobalLValue(A.getLValueBase()) ||
   7122          A.getLValueCallIndex() == B.getLValueCallIndex();
   7123 }
   7124 
   7125 /// \brief Determine whether this is a pointer past the end of the complete
   7126 /// object referred to by the lvalue.
   7127 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
   7128                                             const LValue &LV) {
   7129   // A null pointer can be viewed as being "past the end" but we don't
   7130   // choose to look at it that way here.
   7131   if (!LV.getLValueBase())
   7132     return false;
   7133 
   7134   // If the designator is valid and refers to a subobject, we're not pointing
   7135   // past the end.
   7136   if (!LV.getLValueDesignator().Invalid &&
   7137       !LV.getLValueDesignator().isOnePastTheEnd())
   7138     return false;
   7139 
   7140   // A pointer to an incomplete type might be past-the-end if the type's size is
   7141   // zero.  We cannot tell because the type is incomplete.
   7142   QualType Ty = getType(LV.getLValueBase());
   7143   if (Ty->isIncompleteType())
   7144     return true;
   7145 
   7146   // We're a past-the-end pointer if we point to the byte after the object,
   7147   // no matter what our type or path is.
   7148   auto Size = Ctx.getTypeSizeInChars(Ty);
   7149   return LV.getLValueOffset() == Size;
   7150 }
   7151 
   7152 namespace {
   7153 
   7154 /// \brief Data recursive integer evaluator of certain binary operators.
   7155 ///
   7156 /// We use a data recursive algorithm for binary operators so that we are able
   7157 /// to handle extreme cases of chained binary operators without causing stack
   7158 /// overflow.
   7159 class DataRecursiveIntBinOpEvaluator {
   7160   struct EvalResult {
   7161     APValue Val;
   7162     bool Failed;
   7163 
   7164     EvalResult() : Failed(false) { }
   7165 
   7166     void swap(EvalResult &RHS) {
   7167       Val.swap(RHS.Val);
   7168       Failed = RHS.Failed;
   7169       RHS.Failed = false;
   7170     }
   7171   };
   7172 
   7173   struct Job {
   7174     const Expr *E;
   7175     EvalResult LHSResult; // meaningful only for binary operator expression.
   7176     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
   7177 
   7178     Job() = default;
   7179     Job(Job &&J)
   7180         : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
   7181           SpecEvalRAII(std::move(J.SpecEvalRAII)) {}
   7182 
   7183     void startSpeculativeEval(EvalInfo &Info) {
   7184       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
   7185     }
   7186 
   7187   private:
   7188     SpeculativeEvaluationRAII SpecEvalRAII;
   7189   };
   7190 
   7191   SmallVector<Job, 16> Queue;
   7192 
   7193   IntExprEvaluator &IntEval;
   7194   EvalInfo &Info;
   7195   APValue &FinalResult;
   7196 
   7197 public:
   7198   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
   7199     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
   7200 
   7201   /// \brief True if \param E is a binary operator that we are going to handle
   7202   /// data recursively.
   7203   /// We handle binary operators that are comma, logical, or that have operands
   7204   /// with integral or enumeration type.
   7205   static bool shouldEnqueue(const BinaryOperator *E) {
   7206     return E->getOpcode() == BO_Comma ||
   7207            E->isLogicalOp() ||
   7208            (E->isRValue() &&
   7209             E->getType()->isIntegralOrEnumerationType() &&
   7210             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
   7211             E->getRHS()->getType()->isIntegralOrEnumerationType());
   7212   }
   7213 
   7214   bool Traverse(const BinaryOperator *E) {
   7215     enqueue(E);
   7216     EvalResult PrevResult;
   7217     while (!Queue.empty())
   7218       process(PrevResult);
   7219 
   7220     if (PrevResult.Failed) return false;
   7221 
   7222     FinalResult.swap(PrevResult.Val);
   7223     return true;
   7224   }
   7225 
   7226 private:
   7227   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
   7228     return IntEval.Success(Value, E, Result);
   7229   }
   7230   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
   7231     return IntEval.Success(Value, E, Result);
   7232   }
   7233   bool Error(const Expr *E) {
   7234     return IntEval.Error(E);
   7235   }
   7236   bool Error(const Expr *E, diag::kind D) {
   7237     return IntEval.Error(E, D);
   7238   }
   7239 
   7240   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
   7241     return Info.CCEDiag(E, D);
   7242   }
   7243 
   7244   // \brief Returns true if visiting the RHS is necessary, false otherwise.
   7245   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
   7246                          bool &SuppressRHSDiags);
   7247 
   7248   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
   7249                   const BinaryOperator *E, APValue &Result);
   7250 
   7251   void EvaluateExpr(const Expr *E, EvalResult &Result) {
   7252     Result.Failed = !Evaluate(Result.Val, Info, E);
   7253     if (Result.Failed)
   7254       Result.Val = APValue();
   7255   }
   7256 
   7257   void process(EvalResult &Result);
   7258 
   7259   void enqueue(const Expr *E) {
   7260     E = E->IgnoreParens();
   7261     Queue.resize(Queue.size()+1);
   7262     Queue.back().E = E;
   7263     Queue.back().Kind = Job::AnyExprKind;
   7264   }
   7265 };
   7266 
   7267 }
   7268 
   7269 bool DataRecursiveIntBinOpEvaluator::
   7270        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
   7271                          bool &SuppressRHSDiags) {
   7272   if (E->getOpcode() == BO_Comma) {
   7273     // Ignore LHS but note if we could not evaluate it.
   7274     if (LHSResult.Failed)
   7275       return Info.noteSideEffect();
   7276     return true;
   7277   }
   7278 
   7279   if (E->isLogicalOp()) {
   7280     bool LHSAsBool;
   7281     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
   7282       // We were able to evaluate the LHS, see if we can get away with not
   7283       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
   7284       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
   7285         Success(LHSAsBool, E, LHSResult.Val);
   7286         return false; // Ignore RHS
   7287       }
   7288     } else {
   7289       LHSResult.Failed = true;
   7290 
   7291       // Since we weren't able to evaluate the left hand side, it
   7292       // might have had side effects.
   7293       if (!Info.noteSideEffect())
   7294         return false;
   7295 
   7296       // We can't evaluate the LHS; however, sometimes the result
   7297       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
   7298       // Don't ignore RHS and suppress diagnostics from this arm.
   7299       SuppressRHSDiags = true;
   7300     }
   7301 
   7302     return true;
   7303   }
   7304 
   7305   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
   7306          E->getRHS()->getType()->isIntegralOrEnumerationType());
   7307 
   7308   if (LHSResult.Failed && !Info.noteFailure())
   7309     return false; // Ignore RHS;
   7310 
   7311   return true;
   7312 }
   7313 
   7314 bool DataRecursiveIntBinOpEvaluator::
   7315        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
   7316                   const BinaryOperator *E, APValue &Result) {
   7317   if (E->getOpcode() == BO_Comma) {
   7318     if (RHSResult.Failed)
   7319       return false;
   7320     Result = RHSResult.Val;
   7321     return true;
   7322   }
   7323 
   7324   if (E->isLogicalOp()) {
   7325     bool lhsResult, rhsResult;
   7326     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
   7327     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
   7328 
   7329     if (LHSIsOK) {
   7330       if (RHSIsOK) {
   7331         if (E->getOpcode() == BO_LOr)
   7332           return Success(lhsResult || rhsResult, E, Result);
   7333         else
   7334           return Success(lhsResult && rhsResult, E, Result);
   7335       }
   7336     } else {
   7337       if (RHSIsOK) {
   7338         // We can't evaluate the LHS; however, sometimes the result
   7339         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
   7340         if (rhsResult == (E->getOpcode() == BO_LOr))
   7341           return Success(rhsResult, E, Result);
   7342       }
   7343     }
   7344 
   7345     return false;
   7346   }
   7347 
   7348   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
   7349          E->getRHS()->getType()->isIntegralOrEnumerationType());
   7350 
   7351   if (LHSResult.Failed || RHSResult.Failed)
   7352     return false;
   7353 
   7354   const APValue &LHSVal = LHSResult.Val;
   7355   const APValue &RHSVal = RHSResult.Val;
   7356 
   7357   // Handle cases like (unsigned long)&a + 4.
   7358   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
   7359     Result = LHSVal;
   7360     CharUnits AdditionalOffset =
   7361         CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
   7362     if (E->getOpcode() == BO_Add)
   7363       Result.getLValueOffset() += AdditionalOffset;
   7364     else
   7365       Result.getLValueOffset() -= AdditionalOffset;
   7366     return true;
   7367   }
   7368 
   7369   // Handle cases like 4 + (unsigned long)&a
   7370   if (E->getOpcode() == BO_Add &&
   7371       RHSVal.isLValue() && LHSVal.isInt()) {
   7372     Result = RHSVal;
   7373     Result.getLValueOffset() +=
   7374         CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
   7375     return true;
   7376   }
   7377 
   7378   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
   7379     // Handle (intptr_t)&&A - (intptr_t)&&B.
   7380     if (!LHSVal.getLValueOffset().isZero() ||
   7381         !RHSVal.getLValueOffset().isZero())
   7382       return false;
   7383     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
   7384     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
   7385     if (!LHSExpr || !RHSExpr)
   7386       return false;
   7387     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
   7388     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
   7389     if (!LHSAddrExpr || !RHSAddrExpr)
   7390       return false;
   7391     // Make sure both labels come from the same function.
   7392     if (LHSAddrExpr->getLabel()->getDeclContext() !=
   7393         RHSAddrExpr->getLabel()->getDeclContext())
   7394       return false;
   7395     Result = APValue(LHSAddrExpr, RHSAddrExpr);
   7396     return true;
   7397   }
   7398 
   7399   // All the remaining cases expect both operands to be an integer
   7400   if (!LHSVal.isInt() || !RHSVal.isInt())
   7401     return Error(E);
   7402 
   7403   // Set up the width and signedness manually, in case it can't be deduced
   7404   // from the operation we're performing.
   7405   // FIXME: Don't do this in the cases where we can deduce it.
   7406   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
   7407                E->getType()->isUnsignedIntegerOrEnumerationType());
   7408   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
   7409                          RHSVal.getInt(), Value))
   7410     return false;
   7411   return Success(Value, E, Result);
   7412 }
   7413 
   7414 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
   7415   Job &job = Queue.back();
   7416 
   7417   switch (job.Kind) {
   7418     case Job::AnyExprKind: {
   7419       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
   7420         if (shouldEnqueue(Bop)) {
   7421           job.Kind = Job::BinOpKind;
   7422           enqueue(Bop->getLHS());
   7423           return;
   7424         }
   7425       }
   7426 
   7427       EvaluateExpr(job.E, Result);
   7428       Queue.pop_back();
   7429       return;
   7430     }
   7431 
   7432     case Job::BinOpKind: {
   7433       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
   7434       bool SuppressRHSDiags = false;
   7435       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
   7436         Queue.pop_back();
   7437         return;
   7438       }
   7439       if (SuppressRHSDiags)
   7440         job.startSpeculativeEval(Info);
   7441       job.LHSResult.swap(Result);
   7442       job.Kind = Job::BinOpVisitedLHSKind;
   7443       enqueue(Bop->getRHS());
   7444       return;
   7445     }
   7446 
   7447     case Job::BinOpVisitedLHSKind: {
   7448       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
   7449       EvalResult RHS;
   7450       RHS.swap(Result);
   7451       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
   7452       Queue.pop_back();
   7453       return;
   7454     }
   7455   }
   7456 
   7457   llvm_unreachable("Invalid Job::Kind!");
   7458 }
   7459 
   7460 namespace {
   7461 /// Used when we determine that we should fail, but can keep evaluating prior to
   7462 /// noting that we had a failure.
   7463 class DelayedNoteFailureRAII {
   7464   EvalInfo &Info;
   7465   bool NoteFailure;
   7466 
   7467 public:
   7468   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
   7469       : Info(Info), NoteFailure(NoteFailure) {}
   7470   ~DelayedNoteFailureRAII() {
   7471     if (NoteFailure) {
   7472       bool ContinueAfterFailure = Info.noteFailure();
   7473       (void)ContinueAfterFailure;
   7474       assert(ContinueAfterFailure &&
   7475              "Shouldn't have kept evaluating on failure.");
   7476     }
   7477   }
   7478 };
   7479 }
   7480 
   7481 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   7482   // We don't call noteFailure immediately because the assignment happens after
   7483   // we evaluate LHS and RHS.
   7484   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
   7485     return Error(E);
   7486 
   7487   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
   7488   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
   7489     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
   7490 
   7491   QualType LHSTy = E->getLHS()->getType();
   7492   QualType RHSTy = E->getRHS()->getType();
   7493 
   7494   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
   7495     ComplexValue LHS, RHS;
   7496     bool LHSOK;
   7497     if (E->isAssignmentOp()) {
   7498       LValue LV;
   7499       EvaluateLValue(E->getLHS(), LV, Info);
   7500       LHSOK = false;
   7501     } else if (LHSTy->isRealFloatingType()) {
   7502       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
   7503       if (LHSOK) {
   7504         LHS.makeComplexFloat();
   7505         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
   7506       }
   7507     } else {
   7508       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
   7509     }
   7510     if (!LHSOK && !Info.noteFailure())
   7511       return false;
   7512 
   7513     if (E->getRHS()->getType()->isRealFloatingType()) {
   7514       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
   7515         return false;
   7516       RHS.makeComplexFloat();
   7517       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
   7518     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
   7519       return false;
   7520 
   7521     if (LHS.isComplexFloat()) {
   7522       APFloat::cmpResult CR_r =
   7523         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
   7524       APFloat::cmpResult CR_i =
   7525         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
   7526 
   7527       if (E->getOpcode() == BO_EQ)
   7528         return Success((CR_r == APFloat::cmpEqual &&
   7529                         CR_i == APFloat::cmpEqual), E);
   7530       else {
   7531         assert(E->getOpcode() == BO_NE &&
   7532                "Invalid complex comparison.");
   7533         return Success(((CR_r == APFloat::cmpGreaterThan ||
   7534                          CR_r == APFloat::cmpLessThan ||
   7535                          CR_r == APFloat::cmpUnordered) ||
   7536                         (CR_i == APFloat::cmpGreaterThan ||
   7537                          CR_i == APFloat::cmpLessThan ||
   7538                          CR_i == APFloat::cmpUnordered)), E);
   7539       }
   7540     } else {
   7541       if (E->getOpcode() == BO_EQ)
   7542         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
   7543                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
   7544       else {
   7545         assert(E->getOpcode() == BO_NE &&
   7546                "Invalid compex comparison.");
   7547         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
   7548                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
   7549       }
   7550     }
   7551   }
   7552 
   7553   if (LHSTy->isRealFloatingType() &&
   7554       RHSTy->isRealFloatingType()) {
   7555     APFloat RHS(0.0), LHS(0.0);
   7556 
   7557     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
   7558     if (!LHSOK && !Info.noteFailure())
   7559       return false;
   7560 
   7561     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
   7562       return false;
   7563 
   7564     APFloat::cmpResult CR = LHS.compare(RHS);
   7565 
   7566     switch (E->getOpcode()) {
   7567     default:
   7568       llvm_unreachable("Invalid binary operator!");
   7569     case BO_LT:
   7570       return Success(CR == APFloat::cmpLessThan, E);
   7571     case BO_GT:
   7572       return Success(CR == APFloat::cmpGreaterThan, E);
   7573     case BO_LE:
   7574       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
   7575     case BO_GE:
   7576       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
   7577                      E);
   7578     case BO_EQ:
   7579       return Success(CR == APFloat::cmpEqual, E);
   7580     case BO_NE:
   7581       return Success(CR == APFloat::cmpGreaterThan
   7582                      || CR == APFloat::cmpLessThan
   7583                      || CR == APFloat::cmpUnordered, E);
   7584     }
   7585   }
   7586 
   7587   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
   7588     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
   7589       LValue LHSValue, RHSValue;
   7590 
   7591       bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
   7592       if (!LHSOK && !Info.noteFailure())
   7593         return false;
   7594 
   7595       if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
   7596         return false;
   7597 
   7598       // Reject differing bases from the normal codepath; we special-case
   7599       // comparisons to null.
   7600       if (!HasSameBase(LHSValue, RHSValue)) {
   7601         if (E->getOpcode() == BO_Sub) {
   7602           // Handle &&A - &&B.
   7603           if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
   7604             return Error(E);
   7605           const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
   7606           const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
   7607           if (!LHSExpr || !RHSExpr)
   7608             return Error(E);
   7609           const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
   7610           const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
   7611           if (!LHSAddrExpr || !RHSAddrExpr)
   7612             return Error(E);
   7613           // Make sure both labels come from the same function.
   7614           if (LHSAddrExpr->getLabel()->getDeclContext() !=
   7615               RHSAddrExpr->getLabel()->getDeclContext())
   7616             return Error(E);
   7617           return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
   7618         }
   7619         // Inequalities and subtractions between unrelated pointers have
   7620         // unspecified or undefined behavior.
   7621         if (!E->isEqualityOp())
   7622           return Error(E);
   7623         // A constant address may compare equal to the address of a symbol.
   7624         // The one exception is that address of an object cannot compare equal
   7625         // to a null pointer constant.
   7626         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
   7627             (!RHSValue.Base && !RHSValue.Offset.isZero()))
   7628           return Error(E);
   7629         // It's implementation-defined whether distinct literals will have
   7630         // distinct addresses. In clang, the result of such a comparison is
   7631         // unspecified, so it is not a constant expression. However, we do know
   7632         // that the address of a literal will be non-null.
   7633         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
   7634             LHSValue.Base && RHSValue.Base)
   7635           return Error(E);
   7636         // We can't tell whether weak symbols will end up pointing to the same
   7637         // object.
   7638         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
   7639           return Error(E);
   7640         // We can't compare the address of the start of one object with the
   7641         // past-the-end address of another object, per C++ DR1652.
   7642         if ((LHSValue.Base && LHSValue.Offset.isZero() &&
   7643              isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
   7644             (RHSValue.Base && RHSValue.Offset.isZero() &&
   7645              isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
   7646           return Error(E);
   7647         // We can't tell whether an object is at the same address as another
   7648         // zero sized object.
   7649         if ((RHSValue.Base && isZeroSized(LHSValue)) ||
   7650             (LHSValue.Base && isZeroSized(RHSValue)))
   7651           return Error(E);
   7652         // Pointers with different bases cannot represent the same object.
   7653         // (Note that clang defaults to -fmerge-all-constants, which can
   7654         // lead to inconsistent results for comparisons involving the address
   7655         // of a constant; this generally doesn't matter in practice.)
   7656         return Success(E->getOpcode() == BO_NE, E);
   7657       }
   7658 
   7659       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
   7660       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
   7661 
   7662       SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
   7663       SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
   7664 
   7665       if (E->getOpcode() == BO_Sub) {
   7666         // C++11 [expr.add]p6:
   7667         //   Unless both pointers point to elements of the same array object, or
   7668         //   one past the last element of the array object, the behavior is
   7669         //   undefined.
   7670         if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
   7671             !AreElementsOfSameArray(getType(LHSValue.Base),
   7672                                     LHSDesignator, RHSDesignator))
   7673           CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
   7674 
   7675         QualType Type = E->getLHS()->getType();
   7676         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
   7677 
   7678         CharUnits ElementSize;
   7679         if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
   7680           return false;
   7681 
   7682         // As an extension, a type may have zero size (empty struct or union in
   7683         // C, array of zero length). Pointer subtraction in such cases has
   7684         // undefined behavior, so is not constant.
   7685         if (ElementSize.isZero()) {
   7686           Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
   7687             << ElementType;
   7688           return false;
   7689         }
   7690 
   7691         // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
   7692         // and produce incorrect results when it overflows. Such behavior
   7693         // appears to be non-conforming, but is common, so perhaps we should
   7694         // assume the standard intended for such cases to be undefined behavior
   7695         // and check for them.
   7696 
   7697         // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
   7698         // overflow in the final conversion to ptrdiff_t.
   7699         APSInt LHS(
   7700           llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
   7701         APSInt RHS(
   7702           llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
   7703         APSInt ElemSize(
   7704           llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
   7705         APSInt TrueResult = (LHS - RHS) / ElemSize;
   7706         APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
   7707 
   7708         if (Result.extend(65) != TrueResult &&
   7709             !HandleOverflow(Info, E, TrueResult, E->getType()))
   7710           return false;
   7711         return Success(Result, E);
   7712       }
   7713 
   7714       // C++11 [expr.rel]p3:
   7715       //   Pointers to void (after pointer conversions) can be compared, with a
   7716       //   result defined as follows: If both pointers represent the same
   7717       //   address or are both the null pointer value, the result is true if the
   7718       //   operator is <= or >= and false otherwise; otherwise the result is
   7719       //   unspecified.
   7720       // We interpret this as applying to pointers to *cv* void.
   7721       if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
   7722           E->isRelationalOp())
   7723         CCEDiag(E, diag::note_constexpr_void_comparison);
   7724 
   7725       // C++11 [expr.rel]p2:
   7726       // - If two pointers point to non-static data members of the same object,
   7727       //   or to subobjects or array elements fo such members, recursively, the
   7728       //   pointer to the later declared member compares greater provided the
   7729       //   two members have the same access control and provided their class is
   7730       //   not a union.
   7731       //   [...]
   7732       // - Otherwise pointer comparisons are unspecified.
   7733       if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
   7734           E->isRelationalOp()) {
   7735         bool WasArrayIndex;
   7736         unsigned Mismatch =
   7737           FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
   7738                                  RHSDesignator, WasArrayIndex);
   7739         // At the point where the designators diverge, the comparison has a
   7740         // specified value if:
   7741         //  - we are comparing array indices
   7742         //  - we are comparing fields of a union, or fields with the same access
   7743         // Otherwise, the result is unspecified and thus the comparison is not a
   7744         // constant expression.
   7745         if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
   7746             Mismatch < RHSDesignator.Entries.size()) {
   7747           const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
   7748           const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
   7749           if (!LF && !RF)
   7750             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
   7751           else if (!LF)
   7752             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
   7753               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
   7754               << RF->getParent() << RF;
   7755           else if (!RF)
   7756             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
   7757               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
   7758               << LF->getParent() << LF;
   7759           else if (!LF->getParent()->isUnion() &&
   7760                    LF->getAccess() != RF->getAccess())
   7761             CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
   7762               << LF << LF->getAccess() << RF << RF->getAccess()
   7763               << LF->getParent();
   7764         }
   7765       }
   7766 
   7767       // The comparison here must be unsigned, and performed with the same
   7768       // width as the pointer.
   7769       unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
   7770       uint64_t CompareLHS = LHSOffset.getQuantity();
   7771       uint64_t CompareRHS = RHSOffset.getQuantity();
   7772       assert(PtrSize <= 64 && "Unexpected pointer width");
   7773       uint64_t Mask = ~0ULL >> (64 - PtrSize);
   7774       CompareLHS &= Mask;
   7775       CompareRHS &= Mask;
   7776 
   7777       // If there is a base and this is a relational operator, we can only
   7778       // compare pointers within the object in question; otherwise, the result
   7779       // depends on where the object is located in memory.
   7780       if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
   7781         QualType BaseTy = getType(LHSValue.Base);
   7782         if (BaseTy->isIncompleteType())
   7783           return Error(E);
   7784         CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
   7785         uint64_t OffsetLimit = Size.getQuantity();
   7786         if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
   7787           return Error(E);
   7788       }
   7789 
   7790       switch (E->getOpcode()) {
   7791       default: llvm_unreachable("missing comparison operator");
   7792       case BO_LT: return Success(CompareLHS < CompareRHS, E);
   7793       case BO_GT: return Success(CompareLHS > CompareRHS, E);
   7794       case BO_LE: return Success(CompareLHS <= CompareRHS, E);
   7795       case BO_GE: return Success(CompareLHS >= CompareRHS, E);
   7796       case BO_EQ: return Success(CompareLHS == CompareRHS, E);
   7797       case BO_NE: return Success(CompareLHS != CompareRHS, E);
   7798       }
   7799     }
   7800   }
   7801 
   7802   if (LHSTy->isMemberPointerType()) {
   7803     assert(E->isEqualityOp() && "unexpected member pointer operation");
   7804     assert(RHSTy->isMemberPointerType() && "invalid comparison");
   7805 
   7806     MemberPtr LHSValue, RHSValue;
   7807 
   7808     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
   7809     if (!LHSOK && !Info.noteFailure())
   7810       return false;
   7811 
   7812     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
   7813       return false;
   7814 
   7815     // C++11 [expr.eq]p2:
   7816     //   If both operands are null, they compare equal. Otherwise if only one is
   7817     //   null, they compare unequal.
   7818     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
   7819       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
   7820       return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
   7821     }
   7822 
   7823     //   Otherwise if either is a pointer to a virtual member function, the
   7824     //   result is unspecified.
   7825     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
   7826       if (MD->isVirtual())
   7827         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
   7828     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
   7829       if (MD->isVirtual())
   7830         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
   7831 
   7832     //   Otherwise they compare equal if and only if they would refer to the
   7833     //   same member of the same most derived object or the same subobject if
   7834     //   they were dereferenced with a hypothetical object of the associated
   7835     //   class type.
   7836     bool Equal = LHSValue == RHSValue;
   7837     return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
   7838   }
   7839 
   7840   if (LHSTy->isNullPtrType()) {
   7841     assert(E->isComparisonOp() && "unexpected nullptr operation");
   7842     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
   7843     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
   7844     // are compared, the result is true of the operator is <=, >= or ==, and
   7845     // false otherwise.
   7846     BinaryOperator::Opcode Opcode = E->getOpcode();
   7847     return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
   7848   }
   7849 
   7850   assert((!LHSTy->isIntegralOrEnumerationType() ||
   7851           !RHSTy->isIntegralOrEnumerationType()) &&
   7852          "DataRecursiveIntBinOpEvaluator should have handled integral types");
   7853   // We can't continue from here for non-integral types.
   7854   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
   7855 }
   7856 
   7857 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
   7858 /// a result as the expression's type.
   7859 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
   7860                                     const UnaryExprOrTypeTraitExpr *E) {
   7861   switch(E->getKind()) {
   7862   case UETT_AlignOf: {
   7863     if (E->isArgumentType())
   7864       return Success(GetAlignOfType(Info, E->getArgumentType()), E);
   7865     else
   7866       return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
   7867   }
   7868 
   7869   case UETT_VecStep: {
   7870     QualType Ty = E->getTypeOfArgument();
   7871 
   7872     if (Ty->isVectorType()) {
   7873       unsigned n = Ty->castAs<VectorType>()->getNumElements();
   7874 
   7875       // The vec_step built-in functions that take a 3-component
   7876       // vector return 4. (OpenCL 1.1 spec 6.11.12)
   7877       if (n == 3)
   7878         n = 4;
   7879 
   7880       return Success(n, E);
   7881     } else
   7882       return Success(1, E);
   7883   }
   7884 
   7885   case UETT_SizeOf: {
   7886     QualType SrcTy = E->getTypeOfArgument();
   7887     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
   7888     //   the result is the size of the referenced type."
   7889     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
   7890       SrcTy = Ref->getPointeeType();
   7891 
   7892     CharUnits Sizeof;
   7893     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
   7894       return false;
   7895     return Success(Sizeof, E);
   7896   }
   7897   case UETT_OpenMPRequiredSimdAlign:
   7898     assert(E->isArgumentType());
   7899     return Success(
   7900         Info.Ctx.toCharUnitsFromBits(
   7901                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
   7902             .getQuantity(),
   7903         E);
   7904   }
   7905 
   7906   llvm_unreachable("unknown expr/type trait");
   7907 }
   7908 
   7909 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
   7910   CharUnits Result;
   7911   unsigned n = OOE->getNumComponents();
   7912   if (n == 0)
   7913     return Error(OOE);
   7914   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
   7915   for (unsigned i = 0; i != n; ++i) {
   7916     OffsetOfNode ON = OOE->getComponent(i);
   7917     switch (ON.getKind()) {
   7918     case OffsetOfNode::Array: {
   7919       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
   7920       APSInt IdxResult;
   7921       if (!EvaluateInteger(Idx, IdxResult, Info))
   7922         return false;
   7923       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
   7924       if (!AT)
   7925         return Error(OOE);
   7926       CurrentType = AT->getElementType();
   7927       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
   7928       Result += IdxResult.getSExtValue() * ElementSize;
   7929       break;
   7930     }
   7931 
   7932     case OffsetOfNode::Field: {
   7933       FieldDecl *MemberDecl = ON.getField();
   7934       const RecordType *RT = CurrentType->getAs<RecordType>();
   7935       if (!RT)
   7936         return Error(OOE);
   7937       RecordDecl *RD = RT->getDecl();
   7938       if (RD->isInvalidDecl()) return false;
   7939       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
   7940       unsigned i = MemberDecl->getFieldIndex();
   7941       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
   7942       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
   7943       CurrentType = MemberDecl->getType().getNonReferenceType();
   7944       break;
   7945     }
   7946 
   7947     case OffsetOfNode::Identifier:
   7948       llvm_unreachable("dependent __builtin_offsetof");
   7949 
   7950     case OffsetOfNode::Base: {
   7951       CXXBaseSpecifier *BaseSpec = ON.getBase();
   7952       if (BaseSpec->isVirtual())
   7953         return Error(OOE);
   7954 
   7955       // Find the layout of the class whose base we are looking into.
   7956       const RecordType *RT = CurrentType->getAs<RecordType>();
   7957       if (!RT)
   7958         return Error(OOE);
   7959       RecordDecl *RD = RT->getDecl();
   7960       if (RD->isInvalidDecl()) return false;
   7961       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
   7962 
   7963       // Find the base class itself.
   7964       CurrentType = BaseSpec->getType();
   7965       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
   7966       if (!BaseRT)
   7967         return Error(OOE);
   7968 
   7969       // Add the offset to the base.
   7970       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
   7971       break;
   7972     }
   7973     }
   7974   }
   7975   return Success(Result, OOE);
   7976 }
   7977 
   7978 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
   7979   switch (E->getOpcode()) {
   7980   default:
   7981     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
   7982     // See C99 6.6p3.
   7983     return Error(E);
   7984   case UO_Extension:
   7985     // FIXME: Should extension allow i-c-e extension expressions in its scope?
   7986     // If so, we could clear the diagnostic ID.
   7987     return Visit(E->getSubExpr());
   7988   case UO_Plus:
   7989     // The result is just the value.
   7990     return Visit(E->getSubExpr());
   7991   case UO_Minus: {
   7992     if (!Visit(E->getSubExpr()))
   7993       return false;
   7994     if (!Result.isInt()) return Error(E);
   7995     const APSInt &Value = Result.getInt();
   7996     if (Value.isSigned() && Value.isMinSignedValue() &&
   7997         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
   7998                         E->getType()))
   7999       return false;
   8000     return Success(-Value, E);
   8001   }
   8002   case UO_Not: {
   8003     if (!Visit(E->getSubExpr()))
   8004       return false;
   8005     if (!Result.isInt()) return Error(E);
   8006     return Success(~Result.getInt(), E);
   8007   }
   8008   case UO_LNot: {
   8009     bool bres;
   8010     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
   8011       return false;
   8012     return Success(!bres, E);
   8013   }
   8014   }
   8015 }
   8016 
   8017 /// HandleCast - This is used to evaluate implicit or explicit casts where the
   8018 /// result type is integer.
   8019 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
   8020   const Expr *SubExpr = E->getSubExpr();
   8021   QualType DestType = E->getType();
   8022   QualType SrcType = SubExpr->getType();
   8023 
   8024   switch (E->getCastKind()) {
   8025   case CK_BaseToDerived:
   8026   case CK_DerivedToBase:
   8027   case CK_UncheckedDerivedToBase:
   8028   case CK_Dynamic:
   8029   case CK_ToUnion:
   8030   case CK_ArrayToPointerDecay:
   8031   case CK_FunctionToPointerDecay:
   8032   case CK_NullToPointer:
   8033   case CK_NullToMemberPointer:
   8034   case CK_BaseToDerivedMemberPointer:
   8035   case CK_DerivedToBaseMemberPointer:
   8036   case CK_ReinterpretMemberPointer:
   8037   case CK_ConstructorConversion:
   8038   case CK_IntegralToPointer:
   8039   case CK_ToVoid:
   8040   case CK_VectorSplat:
   8041   case CK_IntegralToFloating:
   8042   case CK_FloatingCast:
   8043   case CK_CPointerToObjCPointerCast:
   8044   case CK_BlockPointerToObjCPointerCast:
   8045   case CK_AnyPointerToBlockPointerCast:
   8046   case CK_ObjCObjectLValueCast:
   8047   case CK_FloatingRealToComplex:
   8048   case CK_FloatingComplexToReal:
   8049   case CK_FloatingComplexCast:
   8050   case CK_FloatingComplexToIntegralComplex:
   8051   case CK_IntegralRealToComplex:
   8052   case CK_IntegralComplexCast:
   8053   case CK_IntegralComplexToFloatingComplex:
   8054   case CK_BuiltinFnToFnPtr:
   8055   case CK_ZeroToOCLEvent:
   8056   case CK_NonAtomicToAtomic:
   8057   case CK_AddressSpaceConversion:
   8058     llvm_unreachable("invalid cast kind for integral value");
   8059 
   8060   case CK_BitCast:
   8061   case CK_Dependent:
   8062   case CK_LValueBitCast:
   8063   case CK_ARCProduceObject:
   8064   case CK_ARCConsumeObject:
   8065   case CK_ARCReclaimReturnedObject:
   8066   case CK_ARCExtendBlockObject:
   8067   case CK_CopyAndAutoreleaseBlockObject:
   8068     return Error(E);
   8069 
   8070   case CK_UserDefinedConversion:
   8071   case CK_LValueToRValue:
   8072   case CK_AtomicToNonAtomic:
   8073   case CK_NoOp:
   8074     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   8075 
   8076   case CK_MemberPointerToBoolean:
   8077   case CK_PointerToBoolean:
   8078   case CK_IntegralToBoolean:
   8079   case CK_FloatingToBoolean:
   8080   case CK_BooleanToSignedIntegral:
   8081   case CK_FloatingComplexToBoolean:
   8082   case CK_IntegralComplexToBoolean: {
   8083     bool BoolResult;
   8084     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
   8085       return false;
   8086     uint64_t IntResult = BoolResult;
   8087     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
   8088       IntResult = (uint64_t)-1;
   8089     return Success(IntResult, E);
   8090   }
   8091 
   8092   case CK_IntegralCast: {
   8093     if (!Visit(SubExpr))
   8094       return false;
   8095 
   8096     if (!Result.isInt()) {
   8097       // Allow casts of address-of-label differences if they are no-ops
   8098       // or narrowing.  (The narrowing case isn't actually guaranteed to
   8099       // be constant-evaluatable except in some narrow cases which are hard
   8100       // to detect here.  We let it through on the assumption the user knows
   8101       // what they are doing.)
   8102       if (Result.isAddrLabelDiff())
   8103         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
   8104       // Only allow casts of lvalues if they are lossless.
   8105       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
   8106     }
   8107 
   8108     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
   8109                                       Result.getInt()), E);
   8110   }
   8111 
   8112   case CK_PointerToIntegral: {
   8113     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
   8114 
   8115     LValue LV;
   8116     if (!EvaluatePointer(SubExpr, LV, Info))
   8117       return false;
   8118 
   8119     if (LV.getLValueBase()) {
   8120       // Only allow based lvalue casts if they are lossless.
   8121       // FIXME: Allow a larger integer size than the pointer size, and allow
   8122       // narrowing back down to pointer width in subsequent integral casts.
   8123       // FIXME: Check integer type's active bits, not its type size.
   8124       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
   8125         return Error(E);
   8126 
   8127       LV.Designator.setInvalid();
   8128       LV.moveInto(Result);
   8129       return true;
   8130     }
   8131 
   8132     APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
   8133                                          SrcType);
   8134     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
   8135   }
   8136 
   8137   case CK_IntegralComplexToReal: {
   8138     ComplexValue C;
   8139     if (!EvaluateComplex(SubExpr, C, Info))
   8140       return false;
   8141     return Success(C.getComplexIntReal(), E);
   8142   }
   8143 
   8144   case CK_FloatingToIntegral: {
   8145     APFloat F(0.0);
   8146     if (!EvaluateFloat(SubExpr, F, Info))
   8147       return false;
   8148 
   8149     APSInt Value;
   8150     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
   8151       return false;
   8152     return Success(Value, E);
   8153   }
   8154   }
   8155 
   8156   llvm_unreachable("unknown cast resulting in integral value");
   8157 }
   8158 
   8159 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
   8160   if (E->getSubExpr()->getType()->isAnyComplexType()) {
   8161     ComplexValue LV;
   8162     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
   8163       return false;
   8164     if (!LV.isComplexInt())
   8165       return Error(E);
   8166     return Success(LV.getComplexIntReal(), E);
   8167   }
   8168 
   8169   return Visit(E->getSubExpr());
   8170 }
   8171 
   8172 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   8173   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
   8174     ComplexValue LV;
   8175     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
   8176       return false;
   8177     if (!LV.isComplexInt())
   8178       return Error(E);
   8179     return Success(LV.getComplexIntImag(), E);
   8180   }
   8181 
   8182   VisitIgnoredValue(E->getSubExpr());
   8183   return Success(0, E);
   8184 }
   8185 
   8186 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
   8187   return Success(E->getPackLength(), E);
   8188 }
   8189 
   8190 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
   8191   return Success(E->getValue(), E);
   8192 }
   8193 
   8194 //===----------------------------------------------------------------------===//
   8195 // Float Evaluation
   8196 //===----------------------------------------------------------------------===//
   8197 
   8198 namespace {
   8199 class FloatExprEvaluator
   8200   : public ExprEvaluatorBase<FloatExprEvaluator> {
   8201   APFloat &Result;
   8202 public:
   8203   FloatExprEvaluator(EvalInfo &info, APFloat &result)
   8204     : ExprEvaluatorBaseTy(info), Result(result) {}
   8205 
   8206   bool Success(const APValue &V, const Expr *e) {
   8207     Result = V.getFloat();
   8208     return true;
   8209   }
   8210 
   8211   bool ZeroInitialization(const Expr *E) {
   8212     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
   8213     return true;
   8214   }
   8215 
   8216   bool VisitCallExpr(const CallExpr *E);
   8217 
   8218   bool VisitUnaryOperator(const UnaryOperator *E);
   8219   bool VisitBinaryOperator(const BinaryOperator *E);
   8220   bool VisitFloatingLiteral(const FloatingLiteral *E);
   8221   bool VisitCastExpr(const CastExpr *E);
   8222 
   8223   bool VisitUnaryReal(const UnaryOperator *E);
   8224   bool VisitUnaryImag(const UnaryOperator *E);
   8225 
   8226   // FIXME: Missing: array subscript of vector, member of vector
   8227 };
   8228 } // end anonymous namespace
   8229 
   8230 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
   8231   assert(E->isRValue() && E->getType()->isRealFloatingType());
   8232   return FloatExprEvaluator(Info, Result).Visit(E);
   8233 }
   8234 
   8235 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
   8236                                   QualType ResultTy,
   8237                                   const Expr *Arg,
   8238                                   bool SNaN,
   8239                                   llvm::APFloat &Result) {
   8240   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
   8241   if (!S) return false;
   8242 
   8243   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
   8244 
   8245   llvm::APInt fill;
   8246 
   8247   // Treat empty strings as if they were zero.
   8248   if (S->getString().empty())
   8249     fill = llvm::APInt(32, 0);
   8250   else if (S->getString().getAsInteger(0, fill))
   8251     return false;
   8252 
   8253   if (Context.getTargetInfo().isNan2008()) {
   8254     if (SNaN)
   8255       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
   8256     else
   8257       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
   8258   } else {
   8259     // Prior to IEEE 754-2008, architectures were allowed to choose whether
   8260     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
   8261     // a different encoding to what became a standard in 2008, and for pre-
   8262     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
   8263     // sNaN. This is now known as "legacy NaN" encoding.
   8264     if (SNaN)
   8265       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
   8266     else
   8267       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
   8268   }
   8269 
   8270   return true;
   8271 }
   8272 
   8273 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
   8274   switch (E->getBuiltinCallee()) {
   8275   default:
   8276     return ExprEvaluatorBaseTy::VisitCallExpr(E);
   8277 
   8278   case Builtin::BI__builtin_huge_val:
   8279   case Builtin::BI__builtin_huge_valf:
   8280   case Builtin::BI__builtin_huge_vall:
   8281   case Builtin::BI__builtin_inf:
   8282   case Builtin::BI__builtin_inff:
   8283   case Builtin::BI__builtin_infl: {
   8284     const llvm::fltSemantics &Sem =
   8285       Info.Ctx.getFloatTypeSemantics(E->getType());
   8286     Result = llvm::APFloat::getInf(Sem);
   8287     return true;
   8288   }
   8289 
   8290   case Builtin::BI__builtin_nans:
   8291   case Builtin::BI__builtin_nansf:
   8292   case Builtin::BI__builtin_nansl:
   8293     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
   8294                                true, Result))
   8295       return Error(E);
   8296     return true;
   8297 
   8298   case Builtin::BI__builtin_nan:
   8299   case Builtin::BI__builtin_nanf:
   8300   case Builtin::BI__builtin_nanl:
   8301     // If this is __builtin_nan() turn this into a nan, otherwise we
   8302     // can't constant fold it.
   8303     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
   8304                                false, Result))
   8305       return Error(E);
   8306     return true;
   8307 
   8308   case Builtin::BI__builtin_fabs:
   8309   case Builtin::BI__builtin_fabsf:
   8310   case Builtin::BI__builtin_fabsl:
   8311     if (!EvaluateFloat(E->getArg(0), Result, Info))
   8312       return false;
   8313 
   8314     if (Result.isNegative())
   8315       Result.changeSign();
   8316     return true;
   8317 
   8318   // FIXME: Builtin::BI__builtin_powi
   8319   // FIXME: Builtin::BI__builtin_powif
   8320   // FIXME: Builtin::BI__builtin_powil
   8321 
   8322   case Builtin::BI__builtin_copysign:
   8323   case Builtin::BI__builtin_copysignf:
   8324   case Builtin::BI__builtin_copysignl: {
   8325     APFloat RHS(0.);
   8326     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
   8327         !EvaluateFloat(E->getArg(1), RHS, Info))
   8328       return false;
   8329     Result.copySign(RHS);
   8330     return true;
   8331   }
   8332   }
   8333 }
   8334 
   8335 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
   8336   if (E->getSubExpr()->getType()->isAnyComplexType()) {
   8337     ComplexValue CV;
   8338     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
   8339       return false;
   8340     Result = CV.FloatReal;
   8341     return true;
   8342   }
   8343 
   8344   return Visit(E->getSubExpr());
   8345 }
   8346 
   8347 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   8348   if (E->getSubExpr()->getType()->isAnyComplexType()) {
   8349     ComplexValue CV;
   8350     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
   8351       return false;
   8352     Result = CV.FloatImag;
   8353     return true;
   8354   }
   8355 
   8356   VisitIgnoredValue(E->getSubExpr());
   8357   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
   8358   Result = llvm::APFloat::getZero(Sem);
   8359   return true;
   8360 }
   8361 
   8362 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
   8363   switch (E->getOpcode()) {
   8364   default: return Error(E);
   8365   case UO_Plus:
   8366     return EvaluateFloat(E->getSubExpr(), Result, Info);
   8367   case UO_Minus:
   8368     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
   8369       return false;
   8370     Result.changeSign();
   8371     return true;
   8372   }
   8373 }
   8374 
   8375 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   8376   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
   8377     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
   8378 
   8379   APFloat RHS(0.0);
   8380   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
   8381   if (!LHSOK && !Info.noteFailure())
   8382     return false;
   8383   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
   8384          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
   8385 }
   8386 
   8387 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
   8388   Result = E->getValue();
   8389   return true;
   8390 }
   8391 
   8392 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
   8393   const Expr* SubExpr = E->getSubExpr();
   8394 
   8395   switch (E->getCastKind()) {
   8396   default:
   8397     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   8398 
   8399   case CK_IntegralToFloating: {
   8400     APSInt IntResult;
   8401     return EvaluateInteger(SubExpr, IntResult, Info) &&
   8402            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
   8403                                 E->getType(), Result);
   8404   }
   8405 
   8406   case CK_FloatingCast: {
   8407     if (!Visit(SubExpr))
   8408       return false;
   8409     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
   8410                                   Result);
   8411   }
   8412 
   8413   case CK_FloatingComplexToReal: {
   8414     ComplexValue V;
   8415     if (!EvaluateComplex(SubExpr, V, Info))
   8416       return false;
   8417     Result = V.getComplexFloatReal();
   8418     return true;
   8419   }
   8420   }
   8421 }
   8422 
   8423 //===----------------------------------------------------------------------===//
   8424 // Complex Evaluation (for float and integer)
   8425 //===----------------------------------------------------------------------===//
   8426 
   8427 namespace {
   8428 class ComplexExprEvaluator
   8429   : public ExprEvaluatorBase<ComplexExprEvaluator> {
   8430   ComplexValue &Result;
   8431 
   8432 public:
   8433   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
   8434     : ExprEvaluatorBaseTy(info), Result(Result) {}
   8435 
   8436   bool Success(const APValue &V, const Expr *e) {
   8437     Result.setFrom(V);
   8438     return true;
   8439   }
   8440 
   8441   bool ZeroInitialization(const Expr *E);
   8442 
   8443   //===--------------------------------------------------------------------===//
   8444   //                            Visitor Methods
   8445   //===--------------------------------------------------------------------===//
   8446 
   8447   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
   8448   bool VisitCastExpr(const CastExpr *E);
   8449   bool VisitBinaryOperator(const BinaryOperator *E);
   8450   bool VisitUnaryOperator(const UnaryOperator *E);
   8451   bool VisitInitListExpr(const InitListExpr *E);
   8452 };
   8453 } // end anonymous namespace
   8454 
   8455 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
   8456                             EvalInfo &Info) {
   8457   assert(E->isRValue() && E->getType()->isAnyComplexType());
   8458   return ComplexExprEvaluator(Info, Result).Visit(E);
   8459 }
   8460 
   8461 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
   8462   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
   8463   if (ElemTy->isRealFloatingType()) {
   8464     Result.makeComplexFloat();
   8465     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
   8466     Result.FloatReal = Zero;
   8467     Result.FloatImag = Zero;
   8468   } else {
   8469     Result.makeComplexInt();
   8470     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
   8471     Result.IntReal = Zero;
   8472     Result.IntImag = Zero;
   8473   }
   8474   return true;
   8475 }
   8476 
   8477 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
   8478   const Expr* SubExpr = E->getSubExpr();
   8479 
   8480   if (SubExpr->getType()->isRealFloatingType()) {
   8481     Result.makeComplexFloat();
   8482     APFloat &Imag = Result.FloatImag;
   8483     if (!EvaluateFloat(SubExpr, Imag, Info))
   8484       return false;
   8485 
   8486     Result.FloatReal = APFloat(Imag.getSemantics());
   8487     return true;
   8488   } else {
   8489     assert(SubExpr->getType()->isIntegerType() &&
   8490            "Unexpected imaginary literal.");
   8491 
   8492     Result.makeComplexInt();
   8493     APSInt &Imag = Result.IntImag;
   8494     if (!EvaluateInteger(SubExpr, Imag, Info))
   8495       return false;
   8496 
   8497     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
   8498     return true;
   8499   }
   8500 }
   8501 
   8502 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
   8503 
   8504   switch (E->getCastKind()) {
   8505   case CK_BitCast:
   8506   case CK_BaseToDerived:
   8507   case CK_DerivedToBase:
   8508   case CK_UncheckedDerivedToBase:
   8509   case CK_Dynamic:
   8510   case CK_ToUnion:
   8511   case CK_ArrayToPointerDecay:
   8512   case CK_FunctionToPointerDecay:
   8513   case CK_NullToPointer:
   8514   case CK_NullToMemberPointer:
   8515   case CK_BaseToDerivedMemberPointer:
   8516   case CK_DerivedToBaseMemberPointer:
   8517   case CK_MemberPointerToBoolean:
   8518   case CK_ReinterpretMemberPointer:
   8519   case CK_ConstructorConversion:
   8520   case CK_IntegralToPointer:
   8521   case CK_PointerToIntegral:
   8522   case CK_PointerToBoolean:
   8523   case CK_ToVoid:
   8524   case CK_VectorSplat:
   8525   case CK_IntegralCast:
   8526   case CK_BooleanToSignedIntegral:
   8527   case CK_IntegralToBoolean:
   8528   case CK_IntegralToFloating:
   8529   case CK_FloatingToIntegral:
   8530   case CK_FloatingToBoolean:
   8531   case CK_FloatingCast:
   8532   case CK_CPointerToObjCPointerCast:
   8533   case CK_BlockPointerToObjCPointerCast:
   8534   case CK_AnyPointerToBlockPointerCast:
   8535   case CK_ObjCObjectLValueCast:
   8536   case CK_FloatingComplexToReal:
   8537   case CK_FloatingComplexToBoolean:
   8538   case CK_IntegralComplexToReal:
   8539   case CK_IntegralComplexToBoolean:
   8540   case CK_ARCProduceObject:
   8541   case CK_ARCConsumeObject:
   8542   case CK_ARCReclaimReturnedObject:
   8543   case CK_ARCExtendBlockObject:
   8544   case CK_CopyAndAutoreleaseBlockObject:
   8545   case CK_BuiltinFnToFnPtr:
   8546   case CK_ZeroToOCLEvent:
   8547   case CK_NonAtomicToAtomic:
   8548   case CK_AddressSpaceConversion:
   8549     llvm_unreachable("invalid cast kind for complex value");
   8550 
   8551   case CK_LValueToRValue:
   8552   case CK_AtomicToNonAtomic:
   8553   case CK_NoOp:
   8554     return ExprEvaluatorBaseTy::VisitCastExpr(E);
   8555 
   8556   case CK_Dependent:
   8557   case CK_LValueBitCast:
   8558   case CK_UserDefinedConversion:
   8559     return Error(E);
   8560 
   8561   case CK_FloatingRealToComplex: {
   8562     APFloat &Real = Result.FloatReal;
   8563     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
   8564       return false;
   8565 
   8566     Result.makeComplexFloat();
   8567     Result.FloatImag = APFloat(Real.getSemantics());
   8568     return true;
   8569   }
   8570 
   8571   case CK_FloatingComplexCast: {
   8572     if (!Visit(E->getSubExpr()))
   8573       return false;
   8574 
   8575     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   8576     QualType From
   8577       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   8578 
   8579     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
   8580            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
   8581   }
   8582 
   8583   case CK_FloatingComplexToIntegralComplex: {
   8584     if (!Visit(E->getSubExpr()))
   8585       return false;
   8586 
   8587     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   8588     QualType From
   8589       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   8590     Result.makeComplexInt();
   8591     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
   8592                                 To, Result.IntReal) &&
   8593            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
   8594                                 To, Result.IntImag);
   8595   }
   8596 
   8597   case CK_IntegralRealToComplex: {
   8598     APSInt &Real = Result.IntReal;
   8599     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
   8600       return false;
   8601 
   8602     Result.makeComplexInt();
   8603     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
   8604     return true;
   8605   }
   8606 
   8607   case CK_IntegralComplexCast: {
   8608     if (!Visit(E->getSubExpr()))
   8609       return false;
   8610 
   8611     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
   8612     QualType From
   8613       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
   8614 
   8615     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
   8616     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
   8617     return true;
   8618   }
   8619 
   8620   case CK_IntegralComplexToFloatingComplex: {
   8621     if (!Visit(E->getSubExpr()))
   8622       return false;
   8623 
   8624     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
   8625     QualType From
   8626       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
   8627     Result.makeComplexFloat();
   8628     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
   8629                                 To, Result.FloatReal) &&
   8630            HandleIntToFloatCast(Info, E, From, Result.IntImag,
   8631                                 To, Result.FloatImag);
   8632   }
   8633   }
   8634 
   8635   llvm_unreachable("unknown cast resulting in complex value");
   8636 }
   8637 
   8638 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   8639   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
   8640     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
   8641 
   8642   // Track whether the LHS or RHS is real at the type system level. When this is
   8643   // the case we can simplify our evaluation strategy.
   8644   bool LHSReal = false, RHSReal = false;
   8645 
   8646   bool LHSOK;
   8647   if (E->getLHS()->getType()->isRealFloatingType()) {
   8648     LHSReal = true;
   8649     APFloat &Real = Result.FloatReal;
   8650     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
   8651     if (LHSOK) {
   8652       Result.makeComplexFloat();
   8653       Result.FloatImag = APFloat(Real.getSemantics());
   8654     }
   8655   } else {
   8656     LHSOK = Visit(E->getLHS());
   8657   }
   8658   if (!LHSOK && !Info.noteFailure())
   8659     return false;
   8660 
   8661   ComplexValue RHS;
   8662   if (E->getRHS()->getType()->isRealFloatingType()) {
   8663     RHSReal = true;
   8664     APFloat &Real = RHS.FloatReal;
   8665     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
   8666       return false;
   8667     RHS.makeComplexFloat();
   8668     RHS.FloatImag = APFloat(Real.getSemantics());
   8669   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
   8670     return false;
   8671 
   8672   assert(!(LHSReal && RHSReal) &&
   8673          "Cannot have both operands of a complex operation be real.");
   8674   switch (E->getOpcode()) {
   8675   default: return Error(E);
   8676   case BO_Add:
   8677     if (Result.isComplexFloat()) {
   8678       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
   8679                                        APFloat::rmNearestTiesToEven);
   8680       if (LHSReal)
   8681         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
   8682       else if (!RHSReal)
   8683         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
   8684                                          APFloat::rmNearestTiesToEven);
   8685     } else {
   8686       Result.getComplexIntReal() += RHS.getComplexIntReal();
   8687       Result.getComplexIntImag() += RHS.getComplexIntImag();
   8688     }
   8689     break;
   8690   case BO_Sub:
   8691     if (Result.isComplexFloat()) {
   8692       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
   8693                                             APFloat::rmNearestTiesToEven);
   8694       if (LHSReal) {
   8695         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
   8696         Result.getComplexFloatImag().changeSign();
   8697       } else if (!RHSReal) {
   8698         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
   8699                                               APFloat::rmNearestTiesToEven);
   8700       }
   8701     } else {
   8702       Result.getComplexIntReal() -= RHS.getComplexIntReal();
   8703       Result.getComplexIntImag() -= RHS.getComplexIntImag();
   8704     }
   8705     break;
   8706   case BO_Mul:
   8707     if (Result.isComplexFloat()) {
   8708       // This is an implementation of complex multiplication according to the
   8709       // constraints laid out in C11 Annex G. The implemantion uses the
   8710       // following naming scheme:
   8711       //   (a + ib) * (c + id)
   8712       ComplexValue LHS = Result;
   8713       APFloat &A = LHS.getComplexFloatReal();
   8714       APFloat &B = LHS.getComplexFloatImag();
   8715       APFloat &C = RHS.getComplexFloatReal();
   8716       APFloat &D = RHS.getComplexFloatImag();
   8717       APFloat &ResR = Result.getComplexFloatReal();
   8718       APFloat &ResI = Result.getComplexFloatImag();
   8719       if (LHSReal) {
   8720         assert(!RHSReal && "Cannot have two real operands for a complex op!");
   8721         ResR = A * C;
   8722         ResI = A * D;
   8723       } else if (RHSReal) {
   8724         ResR = C * A;
   8725         ResI = C * B;
   8726       } else {
   8727         // In the fully general case, we need to handle NaNs and infinities
   8728         // robustly.
   8729         APFloat AC = A * C;
   8730         APFloat BD = B * D;
   8731         APFloat AD = A * D;
   8732         APFloat BC = B * C;
   8733         ResR = AC - BD;
   8734         ResI = AD + BC;
   8735         if (ResR.isNaN() && ResI.isNaN()) {
   8736           bool Recalc = false;
   8737           if (A.isInfinity() || B.isInfinity()) {
   8738             A = APFloat::copySign(
   8739                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
   8740             B = APFloat::copySign(
   8741                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
   8742             if (C.isNaN())
   8743               C = APFloat::copySign(APFloat(C.getSemantics()), C);
   8744             if (D.isNaN())
   8745               D = APFloat::copySign(APFloat(D.getSemantics()), D);
   8746             Recalc = true;
   8747           }
   8748           if (C.isInfinity() || D.isInfinity()) {
   8749             C = APFloat::copySign(
   8750                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
   8751             D = APFloat::copySign(
   8752                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
   8753             if (A.isNaN())
   8754               A = APFloat::copySign(APFloat(A.getSemantics()), A);
   8755             if (B.isNaN())
   8756               B = APFloat::copySign(APFloat(B.getSemantics()), B);
   8757             Recalc = true;
   8758           }
   8759           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
   8760                           AD.isInfinity() || BC.isInfinity())) {
   8761             if (A.isNaN())
   8762               A = APFloat::copySign(APFloat(A.getSemantics()), A);
   8763             if (B.isNaN())
   8764               B = APFloat::copySign(APFloat(B.getSemantics()), B);
   8765             if (C.isNaN())
   8766               C = APFloat::copySign(APFloat(C.getSemantics()), C);
   8767             if (D.isNaN())
   8768               D = APFloat::copySign(APFloat(D.getSemantics()), D);
   8769             Recalc = true;
   8770           }
   8771           if (Recalc) {
   8772             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
   8773             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
   8774           }
   8775         }
   8776       }
   8777     } else {
   8778       ComplexValue LHS = Result;
   8779       Result.getComplexIntReal() =
   8780         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
   8781          LHS.getComplexIntImag() * RHS.getComplexIntImag());
   8782       Result.getComplexIntImag() =
   8783         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
   8784          LHS.getComplexIntImag() * RHS.getComplexIntReal());
   8785     }
   8786     break;
   8787   case BO_Div:
   8788     if (Result.isComplexFloat()) {
   8789       // This is an implementation of complex division according to the
   8790       // constraints laid out in C11 Annex G. The implemantion uses the
   8791       // following naming scheme:
   8792       //   (a + ib) / (c + id)
   8793       ComplexValue LHS = Result;
   8794       APFloat &A = LHS.getComplexFloatReal();
   8795       APFloat &B = LHS.getComplexFloatImag();
   8796       APFloat &C = RHS.getComplexFloatReal();
   8797       APFloat &D = RHS.getComplexFloatImag();
   8798       APFloat &ResR = Result.getComplexFloatReal();
   8799       APFloat &ResI = Result.getComplexFloatImag();
   8800       if (RHSReal) {
   8801         ResR = A / C;
   8802         ResI = B / C;
   8803       } else {
   8804         if (LHSReal) {
   8805           // No real optimizations we can do here, stub out with zero.
   8806           B = APFloat::getZero(A.getSemantics());
   8807         }
   8808         int DenomLogB = 0;
   8809         APFloat MaxCD = maxnum(abs(C), abs(D));
   8810         if (MaxCD.isFinite()) {
   8811           DenomLogB = ilogb(MaxCD);
   8812           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
   8813           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
   8814         }
   8815         APFloat Denom = C * C + D * D;
   8816         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
   8817                       APFloat::rmNearestTiesToEven);
   8818         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
   8819                       APFloat::rmNearestTiesToEven);
   8820         if (ResR.isNaN() && ResI.isNaN()) {
   8821           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
   8822             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
   8823             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
   8824           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
   8825                      D.isFinite()) {
   8826             A = APFloat::copySign(
   8827                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
   8828             B = APFloat::copySign(
   8829                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
   8830             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
   8831             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
   8832           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
   8833             C = APFloat::copySign(
   8834                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
   8835             D = APFloat::copySign(
   8836                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
   8837             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
   8838             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
   8839           }
   8840         }
   8841       }
   8842     } else {
   8843       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
   8844         return Error(E, diag::note_expr_divide_by_zero);
   8845 
   8846       ComplexValue LHS = Result;
   8847       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
   8848         RHS.getComplexIntImag() * RHS.getComplexIntImag();
   8849       Result.getComplexIntReal() =
   8850         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
   8851          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
   8852       Result.getComplexIntImag() =
   8853         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
   8854          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
   8855     }
   8856     break;
   8857   }
   8858 
   8859   return true;
   8860 }
   8861 
   8862 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
   8863   // Get the operand value into 'Result'.
   8864   if (!Visit(E->getSubExpr()))
   8865     return false;
   8866 
   8867   switch (E->getOpcode()) {
   8868   default:
   8869     return Error(E);
   8870   case UO_Extension:
   8871     return true;
   8872   case UO_Plus:
   8873     // The result is always just the subexpr.
   8874     return true;
   8875   case UO_Minus:
   8876     if (Result.isComplexFloat()) {
   8877       Result.getComplexFloatReal().changeSign();
   8878       Result.getComplexFloatImag().changeSign();
   8879     }
   8880     else {
   8881       Result.getComplexIntReal() = -Result.getComplexIntReal();
   8882       Result.getComplexIntImag() = -Result.getComplexIntImag();
   8883     }
   8884     return true;
   8885   case UO_Not:
   8886     if (Result.isComplexFloat())
   8887       Result.getComplexFloatImag().changeSign();
   8888     else
   8889       Result.getComplexIntImag() = -Result.getComplexIntImag();
   8890     return true;
   8891   }
   8892 }
   8893 
   8894 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
   8895   if (E->getNumInits() == 2) {
   8896     if (E->getType()->isComplexType()) {
   8897       Result.makeComplexFloat();
   8898       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
   8899         return false;
   8900       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
   8901         return false;
   8902     } else {
   8903       Result.makeComplexInt();
   8904       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
   8905         return false;
   8906       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
   8907         return false;
   8908     }
   8909     return true;
   8910   }
   8911   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
   8912 }
   8913 
   8914 //===----------------------------------------------------------------------===//
   8915 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
   8916 // implicit conversion.
   8917 //===----------------------------------------------------------------------===//
   8918 
   8919 namespace {
   8920 class AtomicExprEvaluator :
   8921     public ExprEvaluatorBase<AtomicExprEvaluator> {
   8922   APValue &Result;
   8923 public:
   8924   AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
   8925       : ExprEvaluatorBaseTy(Info), Result(Result) {}
   8926 
   8927   bool Success(const APValue &V, const Expr *E) {
   8928     Result = V;
   8929     return true;
   8930   }
   8931 
   8932   bool ZeroInitialization(const Expr *E) {
   8933     ImplicitValueInitExpr VIE(
   8934         E->getType()->castAs<AtomicType>()->getValueType());
   8935     return Evaluate(Result, Info, &VIE);
   8936   }
   8937 
   8938   bool VisitCastExpr(const CastExpr *E) {
   8939     switch (E->getCastKind()) {
   8940     default:
   8941       return ExprEvaluatorBaseTy::VisitCastExpr(E);
   8942     case CK_NonAtomicToAtomic:
   8943       return Evaluate(Result, Info, E->getSubExpr());
   8944     }
   8945   }
   8946 };
   8947 } // end anonymous namespace
   8948 
   8949 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
   8950   assert(E->isRValue() && E->getType()->isAtomicType());
   8951   return AtomicExprEvaluator(Info, Result).Visit(E);
   8952 }
   8953 
   8954 //===----------------------------------------------------------------------===//
   8955 // Void expression evaluation, primarily for a cast to void on the LHS of a
   8956 // comma operator
   8957 //===----------------------------------------------------------------------===//
   8958 
   8959 namespace {
   8960 class VoidExprEvaluator
   8961   : public ExprEvaluatorBase<VoidExprEvaluator> {
   8962 public:
   8963   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
   8964 
   8965   bool Success(const APValue &V, const Expr *e) { return true; }
   8966 
   8967   bool VisitCastExpr(const CastExpr *E) {
   8968     switch (E->getCastKind()) {
   8969     default:
   8970       return ExprEvaluatorBaseTy::VisitCastExpr(E);
   8971     case CK_ToVoid:
   8972       VisitIgnoredValue(E->getSubExpr());
   8973       return true;
   8974     }
   8975   }
   8976 
   8977   bool VisitCallExpr(const CallExpr *E) {
   8978     switch (E->getBuiltinCallee()) {
   8979     default:
   8980       return ExprEvaluatorBaseTy::VisitCallExpr(E);
   8981     case Builtin::BI__assume:
   8982     case Builtin::BI__builtin_assume:
   8983       // The argument is not evaluated!
   8984       return true;
   8985     }
   8986   }
   8987 };
   8988 } // end anonymous namespace
   8989 
   8990 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
   8991   assert(E->isRValue() && E->getType()->isVoidType());
   8992   return VoidExprEvaluator(Info).Visit(E);
   8993 }
   8994 
   8995 //===----------------------------------------------------------------------===//
   8996 // Top level Expr::EvaluateAsRValue method.
   8997 //===----------------------------------------------------------------------===//
   8998 
   8999 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
   9000   // In C, function designators are not lvalues, but we evaluate them as if they
   9001   // are.
   9002   QualType T = E->getType();
   9003   if (E->isGLValue() || T->isFunctionType()) {
   9004     LValue LV;
   9005     if (!EvaluateLValue(E, LV, Info))
   9006       return false;
   9007     LV.moveInto(Result);
   9008   } else if (T->isVectorType()) {
   9009     if (!EvaluateVector(E, Result, Info))
   9010       return false;
   9011   } else if (T->isIntegralOrEnumerationType()) {
   9012     if (!IntExprEvaluator(Info, Result).Visit(E))
   9013       return false;
   9014   } else if (T->hasPointerRepresentation()) {
   9015     LValue LV;
   9016     if (!EvaluatePointer(E, LV, Info))
   9017       return false;
   9018     LV.moveInto(Result);
   9019   } else if (T->isRealFloatingType()) {
   9020     llvm::APFloat F(0.0);
   9021     if (!EvaluateFloat(E, F, Info))
   9022       return false;
   9023     Result = APValue(F);
   9024   } else if (T->isAnyComplexType()) {
   9025     ComplexValue C;
   9026     if (!EvaluateComplex(E, C, Info))
   9027       return false;
   9028     C.moveInto(Result);
   9029   } else if (T->isMemberPointerType()) {
   9030     MemberPtr P;
   9031     if (!EvaluateMemberPointer(E, P, Info))
   9032       return false;
   9033     P.moveInto(Result);
   9034     return true;
   9035   } else if (T->isArrayType()) {
   9036     LValue LV;
   9037     LV.set(E, Info.CurrentCall->Index);
   9038     APValue &Value = Info.CurrentCall->createTemporary(E, false);
   9039     if (!EvaluateArray(E, LV, Value, Info))
   9040       return false;
   9041     Result = Value;
   9042   } else if (T->isRecordType()) {
   9043     LValue LV;
   9044     LV.set(E, Info.CurrentCall->Index);
   9045     APValue &Value = Info.CurrentCall->createTemporary(E, false);
   9046     if (!EvaluateRecord(E, LV, Value, Info))
   9047       return false;
   9048     Result = Value;
   9049   } else if (T->isVoidType()) {
   9050     if (!Info.getLangOpts().CPlusPlus11)
   9051       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
   9052         << E->getType();
   9053     if (!EvaluateVoid(E, Info))
   9054       return false;
   9055   } else if (T->isAtomicType()) {
   9056     if (!EvaluateAtomic(E, Result, Info))
   9057       return false;
   9058   } else if (Info.getLangOpts().CPlusPlus11) {
   9059     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
   9060     return false;
   9061   } else {
   9062     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
   9063     return false;
   9064   }
   9065 
   9066   return true;
   9067 }
   9068 
   9069 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
   9070 /// cases, the in-place evaluation is essential, since later initializers for
   9071 /// an object can indirectly refer to subobjects which were initialized earlier.
   9072 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
   9073                             const Expr *E, bool AllowNonLiteralTypes) {
   9074   assert(!E->isValueDependent());
   9075 
   9076   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
   9077     return false;
   9078 
   9079   if (E->isRValue()) {
   9080     // Evaluate arrays and record types in-place, so that later initializers can
   9081     // refer to earlier-initialized members of the object.
   9082     if (E->getType()->isArrayType())
   9083       return EvaluateArray(E, This, Result, Info);
   9084     else if (E->getType()->isRecordType())
   9085       return EvaluateRecord(E, This, Result, Info);
   9086   }
   9087 
   9088   // For any other type, in-place evaluation is unimportant.
   9089   return Evaluate(Result, Info, E);
   9090 }
   9091 
   9092 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
   9093 /// lvalue-to-rvalue cast if it is an lvalue.
   9094 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
   9095   if (E->getType().isNull())
   9096     return false;
   9097 
   9098   if (!CheckLiteralType(Info, E))
   9099     return false;
   9100 
   9101   if (!::Evaluate(Result, Info, E))
   9102     return false;
   9103 
   9104   if (E->isGLValue()) {
   9105     LValue LV;
   9106     LV.setFrom(Info.Ctx, Result);
   9107     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
   9108       return false;
   9109   }
   9110 
   9111   // Check this core constant expression is a constant expression.
   9112   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
   9113 }
   9114 
   9115 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
   9116                                  const ASTContext &Ctx, bool &IsConst) {
   9117   // Fast-path evaluations of integer literals, since we sometimes see files
   9118   // containing vast quantities of these.
   9119   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
   9120     Result.Val = APValue(APSInt(L->getValue(),
   9121                                 L->getType()->isUnsignedIntegerType()));
   9122     IsConst = true;
   9123     return true;
   9124   }
   9125 
   9126   // This case should be rare, but we need to check it before we check on
   9127   // the type below.
   9128   if (Exp->getType().isNull()) {
   9129     IsConst = false;
   9130     return true;
   9131   }
   9132 
   9133   // FIXME: Evaluating values of large array and record types can cause
   9134   // performance problems. Only do so in C++11 for now.
   9135   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
   9136                           Exp->getType()->isRecordType()) &&
   9137       !Ctx.getLangOpts().CPlusPlus11) {
   9138     IsConst = false;
   9139     return true;
   9140   }
   9141   return false;
   9142 }
   9143 
   9144 
   9145 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
   9146 /// any crazy technique (that has nothing to do with language standards) that
   9147 /// we want to.  If this function returns true, it returns the folded constant
   9148 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
   9149 /// will be applied to the result.
   9150 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
   9151   bool IsConst;
   9152   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
   9153     return IsConst;
   9154 
   9155   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
   9156   return ::EvaluateAsRValue(Info, this, Result.Val);
   9157 }
   9158 
   9159 bool Expr::EvaluateAsBooleanCondition(bool &Result,
   9160                                       const ASTContext &Ctx) const {
   9161   EvalResult Scratch;
   9162   return EvaluateAsRValue(Scratch, Ctx) &&
   9163          HandleConversionToBool(Scratch.Val, Result);
   9164 }
   9165 
   9166 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
   9167                                       Expr::SideEffectsKind SEK) {
   9168   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
   9169          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
   9170 }
   9171 
   9172 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
   9173                          SideEffectsKind AllowSideEffects) const {
   9174   if (!getType()->isIntegralOrEnumerationType())
   9175     return false;
   9176 
   9177   EvalResult ExprResult;
   9178   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
   9179       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
   9180     return false;
   9181 
   9182   Result = ExprResult.Val.getInt();
   9183   return true;
   9184 }
   9185 
   9186 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
   9187                            SideEffectsKind AllowSideEffects) const {
   9188   if (!getType()->isRealFloatingType())
   9189     return false;
   9190 
   9191   EvalResult ExprResult;
   9192   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
   9193       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
   9194     return false;
   9195 
   9196   Result = ExprResult.Val.getFloat();
   9197   return true;
   9198 }
   9199 
   9200 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
   9201   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
   9202 
   9203   LValue LV;
   9204   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
   9205       !CheckLValueConstantExpression(Info, getExprLoc(),
   9206                                      Ctx.getLValueReferenceType(getType()), LV))
   9207     return false;
   9208 
   9209   LV.moveInto(Result.Val);
   9210   return true;
   9211 }
   9212 
   9213 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
   9214                                  const VarDecl *VD,
   9215                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
   9216   // FIXME: Evaluating initializers for large array and record types can cause
   9217   // performance problems. Only do so in C++11 for now.
   9218   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
   9219       !Ctx.getLangOpts().CPlusPlus11)
   9220     return false;
   9221 
   9222   Expr::EvalStatus EStatus;
   9223   EStatus.Diag = &Notes;
   9224 
   9225   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
   9226                                       ? EvalInfo::EM_ConstantExpression
   9227                                       : EvalInfo::EM_ConstantFold);
   9228   InitInfo.setEvaluatingDecl(VD, Value);
   9229 
   9230   LValue LVal;
   9231   LVal.set(VD);
   9232 
   9233   // C++11 [basic.start.init]p2:
   9234   //  Variables with static storage duration or thread storage duration shall be
   9235   //  zero-initialized before any other initialization takes place.
   9236   // This behavior is not present in C.
   9237   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
   9238       !VD->getType()->isReferenceType()) {
   9239     ImplicitValueInitExpr VIE(VD->getType());
   9240     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
   9241                          /*AllowNonLiteralTypes=*/true))
   9242       return false;
   9243   }
   9244 
   9245   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
   9246                        /*AllowNonLiteralTypes=*/true) ||
   9247       EStatus.HasSideEffects)
   9248     return false;
   9249 
   9250   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
   9251                                  Value);
   9252 }
   9253 
   9254 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
   9255 /// constant folded, but discard the result.
   9256 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
   9257   EvalResult Result;
   9258   return EvaluateAsRValue(Result, Ctx) &&
   9259          !hasUnacceptableSideEffect(Result, SEK);
   9260 }
   9261 
   9262 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
   9263                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
   9264   EvalResult EvalResult;
   9265   EvalResult.Diag = Diag;
   9266   bool Result = EvaluateAsRValue(EvalResult, Ctx);
   9267   (void)Result;
   9268   assert(Result && "Could not evaluate expression");
   9269   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
   9270 
   9271   return EvalResult.Val.getInt();
   9272 }
   9273 
   9274 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
   9275   bool IsConst;
   9276   EvalResult EvalResult;
   9277   if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
   9278     EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
   9279     (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
   9280   }
   9281 }
   9282 
   9283 bool Expr::EvalResult::isGlobalLValue() const {
   9284   assert(Val.isLValue());
   9285   return IsGlobalLValue(Val.getLValueBase());
   9286 }
   9287 
   9288 
   9289 /// isIntegerConstantExpr - this recursive routine will test if an expression is
   9290 /// an integer constant expression.
   9291 
   9292 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
   9293 /// comma, etc
   9294 
   9295 // CheckICE - This function does the fundamental ICE checking: the returned
   9296 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
   9297 // and a (possibly null) SourceLocation indicating the location of the problem.
   9298 //
   9299 // Note that to reduce code duplication, this helper does no evaluation
   9300 // itself; the caller checks whether the expression is evaluatable, and
   9301 // in the rare cases where CheckICE actually cares about the evaluated
   9302 // value, it calls into Evalute.
   9303 
   9304 namespace {
   9305 
   9306 enum ICEKind {
   9307   /// This expression is an ICE.
   9308   IK_ICE,
   9309   /// This expression is not an ICE, but if it isn't evaluated, it's
   9310   /// a legal subexpression for an ICE. This return value is used to handle
   9311   /// the comma operator in C99 mode, and non-constant subexpressions.
   9312   IK_ICEIfUnevaluated,
   9313   /// This expression is not an ICE, and is not a legal subexpression for one.
   9314   IK_NotICE
   9315 };
   9316 
   9317 struct ICEDiag {
   9318   ICEKind Kind;
   9319   SourceLocation Loc;
   9320 
   9321   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
   9322 };
   9323 
   9324 }
   9325 
   9326 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
   9327 
   9328 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
   9329 
   9330 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
   9331   Expr::EvalResult EVResult;
   9332   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
   9333       !EVResult.Val.isInt())
   9334     return ICEDiag(IK_NotICE, E->getLocStart());
   9335 
   9336   return NoDiag();
   9337 }
   9338 
   9339 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
   9340   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
   9341   if (!E->getType()->isIntegralOrEnumerationType())
   9342     return ICEDiag(IK_NotICE, E->getLocStart());
   9343 
   9344   switch (E->getStmtClass()) {
   9345 #define ABSTRACT_STMT(Node)
   9346 #define STMT(Node, Base) case Expr::Node##Class:
   9347 #define EXPR(Node, Base)
   9348 #include "clang/AST/StmtNodes.inc"
   9349   case Expr::PredefinedExprClass:
   9350   case Expr::FloatingLiteralClass:
   9351   case Expr::ImaginaryLiteralClass:
   9352   case Expr::StringLiteralClass:
   9353   case Expr::ArraySubscriptExprClass:
   9354   case Expr::OMPArraySectionExprClass:
   9355   case Expr::MemberExprClass:
   9356   case Expr::CompoundAssignOperatorClass:
   9357   case Expr::CompoundLiteralExprClass:
   9358   case Expr::ExtVectorElementExprClass:
   9359   case Expr::DesignatedInitExprClass:
   9360   case Expr::NoInitExprClass:
   9361   case Expr::DesignatedInitUpdateExprClass:
   9362   case Expr::ImplicitValueInitExprClass:
   9363   case Expr::ParenListExprClass:
   9364   case Expr::VAArgExprClass:
   9365   case Expr::AddrLabelExprClass:
   9366   case Expr::StmtExprClass:
   9367   case Expr::CXXMemberCallExprClass:
   9368   case Expr::CUDAKernelCallExprClass:
   9369   case Expr::CXXDynamicCastExprClass:
   9370   case Expr::CXXTypeidExprClass:
   9371   case Expr::CXXUuidofExprClass:
   9372   case Expr::MSPropertyRefExprClass:
   9373   case Expr::MSPropertySubscriptExprClass:
   9374   case Expr::CXXNullPtrLiteralExprClass:
   9375   case Expr::UserDefinedLiteralClass:
   9376   case Expr::CXXThisExprClass:
   9377   case Expr::CXXThrowExprClass:
   9378   case Expr::CXXNewExprClass:
   9379   case Expr::CXXDeleteExprClass:
   9380   case Expr::CXXPseudoDestructorExprClass:
   9381   case Expr::UnresolvedLookupExprClass:
   9382   case Expr::TypoExprClass:
   9383   case Expr::DependentScopeDeclRefExprClass:
   9384   case Expr::CXXConstructExprClass:
   9385   case Expr::CXXInheritedCtorInitExprClass:
   9386   case Expr::CXXStdInitializerListExprClass:
   9387   case Expr::CXXBindTemporaryExprClass:
   9388   case Expr::ExprWithCleanupsClass:
   9389   case Expr::CXXTemporaryObjectExprClass:
   9390   case Expr::CXXUnresolvedConstructExprClass:
   9391   case Expr::CXXDependentScopeMemberExprClass:
   9392   case Expr::UnresolvedMemberExprClass:
   9393   case Expr::ObjCStringLiteralClass:
   9394   case Expr::ObjCBoxedExprClass:
   9395   case Expr::ObjCArrayLiteralClass:
   9396   case Expr::ObjCDictionaryLiteralClass:
   9397   case Expr::ObjCEncodeExprClass:
   9398   case Expr::ObjCMessageExprClass:
   9399   case Expr::ObjCSelectorExprClass:
   9400   case Expr::ObjCProtocolExprClass:
   9401   case Expr::ObjCIvarRefExprClass:
   9402   case Expr::ObjCPropertyRefExprClass:
   9403   case Expr::ObjCSubscriptRefExprClass:
   9404   case Expr::ObjCIsaExprClass:
   9405   case Expr::ShuffleVectorExprClass:
   9406   case Expr::ConvertVectorExprClass:
   9407   case Expr::BlockExprClass:
   9408   case Expr::NoStmtClass:
   9409   case Expr::OpaqueValueExprClass:
   9410   case Expr::PackExpansionExprClass:
   9411   case Expr::SubstNonTypeTemplateParmPackExprClass:
   9412   case Expr::FunctionParmPackExprClass:
   9413   case Expr::AsTypeExprClass:
   9414   case Expr::ObjCIndirectCopyRestoreExprClass:
   9415   case Expr::MaterializeTemporaryExprClass:
   9416   case Expr::PseudoObjectExprClass:
   9417   case Expr::AtomicExprClass:
   9418   case Expr::LambdaExprClass:
   9419   case Expr::CXXFoldExprClass:
   9420   case Expr::CoawaitExprClass:
   9421   case Expr::CoyieldExprClass:
   9422     return ICEDiag(IK_NotICE, E->getLocStart());
   9423 
   9424   case Expr::InitListExprClass: {
   9425     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
   9426     // form "T x = { a };" is equivalent to "T x = a;".
   9427     // Unless we're initializing a reference, T is a scalar as it is known to be
   9428     // of integral or enumeration type.
   9429     if (E->isRValue())
   9430       if (cast<InitListExpr>(E)->getNumInits() == 1)
   9431         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
   9432     return ICEDiag(IK_NotICE, E->getLocStart());
   9433   }
   9434 
   9435   case Expr::SizeOfPackExprClass:
   9436   case Expr::GNUNullExprClass:
   9437     // GCC considers the GNU __null value to be an integral constant expression.
   9438     return NoDiag();
   9439 
   9440   case Expr::SubstNonTypeTemplateParmExprClass:
   9441     return
   9442       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
   9443 
   9444   case Expr::ParenExprClass:
   9445     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
   9446   case Expr::GenericSelectionExprClass:
   9447     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
   9448   case Expr::IntegerLiteralClass:
   9449   case Expr::CharacterLiteralClass:
   9450   case Expr::ObjCBoolLiteralExprClass:
   9451   case Expr::CXXBoolLiteralExprClass:
   9452   case Expr::CXXScalarValueInitExprClass:
   9453   case Expr::TypeTraitExprClass:
   9454   case Expr::ArrayTypeTraitExprClass:
   9455   case Expr::ExpressionTraitExprClass:
   9456   case Expr::CXXNoexceptExprClass:
   9457     return NoDiag();
   9458   case Expr::CallExprClass:
   9459   case Expr::CXXOperatorCallExprClass: {
   9460     // C99 6.6/3 allows function calls within unevaluated subexpressions of
   9461     // constant expressions, but they can never be ICEs because an ICE cannot
   9462     // contain an operand of (pointer to) function type.
   9463     const CallExpr *CE = cast<CallExpr>(E);
   9464     if (CE->getBuiltinCallee())
   9465       return CheckEvalInICE(E, Ctx);
   9466     return ICEDiag(IK_NotICE, E->getLocStart());
   9467   }
   9468   case Expr::DeclRefExprClass: {
   9469     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
   9470       return NoDiag();
   9471     const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
   9472     if (Ctx.getLangOpts().CPlusPlus &&
   9473         D && IsConstNonVolatile(D->getType())) {
   9474       // Parameter variables are never constants.  Without this check,
   9475       // getAnyInitializer() can find a default argument, which leads
   9476       // to chaos.
   9477       if (isa<ParmVarDecl>(D))
   9478         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
   9479 
   9480       // C++ 7.1.5.1p2
   9481       //   A variable of non-volatile const-qualified integral or enumeration
   9482       //   type initialized by an ICE can be used in ICEs.
   9483       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
   9484         if (!Dcl->getType()->isIntegralOrEnumerationType())
   9485           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
   9486 
   9487         const VarDecl *VD;
   9488         // Look for a declaration of this variable that has an initializer, and
   9489         // check whether it is an ICE.
   9490         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
   9491           return NoDiag();
   9492         else
   9493           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
   9494       }
   9495     }
   9496     return ICEDiag(IK_NotICE, E->getLocStart());
   9497   }
   9498   case Expr::UnaryOperatorClass: {
   9499     const UnaryOperator *Exp = cast<UnaryOperator>(E);
   9500     switch (Exp->getOpcode()) {
   9501     case UO_PostInc:
   9502     case UO_PostDec:
   9503     case UO_PreInc:
   9504     case UO_PreDec:
   9505     case UO_AddrOf:
   9506     case UO_Deref:
   9507     case UO_Coawait:
   9508       // C99 6.6/3 allows increment and decrement within unevaluated
   9509       // subexpressions of constant expressions, but they can never be ICEs
   9510       // because an ICE cannot contain an lvalue operand.
   9511       return ICEDiag(IK_NotICE, E->getLocStart());
   9512     case UO_Extension:
   9513     case UO_LNot:
   9514     case UO_Plus:
   9515     case UO_Minus:
   9516     case UO_Not:
   9517     case UO_Real:
   9518     case UO_Imag:
   9519       return CheckICE(Exp->getSubExpr(), Ctx);
   9520     }
   9521 
   9522     // OffsetOf falls through here.
   9523   }
   9524   case Expr::OffsetOfExprClass: {
   9525     // Note that per C99, offsetof must be an ICE. And AFAIK, using
   9526     // EvaluateAsRValue matches the proposed gcc behavior for cases like
   9527     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
   9528     // compliance: we should warn earlier for offsetof expressions with
   9529     // array subscripts that aren't ICEs, and if the array subscripts
   9530     // are ICEs, the value of the offsetof must be an integer constant.
   9531     return CheckEvalInICE(E, Ctx);
   9532   }
   9533   case Expr::UnaryExprOrTypeTraitExprClass: {
   9534     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
   9535     if ((Exp->getKind() ==  UETT_SizeOf) &&
   9536         Exp->getTypeOfArgument()->isVariableArrayType())
   9537       return ICEDiag(IK_NotICE, E->getLocStart());
   9538     return NoDiag();
   9539   }
   9540   case Expr::BinaryOperatorClass: {
   9541     const BinaryOperator *Exp = cast<BinaryOperator>(E);
   9542     switch (Exp->getOpcode()) {
   9543     case BO_PtrMemD:
   9544     case BO_PtrMemI:
   9545     case BO_Assign:
   9546     case BO_MulAssign:
   9547     case BO_DivAssign:
   9548     case BO_RemAssign:
   9549     case BO_AddAssign:
   9550     case BO_SubAssign:
   9551     case BO_ShlAssign:
   9552     case BO_ShrAssign:
   9553     case BO_AndAssign:
   9554     case BO_XorAssign:
   9555     case BO_OrAssign:
   9556       // C99 6.6/3 allows assignments within unevaluated subexpressions of
   9557       // constant expressions, but they can never be ICEs because an ICE cannot
   9558       // contain an lvalue operand.
   9559       return ICEDiag(IK_NotICE, E->getLocStart());
   9560 
   9561     case BO_Mul:
   9562     case BO_Div:
   9563     case BO_Rem:
   9564     case BO_Add:
   9565     case BO_Sub:
   9566     case BO_Shl:
   9567     case BO_Shr:
   9568     case BO_LT:
   9569     case BO_GT:
   9570     case BO_LE:
   9571     case BO_GE:
   9572     case BO_EQ:
   9573     case BO_NE:
   9574     case BO_And:
   9575     case BO_Xor:
   9576     case BO_Or:
   9577     case BO_Comma: {
   9578       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
   9579       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
   9580       if (Exp->getOpcode() == BO_Div ||
   9581           Exp->getOpcode() == BO_Rem) {
   9582         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
   9583         // we don't evaluate one.
   9584         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
   9585           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
   9586           if (REval == 0)
   9587             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
   9588           if (REval.isSigned() && REval.isAllOnesValue()) {
   9589             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
   9590             if (LEval.isMinSignedValue())
   9591               return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
   9592           }
   9593         }
   9594       }
   9595       if (Exp->getOpcode() == BO_Comma) {
   9596         if (Ctx.getLangOpts().C99) {
   9597           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
   9598           // if it isn't evaluated.
   9599           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
   9600             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
   9601         } else {
   9602           // In both C89 and C++, commas in ICEs are illegal.
   9603           return ICEDiag(IK_NotICE, E->getLocStart());
   9604         }
   9605       }
   9606       return Worst(LHSResult, RHSResult);
   9607     }
   9608     case BO_LAnd:
   9609     case BO_LOr: {
   9610       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
   9611       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
   9612       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
   9613         // Rare case where the RHS has a comma "side-effect"; we need
   9614         // to actually check the condition to see whether the side
   9615         // with the comma is evaluated.
   9616         if ((Exp->getOpcode() == BO_LAnd) !=
   9617             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
   9618           return RHSResult;
   9619         return NoDiag();
   9620       }
   9621 
   9622       return Worst(LHSResult, RHSResult);
   9623     }
   9624     }
   9625   }
   9626   case Expr::ImplicitCastExprClass:
   9627   case Expr::CStyleCastExprClass:
   9628   case Expr::CXXFunctionalCastExprClass:
   9629   case Expr::CXXStaticCastExprClass:
   9630   case Expr::CXXReinterpretCastExprClass:
   9631   case Expr::CXXConstCastExprClass:
   9632   case Expr::ObjCBridgedCastExprClass: {
   9633     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
   9634     if (isa<ExplicitCastExpr>(E)) {
   9635       if (const FloatingLiteral *FL
   9636             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
   9637         unsigned DestWidth = Ctx.getIntWidth(E->getType());
   9638         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
   9639         APSInt IgnoredVal(DestWidth, !DestSigned);
   9640         bool Ignored;
   9641         // If the value does not fit in the destination type, the behavior is
   9642         // undefined, so we are not required to treat it as a constant
   9643         // expression.
   9644         if (FL->getValue().convertToInteger(IgnoredVal,
   9645                                             llvm::APFloat::rmTowardZero,
   9646                                             &Ignored) & APFloat::opInvalidOp)
   9647           return ICEDiag(IK_NotICE, E->getLocStart());
   9648         return NoDiag();
   9649       }
   9650     }
   9651     switch (cast<CastExpr>(E)->getCastKind()) {
   9652     case CK_LValueToRValue:
   9653     case CK_AtomicToNonAtomic:
   9654     case CK_NonAtomicToAtomic:
   9655     case CK_NoOp:
   9656     case CK_IntegralToBoolean:
   9657     case CK_IntegralCast:
   9658       return CheckICE(SubExpr, Ctx);
   9659     default:
   9660       return ICEDiag(IK_NotICE, E->getLocStart());
   9661     }
   9662   }
   9663   case Expr::BinaryConditionalOperatorClass: {
   9664     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
   9665     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
   9666     if (CommonResult.Kind == IK_NotICE) return CommonResult;
   9667     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
   9668     if (FalseResult.Kind == IK_NotICE) return FalseResult;
   9669     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
   9670     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
   9671         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
   9672     return FalseResult;
   9673   }
   9674   case Expr::ConditionalOperatorClass: {
   9675     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
   9676     // If the condition (ignoring parens) is a __builtin_constant_p call,
   9677     // then only the true side is actually considered in an integer constant
   9678     // expression, and it is fully evaluated.  This is an important GNU
   9679     // extension.  See GCC PR38377 for discussion.
   9680     if (const CallExpr *CallCE
   9681         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
   9682       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
   9683         return CheckEvalInICE(E, Ctx);
   9684     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
   9685     if (CondResult.Kind == IK_NotICE)
   9686       return CondResult;
   9687 
   9688     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
   9689     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
   9690 
   9691     if (TrueResult.Kind == IK_NotICE)
   9692       return TrueResult;
   9693     if (FalseResult.Kind == IK_NotICE)
   9694       return FalseResult;
   9695     if (CondResult.Kind == IK_ICEIfUnevaluated)
   9696       return CondResult;
   9697     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
   9698       return NoDiag();
   9699     // Rare case where the diagnostics depend on which side is evaluated
   9700     // Note that if we get here, CondResult is 0, and at least one of
   9701     // TrueResult and FalseResult is non-zero.
   9702     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
   9703       return FalseResult;
   9704     return TrueResult;
   9705   }
   9706   case Expr::CXXDefaultArgExprClass:
   9707     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
   9708   case Expr::CXXDefaultInitExprClass:
   9709     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
   9710   case Expr::ChooseExprClass: {
   9711     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
   9712   }
   9713   }
   9714 
   9715   llvm_unreachable("Invalid StmtClass!");
   9716 }
   9717 
   9718 /// Evaluate an expression as a C++11 integral constant expression.
   9719 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
   9720                                                     const Expr *E,
   9721                                                     llvm::APSInt *Value,
   9722                                                     SourceLocation *Loc) {
   9723   if (!E->getType()->isIntegralOrEnumerationType()) {
   9724     if (Loc) *Loc = E->getExprLoc();
   9725     return false;
   9726   }
   9727 
   9728   APValue Result;
   9729   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
   9730     return false;
   9731 
   9732   if (!Result.isInt()) {
   9733     if (Loc) *Loc = E->getExprLoc();
   9734     return false;
   9735   }
   9736 
   9737   if (Value) *Value = Result.getInt();
   9738   return true;
   9739 }
   9740 
   9741 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
   9742                                  SourceLocation *Loc) const {
   9743   if (Ctx.getLangOpts().CPlusPlus11)
   9744     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
   9745 
   9746   ICEDiag D = CheckICE(this, Ctx);
   9747   if (D.Kind != IK_ICE) {
   9748     if (Loc) *Loc = D.Loc;
   9749     return false;
   9750   }
   9751   return true;
   9752 }
   9753 
   9754 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
   9755                                  SourceLocation *Loc, bool isEvaluated) const {
   9756   if (Ctx.getLangOpts().CPlusPlus11)
   9757     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
   9758 
   9759   if (!isIntegerConstantExpr(Ctx, Loc))
   9760     return false;
   9761   // The only possible side-effects here are due to UB discovered in the
   9762   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
   9763   // required to treat the expression as an ICE, so we produce the folded
   9764   // value.
   9765   if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
   9766     llvm_unreachable("ICE cannot be evaluated!");
   9767   return true;
   9768 }
   9769 
   9770 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
   9771   return CheckICE(this, Ctx).Kind == IK_ICE;
   9772 }
   9773 
   9774 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
   9775                                SourceLocation *Loc) const {
   9776   // We support this checking in C++98 mode in order to diagnose compatibility
   9777   // issues.
   9778   assert(Ctx.getLangOpts().CPlusPlus);
   9779 
   9780   // Build evaluation settings.
   9781   Expr::EvalStatus Status;
   9782   SmallVector<PartialDiagnosticAt, 8> Diags;
   9783   Status.Diag = &Diags;
   9784   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
   9785 
   9786   APValue Scratch;
   9787   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
   9788 
   9789   if (!Diags.empty()) {
   9790     IsConstExpr = false;
   9791     if (Loc) *Loc = Diags[0].first;
   9792   } else if (!IsConstExpr) {
   9793     // FIXME: This shouldn't happen.
   9794     if (Loc) *Loc = getExprLoc();
   9795   }
   9796 
   9797   return IsConstExpr;
   9798 }
   9799 
   9800 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
   9801                                     const FunctionDecl *Callee,
   9802                                     ArrayRef<const Expr*> Args) const {
   9803   Expr::EvalStatus Status;
   9804   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
   9805 
   9806   ArgVector ArgValues(Args.size());
   9807   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
   9808        I != E; ++I) {
   9809     if ((*I)->isValueDependent() ||
   9810         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
   9811       // If evaluation fails, throw away the argument entirely.
   9812       ArgValues[I - Args.begin()] = APValue();
   9813     if (Info.EvalStatus.HasSideEffects)
   9814       return false;
   9815   }
   9816 
   9817   // Build fake call to Callee.
   9818   CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
   9819                        ArgValues.data());
   9820   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
   9821 }
   9822 
   9823 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
   9824                                    SmallVectorImpl<
   9825                                      PartialDiagnosticAt> &Diags) {
   9826   // FIXME: It would be useful to check constexpr function templates, but at the
   9827   // moment the constant expression evaluator cannot cope with the non-rigorous
   9828   // ASTs which we build for dependent expressions.
   9829   if (FD->isDependentContext())
   9830     return true;
   9831 
   9832   Expr::EvalStatus Status;
   9833   Status.Diag = &Diags;
   9834 
   9835   EvalInfo Info(FD->getASTContext(), Status,
   9836                 EvalInfo::EM_PotentialConstantExpression);
   9837 
   9838   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
   9839   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
   9840 
   9841   // Fabricate an arbitrary expression on the stack and pretend that it
   9842   // is a temporary being used as the 'this' pointer.
   9843   LValue This;
   9844   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
   9845   This.set(&VIE, Info.CurrentCall->Index);
   9846 
   9847   ArrayRef<const Expr*> Args;
   9848 
   9849   APValue Scratch;
   9850   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
   9851     // Evaluate the call as a constant initializer, to allow the construction
   9852     // of objects of non-literal types.
   9853     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
   9854     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
   9855   } else {
   9856     SourceLocation Loc = FD->getLocation();
   9857     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
   9858                        Args, FD->getBody(), Info, Scratch, nullptr);
   9859   }
   9860 
   9861   return Diags.empty();
   9862 }
   9863 
   9864 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
   9865                                               const FunctionDecl *FD,
   9866                                               SmallVectorImpl<
   9867                                                 PartialDiagnosticAt> &Diags) {
   9868   Expr::EvalStatus Status;
   9869   Status.Diag = &Diags;
   9870 
   9871   EvalInfo Info(FD->getASTContext(), Status,
   9872                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
   9873 
   9874   // Fabricate a call stack frame to give the arguments a plausible cover story.
   9875   ArrayRef<const Expr*> Args;
   9876   ArgVector ArgValues(0);
   9877   bool Success = EvaluateArgs(Args, ArgValues, Info);
   9878   (void)Success;
   9879   assert(Success &&
   9880          "Failed to set up arguments for potential constant evaluation");
   9881   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
   9882 
   9883   APValue ResultScratch;
   9884   Evaluate(ResultScratch, Info, E);
   9885   return Diags.empty();
   9886 }
   9887 
   9888 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
   9889                                  unsigned Type) const {
   9890   if (!getType()->isPointerType())
   9891     return false;
   9892 
   9893   Expr::EvalStatus Status;
   9894   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
   9895   return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
   9896 }
   9897