clang API Documentation

ExprConstant.cpp
Go to the documentation of this file.
00001 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Expr constant evaluator.
00011 //
00012 // Constant expression evaluation produces four main results:
00013 //
00014 //  * A success/failure flag indicating whether constant folding was successful.
00015 //    This is the 'bool' return value used by most of the code in this file. A
00016 //    'false' return value indicates that constant folding has failed, and any
00017 //    appropriate diagnostic has already been produced.
00018 //
00019 //  * An evaluated result, valid only if constant folding has not failed.
00020 //
00021 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
00022 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
00023 //    where it is possible to determine the evaluated result regardless.
00024 //
00025 //  * A set of notes indicating why the evaluation was not a constant expression
00026 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
00027 //    too, why the expression could not be folded.
00028 //
00029 // If we are checking for a potential constant expression, failure to constant
00030 // fold a potential constant sub-expression will be indicated by a 'false'
00031 // return value (the expression could not be folded) and no diagnostic (the
00032 // expression is not necessarily non-constant).
00033 //
00034 //===----------------------------------------------------------------------===//
00035 
00036 #include "clang/AST/APValue.h"
00037 #include "clang/AST/ASTContext.h"
00038 #include "clang/AST/ASTDiagnostic.h"
00039 #include "clang/AST/CharUnits.h"
00040 #include "clang/AST/Expr.h"
00041 #include "clang/AST/RecordLayout.h"
00042 #include "clang/AST/StmtVisitor.h"
00043 #include "clang/AST/TypeLoc.h"
00044 #include "clang/Basic/Builtins.h"
00045 #include "clang/Basic/TargetInfo.h"
00046 #include "llvm/ADT/SmallString.h"
00047 #include "llvm/Support/raw_ostream.h"
00048 #include <cstring>
00049 #include <functional>
00050 
00051 using namespace clang;
00052 using llvm::APSInt;
00053 using llvm::APFloat;
00054 
00055 static bool IsGlobalLValue(APValue::LValueBase B);
00056 
00057 namespace {
00058   struct LValue;
00059   struct CallStackFrame;
00060   struct EvalInfo;
00061 
00062   static QualType getType(APValue::LValueBase B) {
00063     if (!B) return QualType();
00064     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
00065       return D->getType();
00066 
00067     const Expr *Base = B.get<const Expr*>();
00068 
00069     // For a materialized temporary, the type of the temporary we materialized
00070     // may not be the type of the expression.
00071     if (const MaterializeTemporaryExpr *MTE =
00072             dyn_cast<MaterializeTemporaryExpr>(Base)) {
00073       SmallVector<const Expr *, 2> CommaLHSs;
00074       SmallVector<SubobjectAdjustment, 2> Adjustments;
00075       const Expr *Temp = MTE->GetTemporaryExpr();
00076       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
00077                                                                Adjustments);
00078       // Keep any cv-qualifiers from the reference if we generated a temporary
00079       // for it.
00080       if (Inner != Temp)
00081         return Inner->getType();
00082     }
00083 
00084     return Base->getType();
00085   }
00086 
00087   /// Get an LValue path entry, which is known to not be an array index, as a
00088   /// field or base class.
00089   static
00090   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
00091     APValue::BaseOrMemberType Value;
00092     Value.setFromOpaqueValue(E.BaseOrMember);
00093     return Value;
00094   }
00095 
00096   /// Get an LValue path entry, which is known to not be an array index, as a
00097   /// field declaration.
00098   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
00099     return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
00100   }
00101   /// Get an LValue path entry, which is known to not be an array index, as a
00102   /// base class declaration.
00103   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
00104     return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
00105   }
00106   /// Determine whether this LValue path entry for a base class names a virtual
00107   /// base class.
00108   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
00109     return getAsBaseOrMember(E).getInt();
00110   }
00111 
00112   /// Find the path length and type of the most-derived subobject in the given
00113   /// path, and find the size of the containing array, if any.
00114   static
00115   unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
00116                                     ArrayRef<APValue::LValuePathEntry> Path,
00117                                     uint64_t &ArraySize, QualType &Type) {
00118     unsigned MostDerivedLength = 0;
00119     Type = Base;
00120     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
00121       if (Type->isArrayType()) {
00122         const ConstantArrayType *CAT =
00123           cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
00124         Type = CAT->getElementType();
00125         ArraySize = CAT->getSize().getZExtValue();
00126         MostDerivedLength = I + 1;
00127       } else if (Type->isAnyComplexType()) {
00128         const ComplexType *CT = Type->castAs<ComplexType>();
00129         Type = CT->getElementType();
00130         ArraySize = 2;
00131         MostDerivedLength = I + 1;
00132       } else if (const FieldDecl *FD = getAsField(Path[I])) {
00133         Type = FD->getType();
00134         ArraySize = 0;
00135         MostDerivedLength = I + 1;
00136       } else {
00137         // Path[I] describes a base class.
00138         ArraySize = 0;
00139       }
00140     }
00141     return MostDerivedLength;
00142   }
00143 
00144   // The order of this enum is important for diagnostics.
00145   enum CheckSubobjectKind {
00146     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
00147     CSK_This, CSK_Real, CSK_Imag
00148   };
00149 
00150   /// A path from a glvalue to a subobject of that glvalue.
00151   struct SubobjectDesignator {
00152     /// True if the subobject was named in a manner not supported by C++11. Such
00153     /// lvalues can still be folded, but they are not core constant expressions
00154     /// and we cannot perform lvalue-to-rvalue conversions on them.
00155     bool Invalid : 1;
00156 
00157     /// Is this a pointer one past the end of an object?
00158     bool IsOnePastTheEnd : 1;
00159 
00160     /// The length of the path to the most-derived object of which this is a
00161     /// subobject.
00162     unsigned MostDerivedPathLength : 30;
00163 
00164     /// The size of the array of which the most-derived object is an element, or
00165     /// 0 if the most-derived object is not an array element.
00166     uint64_t MostDerivedArraySize;
00167 
00168     /// The type of the most derived object referred to by this address.
00169     QualType MostDerivedType;
00170 
00171     typedef APValue::LValuePathEntry PathEntry;
00172 
00173     /// The entries on the path from the glvalue to the designated subobject.
00174     SmallVector<PathEntry, 8> Entries;
00175 
00176     SubobjectDesignator() : Invalid(true) {}
00177 
00178     explicit SubobjectDesignator(QualType T)
00179       : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
00180         MostDerivedArraySize(0), MostDerivedType(T) {}
00181 
00182     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
00183       : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
00184         MostDerivedPathLength(0), MostDerivedArraySize(0) {
00185       if (!Invalid) {
00186         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
00187         ArrayRef<PathEntry> VEntries = V.getLValuePath();
00188         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
00189         if (V.getLValueBase())
00190           MostDerivedPathLength =
00191               findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
00192                                        V.getLValuePath(), MostDerivedArraySize,
00193                                        MostDerivedType);
00194       }
00195     }
00196 
00197     void setInvalid() {
00198       Invalid = true;
00199       Entries.clear();
00200     }
00201 
00202     /// Determine whether this is a one-past-the-end pointer.
00203     bool isOnePastTheEnd() const {
00204       assert(!Invalid);
00205       if (IsOnePastTheEnd)
00206         return true;
00207       if (MostDerivedArraySize &&
00208           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
00209         return true;
00210       return false;
00211     }
00212 
00213     /// Check that this refers to a valid subobject.
00214     bool isValidSubobject() const {
00215       if (Invalid)
00216         return false;
00217       return !isOnePastTheEnd();
00218     }
00219     /// Check that this refers to a valid subobject, and if not, produce a
00220     /// relevant diagnostic and set the designator as invalid.
00221     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
00222 
00223     /// Update this designator to refer to the first element within this array.
00224     void addArrayUnchecked(const ConstantArrayType *CAT) {
00225       PathEntry Entry;
00226       Entry.ArrayIndex = 0;
00227       Entries.push_back(Entry);
00228 
00229       // This is a most-derived object.
00230       MostDerivedType = CAT->getElementType();
00231       MostDerivedArraySize = CAT->getSize().getZExtValue();
00232       MostDerivedPathLength = Entries.size();
00233     }
00234     /// Update this designator to refer to the given base or member of this
00235     /// object.
00236     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
00237       PathEntry Entry;
00238       APValue::BaseOrMemberType Value(D, Virtual);
00239       Entry.BaseOrMember = Value.getOpaqueValue();
00240       Entries.push_back(Entry);
00241 
00242       // If this isn't a base class, it's a new most-derived object.
00243       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
00244         MostDerivedType = FD->getType();
00245         MostDerivedArraySize = 0;
00246         MostDerivedPathLength = Entries.size();
00247       }
00248     }
00249     /// Update this designator to refer to the given complex component.
00250     void addComplexUnchecked(QualType EltTy, bool Imag) {
00251       PathEntry Entry;
00252       Entry.ArrayIndex = Imag;
00253       Entries.push_back(Entry);
00254 
00255       // This is technically a most-derived object, though in practice this
00256       // is unlikely to matter.
00257       MostDerivedType = EltTy;
00258       MostDerivedArraySize = 2;
00259       MostDerivedPathLength = Entries.size();
00260     }
00261     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
00262     /// Add N to the address of this subobject.
00263     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
00264       if (Invalid) return;
00265       if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
00266         Entries.back().ArrayIndex += N;
00267         if (Entries.back().ArrayIndex > MostDerivedArraySize) {
00268           diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
00269           setInvalid();
00270         }
00271         return;
00272       }
00273       // [expr.add]p4: For the purposes of these operators, a pointer to a
00274       // nonarray object behaves the same as a pointer to the first element of
00275       // an array of length one with the type of the object as its element type.
00276       if (IsOnePastTheEnd && N == (uint64_t)-1)
00277         IsOnePastTheEnd = false;
00278       else if (!IsOnePastTheEnd && N == 1)
00279         IsOnePastTheEnd = true;
00280       else if (N != 0) {
00281         diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
00282         setInvalid();
00283       }
00284     }
00285   };
00286 
00287   /// A stack frame in the constexpr call stack.
00288   struct CallStackFrame {
00289     EvalInfo &Info;
00290 
00291     /// Parent - The caller of this stack frame.
00292     CallStackFrame *Caller;
00293 
00294     /// CallLoc - The location of the call expression for this call.
00295     SourceLocation CallLoc;
00296 
00297     /// Callee - The function which was called.
00298     const FunctionDecl *Callee;
00299 
00300     /// Index - The call index of this call.
00301     unsigned Index;
00302 
00303     /// This - The binding for the this pointer in this call, if any.
00304     const LValue *This;
00305 
00306     /// Arguments - Parameter bindings for this function call, indexed by
00307     /// parameters' function scope indices.
00308     APValue *Arguments;
00309 
00310     // Note that we intentionally use std::map here so that references to
00311     // values are stable.
00312     typedef std::map<const void*, APValue> MapTy;
00313     typedef MapTy::const_iterator temp_iterator;
00314     /// Temporaries - Temporary lvalues materialized within this stack frame.
00315     MapTy Temporaries;
00316 
00317     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
00318                    const FunctionDecl *Callee, const LValue *This,
00319                    APValue *Arguments);
00320     ~CallStackFrame();
00321 
00322     APValue *getTemporary(const void *Key) {
00323       MapTy::iterator I = Temporaries.find(Key);
00324       return I == Temporaries.end() ? nullptr : &I->second;
00325     }
00326     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
00327   };
00328 
00329   /// Temporarily override 'this'.
00330   class ThisOverrideRAII {
00331   public:
00332     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
00333         : Frame(Frame), OldThis(Frame.This) {
00334       if (Enable)
00335         Frame.This = NewThis;
00336     }
00337     ~ThisOverrideRAII() {
00338       Frame.This = OldThis;
00339     }
00340   private:
00341     CallStackFrame &Frame;
00342     const LValue *OldThis;
00343   };
00344 
00345   /// A partial diagnostic which we might know in advance that we are not going
00346   /// to emit.
00347   class OptionalDiagnostic {
00348     PartialDiagnostic *Diag;
00349 
00350   public:
00351     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
00352       : Diag(Diag) {}
00353 
00354     template<typename T>
00355     OptionalDiagnostic &operator<<(const T &v) {
00356       if (Diag)
00357         *Diag << v;
00358       return *this;
00359     }
00360 
00361     OptionalDiagnostic &operator<<(const APSInt &I) {
00362       if (Diag) {
00363         SmallVector<char, 32> Buffer;
00364         I.toString(Buffer);
00365         *Diag << StringRef(Buffer.data(), Buffer.size());
00366       }
00367       return *this;
00368     }
00369 
00370     OptionalDiagnostic &operator<<(const APFloat &F) {
00371       if (Diag) {
00372         // FIXME: Force the precision of the source value down so we don't
00373         // print digits which are usually useless (we don't really care here if
00374         // we truncate a digit by accident in edge cases).  Ideally,
00375         // APFloat::toString would automatically print the shortest 
00376         // representation which rounds to the correct value, but it's a bit
00377         // tricky to implement.
00378         unsigned precision =
00379             llvm::APFloat::semanticsPrecision(F.getSemantics());
00380         precision = (precision * 59 + 195) / 196;
00381         SmallVector<char, 32> Buffer;
00382         F.toString(Buffer, precision);
00383         *Diag << StringRef(Buffer.data(), Buffer.size());
00384       }
00385       return *this;
00386     }
00387   };
00388 
00389   /// A cleanup, and a flag indicating whether it is lifetime-extended.
00390   class Cleanup {
00391     llvm::PointerIntPair<APValue*, 1, bool> Value;
00392 
00393   public:
00394     Cleanup(APValue *Val, bool IsLifetimeExtended)
00395         : Value(Val, IsLifetimeExtended) {}
00396 
00397     bool isLifetimeExtended() const { return Value.getInt(); }
00398     void endLifetime() {
00399       *Value.getPointer() = APValue();
00400     }
00401   };
00402 
00403   /// EvalInfo - This is a private struct used by the evaluator to capture
00404   /// information about a subexpression as it is folded.  It retains information
00405   /// about the AST context, but also maintains information about the folded
00406   /// expression.
00407   ///
00408   /// If an expression could be evaluated, it is still possible it is not a C
00409   /// "integer constant expression" or constant expression.  If not, this struct
00410   /// captures information about how and why not.
00411   ///
00412   /// One bit of information passed *into* the request for constant folding
00413   /// indicates whether the subexpression is "evaluated" or not according to C
00414   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
00415   /// evaluate the expression regardless of what the RHS is, but C only allows
00416   /// certain things in certain situations.
00417   struct EvalInfo {
00418     ASTContext &Ctx;
00419 
00420     /// EvalStatus - Contains information about the evaluation.
00421     Expr::EvalStatus &EvalStatus;
00422 
00423     /// CurrentCall - The top of the constexpr call stack.
00424     CallStackFrame *CurrentCall;
00425 
00426     /// CallStackDepth - The number of calls in the call stack right now.
00427     unsigned CallStackDepth;
00428 
00429     /// NextCallIndex - The next call index to assign.
00430     unsigned NextCallIndex;
00431 
00432     /// StepsLeft - The remaining number of evaluation steps we're permitted
00433     /// to perform. This is essentially a limit for the number of statements
00434     /// we will evaluate.
00435     unsigned StepsLeft;
00436 
00437     /// BottomFrame - The frame in which evaluation started. This must be
00438     /// initialized after CurrentCall and CallStackDepth.
00439     CallStackFrame BottomFrame;
00440 
00441     /// A stack of values whose lifetimes end at the end of some surrounding
00442     /// evaluation frame.
00443     llvm::SmallVector<Cleanup, 16> CleanupStack;
00444 
00445     /// EvaluatingDecl - This is the declaration whose initializer is being
00446     /// evaluated, if any.
00447     APValue::LValueBase EvaluatingDecl;
00448 
00449     /// EvaluatingDeclValue - This is the value being constructed for the
00450     /// declaration whose initializer is being evaluated, if any.
00451     APValue *EvaluatingDeclValue;
00452 
00453     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
00454     /// notes attached to it will also be stored, otherwise they will not be.
00455     bool HasActiveDiagnostic;
00456 
00457     enum EvaluationMode {
00458       /// Evaluate as a constant expression. Stop if we find that the expression
00459       /// is not a constant expression.
00460       EM_ConstantExpression,
00461 
00462       /// Evaluate as a potential constant expression. Keep going if we hit a
00463       /// construct that we can't evaluate yet (because we don't yet know the
00464       /// value of something) but stop if we hit something that could never be
00465       /// a constant expression.
00466       EM_PotentialConstantExpression,
00467 
00468       /// Fold the expression to a constant. Stop if we hit a side-effect that
00469       /// we can't model.
00470       EM_ConstantFold,
00471 
00472       /// Evaluate the expression looking for integer overflow and similar
00473       /// issues. Don't worry about side-effects, and try to visit all
00474       /// subexpressions.
00475       EM_EvaluateForOverflow,
00476 
00477       /// Evaluate in any way we know how. Don't worry about side-effects that
00478       /// can't be modeled.
00479       EM_IgnoreSideEffects,
00480 
00481       /// Evaluate as a constant expression. Stop if we find that the expression
00482       /// is not a constant expression. Some expressions can be retried in the
00483       /// optimizer if we don't constant fold them here, but in an unevaluated
00484       /// context we try to fold them immediately since the optimizer never
00485       /// gets a chance to look at it.
00486       EM_ConstantExpressionUnevaluated,
00487 
00488       /// Evaluate as a potential constant expression. Keep going if we hit a
00489       /// construct that we can't evaluate yet (because we don't yet know the
00490       /// value of something) but stop if we hit something that could never be
00491       /// a constant expression. Some expressions can be retried in the
00492       /// optimizer if we don't constant fold them here, but in an unevaluated
00493       /// context we try to fold them immediately since the optimizer never
00494       /// gets a chance to look at it.
00495       EM_PotentialConstantExpressionUnevaluated
00496     } EvalMode;
00497 
00498     /// Are we checking whether the expression is a potential constant
00499     /// expression?
00500     bool checkingPotentialConstantExpression() const {
00501       return EvalMode == EM_PotentialConstantExpression ||
00502              EvalMode == EM_PotentialConstantExpressionUnevaluated;
00503     }
00504 
00505     /// Are we checking an expression for overflow?
00506     // FIXME: We should check for any kind of undefined or suspicious behavior
00507     // in such constructs, not just overflow.
00508     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
00509 
00510     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
00511       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
00512         CallStackDepth(0), NextCallIndex(1),
00513         StepsLeft(getLangOpts().ConstexprStepLimit),
00514         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
00515         EvaluatingDecl((const ValueDecl *)nullptr),
00516         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
00517         EvalMode(Mode) {}
00518 
00519     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
00520       EvaluatingDecl = Base;
00521       EvaluatingDeclValue = &Value;
00522     }
00523 
00524     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
00525 
00526     bool CheckCallLimit(SourceLocation Loc) {
00527       // Don't perform any constexpr calls (other than the call we're checking)
00528       // when checking a potential constant expression.
00529       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
00530         return false;
00531       if (NextCallIndex == 0) {
00532         // NextCallIndex has wrapped around.
00533         Diag(Loc, diag::note_constexpr_call_limit_exceeded);
00534         return false;
00535       }
00536       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
00537         return true;
00538       Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
00539         << getLangOpts().ConstexprCallDepth;
00540       return false;
00541     }
00542 
00543     CallStackFrame *getCallFrame(unsigned CallIndex) {
00544       assert(CallIndex && "no call index in getCallFrame");
00545       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
00546       // be null in this loop.
00547       CallStackFrame *Frame = CurrentCall;
00548       while (Frame->Index > CallIndex)
00549         Frame = Frame->Caller;
00550       return (Frame->Index == CallIndex) ? Frame : nullptr;
00551     }
00552 
00553     bool nextStep(const Stmt *S) {
00554       if (!StepsLeft) {
00555         Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
00556         return false;
00557       }
00558       --StepsLeft;
00559       return true;
00560     }
00561 
00562   private:
00563     /// Add a diagnostic to the diagnostics list.
00564     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
00565       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
00566       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
00567       return EvalStatus.Diag->back().second;
00568     }
00569 
00570     /// Add notes containing a call stack to the current point of evaluation.
00571     void addCallStack(unsigned Limit);
00572 
00573   public:
00574     /// Diagnose that the evaluation cannot be folded.
00575     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
00576                               = diag::note_invalid_subexpr_in_const_expr,
00577                             unsigned ExtraNotes = 0) {
00578       if (EvalStatus.Diag) {
00579         // If we have a prior diagnostic, it will be noting that the expression
00580         // isn't a constant expression. This diagnostic is more important,
00581         // unless we require this evaluation to produce a constant expression.
00582         //
00583         // FIXME: We might want to show both diagnostics to the user in
00584         // EM_ConstantFold mode.
00585         if (!EvalStatus.Diag->empty()) {
00586           switch (EvalMode) {
00587           case EM_ConstantFold:
00588           case EM_IgnoreSideEffects:
00589           case EM_EvaluateForOverflow:
00590             if (!EvalStatus.HasSideEffects)
00591               break;
00592             // We've had side-effects; we want the diagnostic from them, not
00593             // some later problem.
00594           case EM_ConstantExpression:
00595           case EM_PotentialConstantExpression:
00596           case EM_ConstantExpressionUnevaluated:
00597           case EM_PotentialConstantExpressionUnevaluated:
00598             HasActiveDiagnostic = false;
00599             return OptionalDiagnostic();
00600           }
00601         }
00602 
00603         unsigned CallStackNotes = CallStackDepth - 1;
00604         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
00605         if (Limit)
00606           CallStackNotes = std::min(CallStackNotes, Limit + 1);
00607         if (checkingPotentialConstantExpression())
00608           CallStackNotes = 0;
00609 
00610         HasActiveDiagnostic = true;
00611         EvalStatus.Diag->clear();
00612         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
00613         addDiag(Loc, DiagId);
00614         if (!checkingPotentialConstantExpression())
00615           addCallStack(Limit);
00616         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
00617       }
00618       HasActiveDiagnostic = false;
00619       return OptionalDiagnostic();
00620     }
00621 
00622     OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
00623                               = diag::note_invalid_subexpr_in_const_expr,
00624                             unsigned ExtraNotes = 0) {
00625       if (EvalStatus.Diag)
00626         return Diag(E->getExprLoc(), DiagId, ExtraNotes);
00627       HasActiveDiagnostic = false;
00628       return OptionalDiagnostic();
00629     }
00630 
00631     /// Diagnose that the evaluation does not produce a C++11 core constant
00632     /// expression.
00633     ///
00634     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
00635     /// EM_PotentialConstantExpression mode and we produce one of these.
00636     template<typename LocArg>
00637     OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
00638                                  = diag::note_invalid_subexpr_in_const_expr,
00639                                unsigned ExtraNotes = 0) {
00640       // Don't override a previous diagnostic. Don't bother collecting
00641       // diagnostics if we're evaluating for overflow.
00642       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
00643         HasActiveDiagnostic = false;
00644         return OptionalDiagnostic();
00645       }
00646       return Diag(Loc, DiagId, ExtraNotes);
00647     }
00648 
00649     /// Add a note to a prior diagnostic.
00650     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
00651       if (!HasActiveDiagnostic)
00652         return OptionalDiagnostic();
00653       return OptionalDiagnostic(&addDiag(Loc, DiagId));
00654     }
00655 
00656     /// Add a stack of notes to a prior diagnostic.
00657     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
00658       if (HasActiveDiagnostic) {
00659         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
00660                                 Diags.begin(), Diags.end());
00661       }
00662     }
00663 
00664     /// Should we continue evaluation after encountering a side-effect that we
00665     /// couldn't model?
00666     bool keepEvaluatingAfterSideEffect() {
00667       switch (EvalMode) {
00668       case EM_PotentialConstantExpression:
00669       case EM_PotentialConstantExpressionUnevaluated:
00670       case EM_EvaluateForOverflow:
00671       case EM_IgnoreSideEffects:
00672         return true;
00673 
00674       case EM_ConstantExpression:
00675       case EM_ConstantExpressionUnevaluated:
00676       case EM_ConstantFold:
00677         return false;
00678       }
00679       llvm_unreachable("Missed EvalMode case");
00680     }
00681 
00682     /// Note that we have had a side-effect, and determine whether we should
00683     /// keep evaluating.
00684     bool noteSideEffect() {
00685       EvalStatus.HasSideEffects = true;
00686       return keepEvaluatingAfterSideEffect();
00687     }
00688 
00689     /// Should we continue evaluation as much as possible after encountering a
00690     /// construct which can't be reduced to a value?
00691     bool keepEvaluatingAfterFailure() {
00692       if (!StepsLeft)
00693         return false;
00694 
00695       switch (EvalMode) {
00696       case EM_PotentialConstantExpression:
00697       case EM_PotentialConstantExpressionUnevaluated:
00698       case EM_EvaluateForOverflow:
00699         return true;
00700 
00701       case EM_ConstantExpression:
00702       case EM_ConstantExpressionUnevaluated:
00703       case EM_ConstantFold:
00704       case EM_IgnoreSideEffects:
00705         return false;
00706       }
00707       llvm_unreachable("Missed EvalMode case");
00708     }
00709   };
00710 
00711   /// Object used to treat all foldable expressions as constant expressions.
00712   struct FoldConstant {
00713     EvalInfo &Info;
00714     bool Enabled;
00715     bool HadNoPriorDiags;
00716     EvalInfo::EvaluationMode OldMode;
00717 
00718     explicit FoldConstant(EvalInfo &Info, bool Enabled)
00719       : Info(Info),
00720         Enabled(Enabled),
00721         HadNoPriorDiags(Info.EvalStatus.Diag &&
00722                         Info.EvalStatus.Diag->empty() &&
00723                         !Info.EvalStatus.HasSideEffects),
00724         OldMode(Info.EvalMode) {
00725       if (Enabled &&
00726           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
00727            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
00728         Info.EvalMode = EvalInfo::EM_ConstantFold;
00729     }
00730     void keepDiagnostics() { Enabled = false; }
00731     ~FoldConstant() {
00732       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
00733           !Info.EvalStatus.HasSideEffects)
00734         Info.EvalStatus.Diag->clear();
00735       Info.EvalMode = OldMode;
00736     }
00737   };
00738 
00739   /// RAII object used to suppress diagnostics and side-effects from a
00740   /// speculative evaluation.
00741   class SpeculativeEvaluationRAII {
00742     EvalInfo &Info;
00743     Expr::EvalStatus Old;
00744 
00745   public:
00746     SpeculativeEvaluationRAII(EvalInfo &Info,
00747                         SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
00748       : Info(Info), Old(Info.EvalStatus) {
00749       Info.EvalStatus.Diag = NewDiag;
00750       // If we're speculatively evaluating, we may have skipped over some
00751       // evaluations and missed out a side effect.
00752       Info.EvalStatus.HasSideEffects = true;
00753     }
00754     ~SpeculativeEvaluationRAII() {
00755       Info.EvalStatus = Old;
00756     }
00757   };
00758 
00759   /// RAII object wrapping a full-expression or block scope, and handling
00760   /// the ending of the lifetime of temporaries created within it.
00761   template<bool IsFullExpression>
00762   class ScopeRAII {
00763     EvalInfo &Info;
00764     unsigned OldStackSize;
00765   public:
00766     ScopeRAII(EvalInfo &Info)
00767         : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
00768     ~ScopeRAII() {
00769       // Body moved to a static method to encourage the compiler to inline away
00770       // instances of this class.
00771       cleanup(Info, OldStackSize);
00772     }
00773   private:
00774     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
00775       unsigned NewEnd = OldStackSize;
00776       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
00777            I != N; ++I) {
00778         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
00779           // Full-expression cleanup of a lifetime-extended temporary: nothing
00780           // to do, just move this cleanup to the right place in the stack.
00781           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
00782           ++NewEnd;
00783         } else {
00784           // End the lifetime of the object.
00785           Info.CleanupStack[I].endLifetime();
00786         }
00787       }
00788       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
00789                               Info.CleanupStack.end());
00790     }
00791   };
00792   typedef ScopeRAII<false> BlockScopeRAII;
00793   typedef ScopeRAII<true> FullExpressionRAII;
00794 }
00795 
00796 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
00797                                          CheckSubobjectKind CSK) {
00798   if (Invalid)
00799     return false;
00800   if (isOnePastTheEnd()) {
00801     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
00802       << CSK;
00803     setInvalid();
00804     return false;
00805   }
00806   return true;
00807 }
00808 
00809 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
00810                                                     const Expr *E, uint64_t N) {
00811   if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
00812     Info.CCEDiag(E, diag::note_constexpr_array_index)
00813       << static_cast<int>(N) << /*array*/ 0
00814       << static_cast<unsigned>(MostDerivedArraySize);
00815   else
00816     Info.CCEDiag(E, diag::note_constexpr_array_index)
00817       << static_cast<int>(N) << /*non-array*/ 1;
00818   setInvalid();
00819 }
00820 
00821 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
00822                                const FunctionDecl *Callee, const LValue *This,
00823                                APValue *Arguments)
00824     : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
00825       Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
00826   Info.CurrentCall = this;
00827   ++Info.CallStackDepth;
00828 }
00829 
00830 CallStackFrame::~CallStackFrame() {
00831   assert(Info.CurrentCall == this && "calls retired out of order");
00832   --Info.CallStackDepth;
00833   Info.CurrentCall = Caller;
00834 }
00835 
00836 APValue &CallStackFrame::createTemporary(const void *Key,
00837                                          bool IsLifetimeExtended) {
00838   APValue &Result = Temporaries[Key];
00839   assert(Result.isUninit() && "temporary created multiple times");
00840   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
00841   return Result;
00842 }
00843 
00844 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
00845 
00846 void EvalInfo::addCallStack(unsigned Limit) {
00847   // Determine which calls to skip, if any.
00848   unsigned ActiveCalls = CallStackDepth - 1;
00849   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
00850   if (Limit && Limit < ActiveCalls) {
00851     SkipStart = Limit / 2 + Limit % 2;
00852     SkipEnd = ActiveCalls - Limit / 2;
00853   }
00854 
00855   // Walk the call stack and add the diagnostics.
00856   unsigned CallIdx = 0;
00857   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
00858        Frame = Frame->Caller, ++CallIdx) {
00859     // Skip this call?
00860     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
00861       if (CallIdx == SkipStart) {
00862         // Note that we're skipping calls.
00863         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
00864           << unsigned(ActiveCalls - Limit);
00865       }
00866       continue;
00867     }
00868 
00869     SmallVector<char, 128> Buffer;
00870     llvm::raw_svector_ostream Out(Buffer);
00871     describeCall(Frame, Out);
00872     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
00873   }
00874 }
00875 
00876 namespace {
00877   struct ComplexValue {
00878   private:
00879     bool IsInt;
00880 
00881   public:
00882     APSInt IntReal, IntImag;
00883     APFloat FloatReal, FloatImag;
00884 
00885     ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
00886 
00887     void makeComplexFloat() { IsInt = false; }
00888     bool isComplexFloat() const { return !IsInt; }
00889     APFloat &getComplexFloatReal() { return FloatReal; }
00890     APFloat &getComplexFloatImag() { return FloatImag; }
00891 
00892     void makeComplexInt() { IsInt = true; }
00893     bool isComplexInt() const { return IsInt; }
00894     APSInt &getComplexIntReal() { return IntReal; }
00895     APSInt &getComplexIntImag() { return IntImag; }
00896 
00897     void moveInto(APValue &v) const {
00898       if (isComplexFloat())
00899         v = APValue(FloatReal, FloatImag);
00900       else
00901         v = APValue(IntReal, IntImag);
00902     }
00903     void setFrom(const APValue &v) {
00904       assert(v.isComplexFloat() || v.isComplexInt());
00905       if (v.isComplexFloat()) {
00906         makeComplexFloat();
00907         FloatReal = v.getComplexFloatReal();
00908         FloatImag = v.getComplexFloatImag();
00909       } else {
00910         makeComplexInt();
00911         IntReal = v.getComplexIntReal();
00912         IntImag = v.getComplexIntImag();
00913       }
00914     }
00915   };
00916 
00917   struct LValue {
00918     APValue::LValueBase Base;
00919     CharUnits Offset;
00920     unsigned CallIndex;
00921     SubobjectDesignator Designator;
00922 
00923     const APValue::LValueBase getLValueBase() const { return Base; }
00924     CharUnits &getLValueOffset() { return Offset; }
00925     const CharUnits &getLValueOffset() const { return Offset; }
00926     unsigned getLValueCallIndex() const { return CallIndex; }
00927     SubobjectDesignator &getLValueDesignator() { return Designator; }
00928     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
00929 
00930     void moveInto(APValue &V) const {
00931       if (Designator.Invalid)
00932         V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
00933       else
00934         V = APValue(Base, Offset, Designator.Entries,
00935                     Designator.IsOnePastTheEnd, CallIndex);
00936     }
00937     void setFrom(ASTContext &Ctx, const APValue &V) {
00938       assert(V.isLValue());
00939       Base = V.getLValueBase();
00940       Offset = V.getLValueOffset();
00941       CallIndex = V.getLValueCallIndex();
00942       Designator = SubobjectDesignator(Ctx, V);
00943     }
00944 
00945     void set(APValue::LValueBase B, unsigned I = 0) {
00946       Base = B;
00947       Offset = CharUnits::Zero();
00948       CallIndex = I;
00949       Designator = SubobjectDesignator(getType(B));
00950     }
00951 
00952     // Check that this LValue is not based on a null pointer. If it is, produce
00953     // a diagnostic and mark the designator as invalid.
00954     bool checkNullPointer(EvalInfo &Info, const Expr *E,
00955                           CheckSubobjectKind CSK) {
00956       if (Designator.Invalid)
00957         return false;
00958       if (!Base) {
00959         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
00960           << CSK;
00961         Designator.setInvalid();
00962         return false;
00963       }
00964       return true;
00965     }
00966 
00967     // Check this LValue refers to an object. If not, set the designator to be
00968     // invalid and emit a diagnostic.
00969     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
00970       // Outside C++11, do not build a designator referring to a subobject of
00971       // any object: we won't use such a designator for anything.
00972       if (!Info.getLangOpts().CPlusPlus11)
00973         Designator.setInvalid();
00974       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
00975              Designator.checkSubobject(Info, E, CSK);
00976     }
00977 
00978     void addDecl(EvalInfo &Info, const Expr *E,
00979                  const Decl *D, bool Virtual = false) {
00980       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
00981         Designator.addDeclUnchecked(D, Virtual);
00982     }
00983     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
00984       if (checkSubobject(Info, E, CSK_ArrayToPointer))
00985         Designator.addArrayUnchecked(CAT);
00986     }
00987     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
00988       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
00989         Designator.addComplexUnchecked(EltTy, Imag);
00990     }
00991     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
00992       if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
00993         Designator.adjustIndex(Info, E, N);
00994     }
00995   };
00996 
00997   struct MemberPtr {
00998     MemberPtr() {}
00999     explicit MemberPtr(const ValueDecl *Decl) :
01000       DeclAndIsDerivedMember(Decl, false), Path() {}
01001 
01002     /// The member or (direct or indirect) field referred to by this member
01003     /// pointer, or 0 if this is a null member pointer.
01004     const ValueDecl *getDecl() const {
01005       return DeclAndIsDerivedMember.getPointer();
01006     }
01007     /// Is this actually a member of some type derived from the relevant class?
01008     bool isDerivedMember() const {
01009       return DeclAndIsDerivedMember.getInt();
01010     }
01011     /// Get the class which the declaration actually lives in.
01012     const CXXRecordDecl *getContainingRecord() const {
01013       return cast<CXXRecordDecl>(
01014           DeclAndIsDerivedMember.getPointer()->getDeclContext());
01015     }
01016 
01017     void moveInto(APValue &V) const {
01018       V = APValue(getDecl(), isDerivedMember(), Path);
01019     }
01020     void setFrom(const APValue &V) {
01021       assert(V.isMemberPointer());
01022       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
01023       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
01024       Path.clear();
01025       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
01026       Path.insert(Path.end(), P.begin(), P.end());
01027     }
01028 
01029     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
01030     /// whether the member is a member of some class derived from the class type
01031     /// of the member pointer.
01032     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
01033     /// Path - The path of base/derived classes from the member declaration's
01034     /// class (exclusive) to the class type of the member pointer (inclusive).
01035     SmallVector<const CXXRecordDecl*, 4> Path;
01036 
01037     /// Perform a cast towards the class of the Decl (either up or down the
01038     /// hierarchy).
01039     bool castBack(const CXXRecordDecl *Class) {
01040       assert(!Path.empty());
01041       const CXXRecordDecl *Expected;
01042       if (Path.size() >= 2)
01043         Expected = Path[Path.size() - 2];
01044       else
01045         Expected = getContainingRecord();
01046       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
01047         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
01048         // if B does not contain the original member and is not a base or
01049         // derived class of the class containing the original member, the result
01050         // of the cast is undefined.
01051         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
01052         // (D::*). We consider that to be a language defect.
01053         return false;
01054       }
01055       Path.pop_back();
01056       return true;
01057     }
01058     /// Perform a base-to-derived member pointer cast.
01059     bool castToDerived(const CXXRecordDecl *Derived) {
01060       if (!getDecl())
01061         return true;
01062       if (!isDerivedMember()) {
01063         Path.push_back(Derived);
01064         return true;
01065       }
01066       if (!castBack(Derived))
01067         return false;
01068       if (Path.empty())
01069         DeclAndIsDerivedMember.setInt(false);
01070       return true;
01071     }
01072     /// Perform a derived-to-base member pointer cast.
01073     bool castToBase(const CXXRecordDecl *Base) {
01074       if (!getDecl())
01075         return true;
01076       if (Path.empty())
01077         DeclAndIsDerivedMember.setInt(true);
01078       if (isDerivedMember()) {
01079         Path.push_back(Base);
01080         return true;
01081       }
01082       return castBack(Base);
01083     }
01084   };
01085 
01086   /// Compare two member pointers, which are assumed to be of the same type.
01087   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
01088     if (!LHS.getDecl() || !RHS.getDecl())
01089       return !LHS.getDecl() && !RHS.getDecl();
01090     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
01091       return false;
01092     return LHS.Path == RHS.Path;
01093   }
01094 }
01095 
01096 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
01097 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
01098                             const LValue &This, const Expr *E,
01099                             bool AllowNonLiteralTypes = false);
01100 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
01101 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
01102 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
01103                                   EvalInfo &Info);
01104 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
01105 static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
01106 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
01107                                     EvalInfo &Info);
01108 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
01109 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
01110 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
01111 
01112 //===----------------------------------------------------------------------===//
01113 // Misc utilities
01114 //===----------------------------------------------------------------------===//
01115 
01116 /// Produce a string describing the given constexpr call.
01117 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
01118   unsigned ArgIndex = 0;
01119   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
01120                       !isa<CXXConstructorDecl>(Frame->Callee) &&
01121                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
01122 
01123   if (!IsMemberCall)
01124     Out << *Frame->Callee << '(';
01125 
01126   if (Frame->This && IsMemberCall) {
01127     APValue Val;
01128     Frame->This->moveInto(Val);
01129     Val.printPretty(Out, Frame->Info.Ctx,
01130                     Frame->This->Designator.MostDerivedType);
01131     // FIXME: Add parens around Val if needed.
01132     Out << "->" << *Frame->Callee << '(';
01133     IsMemberCall = false;
01134   }
01135 
01136   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
01137        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
01138     if (ArgIndex > (unsigned)IsMemberCall)
01139       Out << ", ";
01140 
01141     const ParmVarDecl *Param = *I;
01142     const APValue &Arg = Frame->Arguments[ArgIndex];
01143     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
01144 
01145     if (ArgIndex == 0 && IsMemberCall)
01146       Out << "->" << *Frame->Callee << '(';
01147   }
01148 
01149   Out << ')';
01150 }
01151 
01152 /// Evaluate an expression to see if it had side-effects, and discard its
01153 /// result.
01154 /// \return \c true if the caller should keep evaluating.
01155 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
01156   APValue Scratch;
01157   if (!Evaluate(Scratch, Info, E))
01158     // We don't need the value, but we might have skipped a side effect here.
01159     return Info.noteSideEffect();
01160   return true;
01161 }
01162 
01163 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
01164 /// return its existing value.
01165 static int64_t getExtValue(const APSInt &Value) {
01166   return Value.isSigned() ? Value.getSExtValue()
01167                           : static_cast<int64_t>(Value.getZExtValue());
01168 }
01169 
01170 /// Should this call expression be treated as a string literal?
01171 static bool IsStringLiteralCall(const CallExpr *E) {
01172   unsigned Builtin = E->getBuiltinCallee();
01173   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
01174           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
01175 }
01176 
01177 static bool IsGlobalLValue(APValue::LValueBase B) {
01178   // C++11 [expr.const]p3 An address constant expression is a prvalue core
01179   // constant expression of pointer type that evaluates to...
01180 
01181   // ... a null pointer value, or a prvalue core constant expression of type
01182   // std::nullptr_t.
01183   if (!B) return true;
01184 
01185   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
01186     // ... the address of an object with static storage duration,
01187     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
01188       return VD->hasGlobalStorage();
01189     // ... the address of a function,
01190     return isa<FunctionDecl>(D);
01191   }
01192 
01193   const Expr *E = B.get<const Expr*>();
01194   switch (E->getStmtClass()) {
01195   default:
01196     return false;
01197   case Expr::CompoundLiteralExprClass: {
01198     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
01199     return CLE->isFileScope() && CLE->isLValue();
01200   }
01201   case Expr::MaterializeTemporaryExprClass:
01202     // A materialized temporary might have been lifetime-extended to static
01203     // storage duration.
01204     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
01205   // A string literal has static storage duration.
01206   case Expr::StringLiteralClass:
01207   case Expr::PredefinedExprClass:
01208   case Expr::ObjCStringLiteralClass:
01209   case Expr::ObjCEncodeExprClass:
01210   case Expr::CXXTypeidExprClass:
01211   case Expr::CXXUuidofExprClass:
01212     return true;
01213   case Expr::CallExprClass:
01214     return IsStringLiteralCall(cast<CallExpr>(E));
01215   // For GCC compatibility, &&label has static storage duration.
01216   case Expr::AddrLabelExprClass:
01217     return true;
01218   // A Block literal expression may be used as the initialization value for
01219   // Block variables at global or local static scope.
01220   case Expr::BlockExprClass:
01221     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
01222   case Expr::ImplicitValueInitExprClass:
01223     // FIXME:
01224     // We can never form an lvalue with an implicit value initialization as its
01225     // base through expression evaluation, so these only appear in one case: the
01226     // implicit variable declaration we invent when checking whether a constexpr
01227     // constructor can produce a constant expression. We must assume that such
01228     // an expression might be a global lvalue.
01229     return true;
01230   }
01231 }
01232 
01233 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
01234   assert(Base && "no location for a null lvalue");
01235   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
01236   if (VD)
01237     Info.Note(VD->getLocation(), diag::note_declared_at);
01238   else
01239     Info.Note(Base.get<const Expr*>()->getExprLoc(),
01240               diag::note_constexpr_temporary_here);
01241 }
01242 
01243 /// Check that this reference or pointer core constant expression is a valid
01244 /// value for an address or reference constant expression. Return true if we
01245 /// can fold this expression, whether or not it's a constant expression.
01246 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
01247                                           QualType Type, const LValue &LVal) {
01248   bool IsReferenceType = Type->isReferenceType();
01249 
01250   APValue::LValueBase Base = LVal.getLValueBase();
01251   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
01252 
01253   // Check that the object is a global. Note that the fake 'this' object we
01254   // manufacture when checking potential constant expressions is conservatively
01255   // assumed to be global here.
01256   if (!IsGlobalLValue(Base)) {
01257     if (Info.getLangOpts().CPlusPlus11) {
01258       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
01259       Info.Diag(Loc, diag::note_constexpr_non_global, 1)
01260         << IsReferenceType << !Designator.Entries.empty()
01261         << !!VD << VD;
01262       NoteLValueLocation(Info, Base);
01263     } else {
01264       Info.Diag(Loc);
01265     }
01266     // Don't allow references to temporaries to escape.
01267     return false;
01268   }
01269   assert((Info.checkingPotentialConstantExpression() ||
01270           LVal.getLValueCallIndex() == 0) &&
01271          "have call index for global lvalue");
01272 
01273   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
01274     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
01275       // Check if this is a thread-local variable.
01276       if (Var->getTLSKind())
01277         return false;
01278 
01279       // A dllimport variable never acts like a constant.
01280       if (Var->hasAttr<DLLImportAttr>())
01281         return false;
01282     }
01283     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
01284       // __declspec(dllimport) must be handled very carefully:
01285       // We must never initialize an expression with the thunk in C++.
01286       // Doing otherwise would allow the same id-expression to yield
01287       // different addresses for the same function in different translation
01288       // units.  However, this means that we must dynamically initialize the
01289       // expression with the contents of the import address table at runtime.
01290       //
01291       // The C language has no notion of ODR; furthermore, it has no notion of
01292       // dynamic initialization.  This means that we are permitted to
01293       // perform initialization with the address of the thunk.
01294       if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
01295         return false;
01296     }
01297   }
01298 
01299   // Allow address constant expressions to be past-the-end pointers. This is
01300   // an extension: the standard requires them to point to an object.
01301   if (!IsReferenceType)
01302     return true;
01303 
01304   // A reference constant expression must refer to an object.
01305   if (!Base) {
01306     // FIXME: diagnostic
01307     Info.CCEDiag(Loc);
01308     return true;
01309   }
01310 
01311   // Does this refer one past the end of some object?
01312   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
01313     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
01314     Info.Diag(Loc, diag::note_constexpr_past_end, 1)
01315       << !Designator.Entries.empty() << !!VD << VD;
01316     NoteLValueLocation(Info, Base);
01317   }
01318 
01319   return true;
01320 }
01321 
01322 /// Check that this core constant expression is of literal type, and if not,
01323 /// produce an appropriate diagnostic.
01324 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
01325                              const LValue *This = nullptr) {
01326   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
01327     return true;
01328 
01329   // C++1y: A constant initializer for an object o [...] may also invoke
01330   // constexpr constructors for o and its subobjects even if those objects
01331   // are of non-literal class types.
01332   if (Info.getLangOpts().CPlusPlus14 && This &&
01333       Info.EvaluatingDecl == This->getLValueBase())
01334     return true;
01335 
01336   // Prvalue constant expressions must be of literal types.
01337   if (Info.getLangOpts().CPlusPlus11)
01338     Info.Diag(E, diag::note_constexpr_nonliteral)
01339       << E->getType();
01340   else
01341     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
01342   return false;
01343 }
01344 
01345 /// Check that this core constant expression value is a valid value for a
01346 /// constant expression. If not, report an appropriate diagnostic. Does not
01347 /// check that the expression is of literal type.
01348 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
01349                                     QualType Type, const APValue &Value) {
01350   if (Value.isUninit()) {
01351     Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
01352       << true << Type;
01353     return false;
01354   }
01355 
01356   // We allow _Atomic(T) to be initialized from anything that T can be
01357   // initialized from.
01358   if (const AtomicType *AT = Type->getAs<AtomicType>())
01359     Type = AT->getValueType();
01360 
01361   // Core issue 1454: For a literal constant expression of array or class type,
01362   // each subobject of its value shall have been initialized by a constant
01363   // expression.
01364   if (Value.isArray()) {
01365     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
01366     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
01367       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
01368                                    Value.getArrayInitializedElt(I)))
01369         return false;
01370     }
01371     if (!Value.hasArrayFiller())
01372       return true;
01373     return CheckConstantExpression(Info, DiagLoc, EltTy,
01374                                    Value.getArrayFiller());
01375   }
01376   if (Value.isUnion() && Value.getUnionField()) {
01377     return CheckConstantExpression(Info, DiagLoc,
01378                                    Value.getUnionField()->getType(),
01379                                    Value.getUnionValue());
01380   }
01381   if (Value.isStruct()) {
01382     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
01383     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
01384       unsigned BaseIndex = 0;
01385       for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
01386              End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
01387         if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
01388                                      Value.getStructBase(BaseIndex)))
01389           return false;
01390       }
01391     }
01392     for (const auto *I : RD->fields()) {
01393       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
01394                                    Value.getStructField(I->getFieldIndex())))
01395         return false;
01396     }
01397   }
01398 
01399   if (Value.isLValue()) {
01400     LValue LVal;
01401     LVal.setFrom(Info.Ctx, Value);
01402     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
01403   }
01404 
01405   // Everything else is fine.
01406   return true;
01407 }
01408 
01409 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
01410   return LVal.Base.dyn_cast<const ValueDecl*>();
01411 }
01412 
01413 static bool IsLiteralLValue(const LValue &Value) {
01414   if (Value.CallIndex)
01415     return false;
01416   const Expr *E = Value.Base.dyn_cast<const Expr*>();
01417   return E && !isa<MaterializeTemporaryExpr>(E);
01418 }
01419 
01420 static bool IsWeakLValue(const LValue &Value) {
01421   const ValueDecl *Decl = GetLValueBaseDecl(Value);
01422   return Decl && Decl->isWeak();
01423 }
01424 
01425 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
01426   // A null base expression indicates a null pointer.  These are always
01427   // evaluatable, and they are false unless the offset is zero.
01428   if (!Value.getLValueBase()) {
01429     Result = !Value.getLValueOffset().isZero();
01430     return true;
01431   }
01432 
01433   // We have a non-null base.  These are generally known to be true, but if it's
01434   // a weak declaration it can be null at runtime.
01435   Result = true;
01436   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
01437   return !Decl || !Decl->isWeak();
01438 }
01439 
01440 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
01441   switch (Val.getKind()) {
01442   case APValue::Uninitialized:
01443     return false;
01444   case APValue::Int:
01445     Result = Val.getInt().getBoolValue();
01446     return true;
01447   case APValue::Float:
01448     Result = !Val.getFloat().isZero();
01449     return true;
01450   case APValue::ComplexInt:
01451     Result = Val.getComplexIntReal().getBoolValue() ||
01452              Val.getComplexIntImag().getBoolValue();
01453     return true;
01454   case APValue::ComplexFloat:
01455     Result = !Val.getComplexFloatReal().isZero() ||
01456              !Val.getComplexFloatImag().isZero();
01457     return true;
01458   case APValue::LValue:
01459     return EvalPointerValueAsBool(Val, Result);
01460   case APValue::MemberPointer:
01461     Result = Val.getMemberPointerDecl();
01462     return true;
01463   case APValue::Vector:
01464   case APValue::Array:
01465   case APValue::Struct:
01466   case APValue::Union:
01467   case APValue::AddrLabelDiff:
01468     return false;
01469   }
01470 
01471   llvm_unreachable("unknown APValue kind");
01472 }
01473 
01474 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
01475                                        EvalInfo &Info) {
01476   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
01477   APValue Val;
01478   if (!Evaluate(Val, Info, E))
01479     return false;
01480   return HandleConversionToBool(Val, Result);
01481 }
01482 
01483 template<typename T>
01484 static void HandleOverflow(EvalInfo &Info, const Expr *E,
01485                            const T &SrcValue, QualType DestType) {
01486   Info.CCEDiag(E, diag::note_constexpr_overflow)
01487     << SrcValue << DestType;
01488 }
01489 
01490 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
01491                                  QualType SrcType, const APFloat &Value,
01492                                  QualType DestType, APSInt &Result) {
01493   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
01494   // Determine whether we are converting to unsigned or signed.
01495   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
01496 
01497   Result = APSInt(DestWidth, !DestSigned);
01498   bool ignored;
01499   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
01500       & APFloat::opInvalidOp)
01501     HandleOverflow(Info, E, Value, DestType);
01502   return true;
01503 }
01504 
01505 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
01506                                    QualType SrcType, QualType DestType,
01507                                    APFloat &Result) {
01508   APFloat Value = Result;
01509   bool ignored;
01510   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
01511                      APFloat::rmNearestTiesToEven, &ignored)
01512       & APFloat::opOverflow)
01513     HandleOverflow(Info, E, Value, DestType);
01514   return true;
01515 }
01516 
01517 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
01518                                  QualType DestType, QualType SrcType,
01519                                  APSInt &Value) {
01520   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
01521   APSInt Result = Value;
01522   // Figure out if this is a truncate, extend or noop cast.
01523   // If the input is signed, do a sign extend, noop, or truncate.
01524   Result = Result.extOrTrunc(DestWidth);
01525   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
01526   return Result;
01527 }
01528 
01529 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
01530                                  QualType SrcType, const APSInt &Value,
01531                                  QualType DestType, APFloat &Result) {
01532   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
01533   if (Result.convertFromAPInt(Value, Value.isSigned(),
01534                               APFloat::rmNearestTiesToEven)
01535       & APFloat::opOverflow)
01536     HandleOverflow(Info, E, Value, DestType);
01537   return true;
01538 }
01539 
01540 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
01541                                   APValue &Value, const FieldDecl *FD) {
01542   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
01543 
01544   if (!Value.isInt()) {
01545     // Trying to store a pointer-cast-to-integer into a bitfield.
01546     // FIXME: In this case, we should provide the diagnostic for casting
01547     // a pointer to an integer.
01548     assert(Value.isLValue() && "integral value neither int nor lvalue?");
01549     Info.Diag(E);
01550     return false;
01551   }
01552 
01553   APSInt &Int = Value.getInt();
01554   unsigned OldBitWidth = Int.getBitWidth();
01555   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
01556   if (NewBitWidth < OldBitWidth)
01557     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
01558   return true;
01559 }
01560 
01561 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
01562                                   llvm::APInt &Res) {
01563   APValue SVal;
01564   if (!Evaluate(SVal, Info, E))
01565     return false;
01566   if (SVal.isInt()) {
01567     Res = SVal.getInt();
01568     return true;
01569   }
01570   if (SVal.isFloat()) {
01571     Res = SVal.getFloat().bitcastToAPInt();
01572     return true;
01573   }
01574   if (SVal.isVector()) {
01575     QualType VecTy = E->getType();
01576     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
01577     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
01578     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
01579     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
01580     Res = llvm::APInt::getNullValue(VecSize);
01581     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
01582       APValue &Elt = SVal.getVectorElt(i);
01583       llvm::APInt EltAsInt;
01584       if (Elt.isInt()) {
01585         EltAsInt = Elt.getInt();
01586       } else if (Elt.isFloat()) {
01587         EltAsInt = Elt.getFloat().bitcastToAPInt();
01588       } else {
01589         // Don't try to handle vectors of anything other than int or float
01590         // (not sure if it's possible to hit this case).
01591         Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
01592         return false;
01593       }
01594       unsigned BaseEltSize = EltAsInt.getBitWidth();
01595       if (BigEndian)
01596         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
01597       else
01598         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
01599     }
01600     return true;
01601   }
01602   // Give up if the input isn't an int, float, or vector.  For example, we
01603   // reject "(v4i16)(intptr_t)&a".
01604   Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
01605   return false;
01606 }
01607 
01608 /// Perform the given integer operation, which is known to need at most BitWidth
01609 /// bits, and check for overflow in the original type (if that type was not an
01610 /// unsigned type).
01611 template<typename Operation>
01612 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
01613                                    const APSInt &LHS, const APSInt &RHS,
01614                                    unsigned BitWidth, Operation Op) {
01615   if (LHS.isUnsigned())
01616     return Op(LHS, RHS);
01617 
01618   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
01619   APSInt Result = Value.trunc(LHS.getBitWidth());
01620   if (Result.extend(BitWidth) != Value) {
01621     if (Info.checkingForOverflow())
01622       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
01623         diag::warn_integer_constant_overflow)
01624           << Result.toString(10) << E->getType();
01625     else
01626       HandleOverflow(Info, E, Value, E->getType());
01627   }
01628   return Result;
01629 }
01630 
01631 /// Perform the given binary integer operation.
01632 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
01633                               BinaryOperatorKind Opcode, APSInt RHS,
01634                               APSInt &Result) {
01635   switch (Opcode) {
01636   default:
01637     Info.Diag(E);
01638     return false;
01639   case BO_Mul:
01640     Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
01641                                   std::multiplies<APSInt>());
01642     return true;
01643   case BO_Add:
01644     Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
01645                                   std::plus<APSInt>());
01646     return true;
01647   case BO_Sub:
01648     Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
01649                                   std::minus<APSInt>());
01650     return true;
01651   case BO_And: Result = LHS & RHS; return true;
01652   case BO_Xor: Result = LHS ^ RHS; return true;
01653   case BO_Or:  Result = LHS | RHS; return true;
01654   case BO_Div:
01655   case BO_Rem:
01656     if (RHS == 0) {
01657       Info.Diag(E, diag::note_expr_divide_by_zero);
01658       return false;
01659     }
01660     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
01661     if (RHS.isNegative() && RHS.isAllOnesValue() &&
01662         LHS.isSigned() && LHS.isMinSignedValue())
01663       HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
01664     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
01665     return true;
01666   case BO_Shl: {
01667     if (Info.getLangOpts().OpenCL)
01668       // OpenCL 6.3j: shift values are effectively % word size of LHS.
01669       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
01670                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
01671                     RHS.isUnsigned());
01672     else if (RHS.isSigned() && RHS.isNegative()) {
01673       // During constant-folding, a negative shift is an opposite shift. Such
01674       // a shift is not a constant expression.
01675       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
01676       RHS = -RHS;
01677       goto shift_right;
01678     }
01679   shift_left:
01680     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
01681     // the shifted type.
01682     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
01683     if (SA != RHS) {
01684       Info.CCEDiag(E, diag::note_constexpr_large_shift)
01685         << RHS << E->getType() << LHS.getBitWidth();
01686     } else if (LHS.isSigned()) {
01687       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
01688       // operand, and must not overflow the corresponding unsigned type.
01689       if (LHS.isNegative())
01690         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
01691       else if (LHS.countLeadingZeros() < SA)
01692         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
01693     }
01694     Result = LHS << SA;
01695     return true;
01696   }
01697   case BO_Shr: {
01698     if (Info.getLangOpts().OpenCL)
01699       // OpenCL 6.3j: shift values are effectively % word size of LHS.
01700       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
01701                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
01702                     RHS.isUnsigned());
01703     else if (RHS.isSigned() && RHS.isNegative()) {
01704       // During constant-folding, a negative shift is an opposite shift. Such a
01705       // shift is not a constant expression.
01706       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
01707       RHS = -RHS;
01708       goto shift_left;
01709     }
01710   shift_right:
01711     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
01712     // shifted type.
01713     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
01714     if (SA != RHS)
01715       Info.CCEDiag(E, diag::note_constexpr_large_shift)
01716         << RHS << E->getType() << LHS.getBitWidth();
01717     Result = LHS >> SA;
01718     return true;
01719   }
01720 
01721   case BO_LT: Result = LHS < RHS; return true;
01722   case BO_GT: Result = LHS > RHS; return true;
01723   case BO_LE: Result = LHS <= RHS; return true;
01724   case BO_GE: Result = LHS >= RHS; return true;
01725   case BO_EQ: Result = LHS == RHS; return true;
01726   case BO_NE: Result = LHS != RHS; return true;
01727   }
01728 }
01729 
01730 /// Perform the given binary floating-point operation, in-place, on LHS.
01731 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
01732                                   APFloat &LHS, BinaryOperatorKind Opcode,
01733                                   const APFloat &RHS) {
01734   switch (Opcode) {
01735   default:
01736     Info.Diag(E);
01737     return false;
01738   case BO_Mul:
01739     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
01740     break;
01741   case BO_Add:
01742     LHS.add(RHS, APFloat::rmNearestTiesToEven);
01743     break;
01744   case BO_Sub:
01745     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
01746     break;
01747   case BO_Div:
01748     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
01749     break;
01750   }
01751 
01752   if (LHS.isInfinity() || LHS.isNaN())
01753     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
01754   return true;
01755 }
01756 
01757 /// Cast an lvalue referring to a base subobject to a derived class, by
01758 /// truncating the lvalue's path to the given length.
01759 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
01760                                const RecordDecl *TruncatedType,
01761                                unsigned TruncatedElements) {
01762   SubobjectDesignator &D = Result.Designator;
01763 
01764   // Check we actually point to a derived class object.
01765   if (TruncatedElements == D.Entries.size())
01766     return true;
01767   assert(TruncatedElements >= D.MostDerivedPathLength &&
01768          "not casting to a derived class");
01769   if (!Result.checkSubobject(Info, E, CSK_Derived))
01770     return false;
01771 
01772   // Truncate the path to the subobject, and remove any derived-to-base offsets.
01773   const RecordDecl *RD = TruncatedType;
01774   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
01775     if (RD->isInvalidDecl()) return false;
01776     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
01777     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
01778     if (isVirtualBaseClass(D.Entries[I]))
01779       Result.Offset -= Layout.getVBaseClassOffset(Base);
01780     else
01781       Result.Offset -= Layout.getBaseClassOffset(Base);
01782     RD = Base;
01783   }
01784   D.Entries.resize(TruncatedElements);
01785   return true;
01786 }
01787 
01788 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
01789                                    const CXXRecordDecl *Derived,
01790                                    const CXXRecordDecl *Base,
01791                                    const ASTRecordLayout *RL = nullptr) {
01792   if (!RL) {
01793     if (Derived->isInvalidDecl()) return false;
01794     RL = &Info.Ctx.getASTRecordLayout(Derived);
01795   }
01796 
01797   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
01798   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
01799   return true;
01800 }
01801 
01802 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
01803                              const CXXRecordDecl *DerivedDecl,
01804                              const CXXBaseSpecifier *Base) {
01805   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
01806 
01807   if (!Base->isVirtual())
01808     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
01809 
01810   SubobjectDesignator &D = Obj.Designator;
01811   if (D.Invalid)
01812     return false;
01813 
01814   // Extract most-derived object and corresponding type.
01815   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
01816   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
01817     return false;
01818 
01819   // Find the virtual base class.
01820   if (DerivedDecl->isInvalidDecl()) return false;
01821   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
01822   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
01823   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
01824   return true;
01825 }
01826 
01827 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
01828                                  QualType Type, LValue &Result) {
01829   for (CastExpr::path_const_iterator PathI = E->path_begin(),
01830                                      PathE = E->path_end();
01831        PathI != PathE; ++PathI) {
01832     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
01833                           *PathI))
01834       return false;
01835     Type = (*PathI)->getType();
01836   }
01837   return true;
01838 }
01839 
01840 /// Update LVal to refer to the given field, which must be a member of the type
01841 /// currently described by LVal.
01842 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
01843                                const FieldDecl *FD,
01844                                const ASTRecordLayout *RL = nullptr) {
01845   if (!RL) {
01846     if (FD->getParent()->isInvalidDecl()) return false;
01847     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
01848   }
01849 
01850   unsigned I = FD->getFieldIndex();
01851   LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
01852   LVal.addDecl(Info, E, FD);
01853   return true;
01854 }
01855 
01856 /// Update LVal to refer to the given indirect field.
01857 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
01858                                        LValue &LVal,
01859                                        const IndirectFieldDecl *IFD) {
01860   for (const auto *C : IFD->chain())
01861     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
01862       return false;
01863   return true;
01864 }
01865 
01866 /// Get the size of the given type in char units.
01867 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
01868                          QualType Type, CharUnits &Size) {
01869   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
01870   // extension.
01871   if (Type->isVoidType() || Type->isFunctionType()) {
01872     Size = CharUnits::One();
01873     return true;
01874   }
01875 
01876   if (!Type->isConstantSizeType()) {
01877     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
01878     // FIXME: Better diagnostic.
01879     Info.Diag(Loc);
01880     return false;
01881   }
01882 
01883   Size = Info.Ctx.getTypeSizeInChars(Type);
01884   return true;
01885 }
01886 
01887 /// Update a pointer value to model pointer arithmetic.
01888 /// \param Info - Information about the ongoing evaluation.
01889 /// \param E - The expression being evaluated, for diagnostic purposes.
01890 /// \param LVal - The pointer value to be updated.
01891 /// \param EltTy - The pointee type represented by LVal.
01892 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
01893 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
01894                                         LValue &LVal, QualType EltTy,
01895                                         int64_t Adjustment) {
01896   CharUnits SizeOfPointee;
01897   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
01898     return false;
01899 
01900   // Compute the new offset in the appropriate width.
01901   LVal.Offset += Adjustment * SizeOfPointee;
01902   LVal.adjustIndex(Info, E, Adjustment);
01903   return true;
01904 }
01905 
01906 /// Update an lvalue to refer to a component of a complex number.
01907 /// \param Info - Information about the ongoing evaluation.
01908 /// \param LVal - The lvalue to be updated.
01909 /// \param EltTy - The complex number's component type.
01910 /// \param Imag - False for the real component, true for the imaginary.
01911 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
01912                                        LValue &LVal, QualType EltTy,
01913                                        bool Imag) {
01914   if (Imag) {
01915     CharUnits SizeOfComponent;
01916     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
01917       return false;
01918     LVal.Offset += SizeOfComponent;
01919   }
01920   LVal.addComplex(Info, E, EltTy, Imag);
01921   return true;
01922 }
01923 
01924 /// Try to evaluate the initializer for a variable declaration.
01925 ///
01926 /// \param Info   Information about the ongoing evaluation.
01927 /// \param E      An expression to be used when printing diagnostics.
01928 /// \param VD     The variable whose initializer should be obtained.
01929 /// \param Frame  The frame in which the variable was created. Must be null
01930 ///               if this variable is not local to the evaluation.
01931 /// \param Result Filled in with a pointer to the value of the variable.
01932 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
01933                                 const VarDecl *VD, CallStackFrame *Frame,
01934                                 APValue *&Result) {
01935   // If this is a parameter to an active constexpr function call, perform
01936   // argument substitution.
01937   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
01938     // Assume arguments of a potential constant expression are unknown
01939     // constant expressions.
01940     if (Info.checkingPotentialConstantExpression())
01941       return false;
01942     if (!Frame || !Frame->Arguments) {
01943       Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
01944       return false;
01945     }
01946     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
01947     return true;
01948   }
01949 
01950   // If this is a local variable, dig out its value.
01951   if (Frame) {
01952     Result = Frame->getTemporary(VD);
01953     assert(Result && "missing value for local variable");
01954     return true;
01955   }
01956 
01957   // Dig out the initializer, and use the declaration which it's attached to.
01958   const Expr *Init = VD->getAnyInitializer(VD);
01959   if (!Init || Init->isValueDependent()) {
01960     // If we're checking a potential constant expression, the variable could be
01961     // initialized later.
01962     if (!Info.checkingPotentialConstantExpression())
01963       Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
01964     return false;
01965   }
01966 
01967   // If we're currently evaluating the initializer of this declaration, use that
01968   // in-flight value.
01969   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
01970     Result = Info.EvaluatingDeclValue;
01971     return true;
01972   }
01973 
01974   // Never evaluate the initializer of a weak variable. We can't be sure that
01975   // this is the definition which will be used.
01976   if (VD->isWeak()) {
01977     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
01978     return false;
01979   }
01980 
01981   // Check that we can fold the initializer. In C++, we will have already done
01982   // this in the cases where it matters for conformance.
01983   SmallVector<PartialDiagnosticAt, 8> Notes;
01984   if (!VD->evaluateValue(Notes)) {
01985     Info.Diag(E, diag::note_constexpr_var_init_non_constant,
01986               Notes.size() + 1) << VD;
01987     Info.Note(VD->getLocation(), diag::note_declared_at);
01988     Info.addNotes(Notes);
01989     return false;
01990   } else if (!VD->checkInitIsICE()) {
01991     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
01992                  Notes.size() + 1) << VD;
01993     Info.Note(VD->getLocation(), diag::note_declared_at);
01994     Info.addNotes(Notes);
01995   }
01996 
01997   Result = VD->getEvaluatedValue();
01998   return true;
01999 }
02000 
02001 static bool IsConstNonVolatile(QualType T) {
02002   Qualifiers Quals = T.getQualifiers();
02003   return Quals.hasConst() && !Quals.hasVolatile();
02004 }
02005 
02006 /// Get the base index of the given base class within an APValue representing
02007 /// the given derived class.
02008 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
02009                              const CXXRecordDecl *Base) {
02010   Base = Base->getCanonicalDecl();
02011   unsigned Index = 0;
02012   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
02013          E = Derived->bases_end(); I != E; ++I, ++Index) {
02014     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
02015       return Index;
02016   }
02017 
02018   llvm_unreachable("base class missing from derived class's bases list");
02019 }
02020 
02021 /// Extract the value of a character from a string literal.
02022 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
02023                                             uint64_t Index) {
02024   // FIXME: Support ObjCEncodeExpr, MakeStringConstant
02025   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
02026     Lit = PE->getFunctionName();
02027   const StringLiteral *S = cast<StringLiteral>(Lit);
02028   const ConstantArrayType *CAT =
02029       Info.Ctx.getAsConstantArrayType(S->getType());
02030   assert(CAT && "string literal isn't an array");
02031   QualType CharType = CAT->getElementType();
02032   assert(CharType->isIntegerType() && "unexpected character type");
02033 
02034   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
02035                CharType->isUnsignedIntegerType());
02036   if (Index < S->getLength())
02037     Value = S->getCodeUnit(Index);
02038   return Value;
02039 }
02040 
02041 // Expand a string literal into an array of characters.
02042 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
02043                                 APValue &Result) {
02044   const StringLiteral *S = cast<StringLiteral>(Lit);
02045   const ConstantArrayType *CAT =
02046       Info.Ctx.getAsConstantArrayType(S->getType());
02047   assert(CAT && "string literal isn't an array");
02048   QualType CharType = CAT->getElementType();
02049   assert(CharType->isIntegerType() && "unexpected character type");
02050 
02051   unsigned Elts = CAT->getSize().getZExtValue();
02052   Result = APValue(APValue::UninitArray(),
02053                    std::min(S->getLength(), Elts), Elts);
02054   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
02055                CharType->isUnsignedIntegerType());
02056   if (Result.hasArrayFiller())
02057     Result.getArrayFiller() = APValue(Value);
02058   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
02059     Value = S->getCodeUnit(I);
02060     Result.getArrayInitializedElt(I) = APValue(Value);
02061   }
02062 }
02063 
02064 // Expand an array so that it has more than Index filled elements.
02065 static void expandArray(APValue &Array, unsigned Index) {
02066   unsigned Size = Array.getArraySize();
02067   assert(Index < Size);
02068 
02069   // Always at least double the number of elements for which we store a value.
02070   unsigned OldElts = Array.getArrayInitializedElts();
02071   unsigned NewElts = std::max(Index+1, OldElts * 2);
02072   NewElts = std::min(Size, std::max(NewElts, 8u));
02073 
02074   // Copy the data across.
02075   APValue NewValue(APValue::UninitArray(), NewElts, Size);
02076   for (unsigned I = 0; I != OldElts; ++I)
02077     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
02078   for (unsigned I = OldElts; I != NewElts; ++I)
02079     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
02080   if (NewValue.hasArrayFiller())
02081     NewValue.getArrayFiller() = Array.getArrayFiller();
02082   Array.swap(NewValue);
02083 }
02084 
02085 /// Determine whether a type would actually be read by an lvalue-to-rvalue
02086 /// conversion. If it's of class type, we may assume that the copy operation
02087 /// is trivial. Note that this is never true for a union type with fields
02088 /// (because the copy always "reads" the active member) and always true for
02089 /// a non-class type.
02090 static bool isReadByLvalueToRvalueConversion(QualType T) {
02091   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
02092   if (!RD || (RD->isUnion() && !RD->field_empty()))
02093     return true;
02094   if (RD->isEmpty())
02095     return false;
02096 
02097   for (auto *Field : RD->fields())
02098     if (isReadByLvalueToRvalueConversion(Field->getType()))
02099       return true;
02100 
02101   for (auto &BaseSpec : RD->bases())
02102     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
02103       return true;
02104 
02105   return false;
02106 }
02107 
02108 /// Diagnose an attempt to read from any unreadable field within the specified
02109 /// type, which might be a class type.
02110 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
02111                                      QualType T) {
02112   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
02113   if (!RD)
02114     return false;
02115 
02116   if (!RD->hasMutableFields())
02117     return false;
02118 
02119   for (auto *Field : RD->fields()) {
02120     // If we're actually going to read this field in some way, then it can't
02121     // be mutable. If we're in a union, then assigning to a mutable field
02122     // (even an empty one) can change the active member, so that's not OK.
02123     // FIXME: Add core issue number for the union case.
02124     if (Field->isMutable() &&
02125         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
02126       Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
02127       Info.Note(Field->getLocation(), diag::note_declared_at);
02128       return true;
02129     }
02130 
02131     if (diagnoseUnreadableFields(Info, E, Field->getType()))
02132       return true;
02133   }
02134 
02135   for (auto &BaseSpec : RD->bases())
02136     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
02137       return true;
02138 
02139   // All mutable fields were empty, and thus not actually read.
02140   return false;
02141 }
02142 
02143 /// Kinds of access we can perform on an object, for diagnostics.
02144 enum AccessKinds {
02145   AK_Read,
02146   AK_Assign,
02147   AK_Increment,
02148   AK_Decrement
02149 };
02150 
02151 /// A handle to a complete object (an object that is not a subobject of
02152 /// another object).
02153 struct CompleteObject {
02154   /// The value of the complete object.
02155   APValue *Value;
02156   /// The type of the complete object.
02157   QualType Type;
02158 
02159   CompleteObject() : Value(nullptr) {}
02160   CompleteObject(APValue *Value, QualType Type)
02161       : Value(Value), Type(Type) {
02162     assert(Value && "missing value for complete object");
02163   }
02164 
02165   LLVM_EXPLICIT operator bool() const { return Value; }
02166 };
02167 
02168 /// Find the designated sub-object of an rvalue.
02169 template<typename SubobjectHandler>
02170 typename SubobjectHandler::result_type
02171 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
02172               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
02173   if (Sub.Invalid)
02174     // A diagnostic will have already been produced.
02175     return handler.failed();
02176   if (Sub.isOnePastTheEnd()) {
02177     if (Info.getLangOpts().CPlusPlus11)
02178       Info.Diag(E, diag::note_constexpr_access_past_end)
02179         << handler.AccessKind;
02180     else
02181       Info.Diag(E);
02182     return handler.failed();
02183   }
02184 
02185   APValue *O = Obj.Value;
02186   QualType ObjType = Obj.Type;
02187   const FieldDecl *LastField = nullptr;
02188 
02189   // Walk the designator's path to find the subobject.
02190   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
02191     if (O->isUninit()) {
02192       if (!Info.checkingPotentialConstantExpression())
02193         Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
02194       return handler.failed();
02195     }
02196 
02197     if (I == N) {
02198       // If we are reading an object of class type, there may still be more
02199       // things we need to check: if there are any mutable subobjects, we
02200       // cannot perform this read. (This only happens when performing a trivial
02201       // copy or assignment.)
02202       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
02203           diagnoseUnreadableFields(Info, E, ObjType))
02204         return handler.failed();
02205 
02206       if (!handler.found(*O, ObjType))
02207         return false;
02208 
02209       // If we modified a bit-field, truncate it to the right width.
02210       if (handler.AccessKind != AK_Read &&
02211           LastField && LastField->isBitField() &&
02212           !truncateBitfieldValue(Info, E, *O, LastField))
02213         return false;
02214 
02215       return true;
02216     }
02217 
02218     LastField = nullptr;
02219     if (ObjType->isArrayType()) {
02220       // Next subobject is an array element.
02221       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
02222       assert(CAT && "vla in literal type?");
02223       uint64_t Index = Sub.Entries[I].ArrayIndex;
02224       if (CAT->getSize().ule(Index)) {
02225         // Note, it should not be possible to form a pointer with a valid
02226         // designator which points more than one past the end of the array.
02227         if (Info.getLangOpts().CPlusPlus11)
02228           Info.Diag(E, diag::note_constexpr_access_past_end)
02229             << handler.AccessKind;
02230         else
02231           Info.Diag(E);
02232         return handler.failed();
02233       }
02234 
02235       ObjType = CAT->getElementType();
02236 
02237       // An array object is represented as either an Array APValue or as an
02238       // LValue which refers to a string literal.
02239       if (O->isLValue()) {
02240         assert(I == N - 1 && "extracting subobject of character?");
02241         assert(!O->hasLValuePath() || O->getLValuePath().empty());
02242         if (handler.AccessKind != AK_Read)
02243           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
02244                               *O);
02245         else
02246           return handler.foundString(*O, ObjType, Index);
02247       }
02248 
02249       if (O->getArrayInitializedElts() > Index)
02250         O = &O->getArrayInitializedElt(Index);
02251       else if (handler.AccessKind != AK_Read) {
02252         expandArray(*O, Index);
02253         O = &O->getArrayInitializedElt(Index);
02254       } else
02255         O = &O->getArrayFiller();
02256     } else if (ObjType->isAnyComplexType()) {
02257       // Next subobject is a complex number.
02258       uint64_t Index = Sub.Entries[I].ArrayIndex;
02259       if (Index > 1) {
02260         if (Info.getLangOpts().CPlusPlus11)
02261           Info.Diag(E, diag::note_constexpr_access_past_end)
02262             << handler.AccessKind;
02263         else
02264           Info.Diag(E);
02265         return handler.failed();
02266       }
02267 
02268       bool WasConstQualified = ObjType.isConstQualified();
02269       ObjType = ObjType->castAs<ComplexType>()->getElementType();
02270       if (WasConstQualified)
02271         ObjType.addConst();
02272 
02273       assert(I == N - 1 && "extracting subobject of scalar?");
02274       if (O->isComplexInt()) {
02275         return handler.found(Index ? O->getComplexIntImag()
02276                                    : O->getComplexIntReal(), ObjType);
02277       } else {
02278         assert(O->isComplexFloat());
02279         return handler.found(Index ? O->getComplexFloatImag()
02280                                    : O->getComplexFloatReal(), ObjType);
02281       }
02282     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
02283       if (Field->isMutable() && handler.AccessKind == AK_Read) {
02284         Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
02285           << Field;
02286         Info.Note(Field->getLocation(), diag::note_declared_at);
02287         return handler.failed();
02288       }
02289 
02290       // Next subobject is a class, struct or union field.
02291       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
02292       if (RD->isUnion()) {
02293         const FieldDecl *UnionField = O->getUnionField();
02294         if (!UnionField ||
02295             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
02296           Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
02297             << handler.AccessKind << Field << !UnionField << UnionField;
02298           return handler.failed();
02299         }
02300         O = &O->getUnionValue();
02301       } else
02302         O = &O->getStructField(Field->getFieldIndex());
02303 
02304       bool WasConstQualified = ObjType.isConstQualified();
02305       ObjType = Field->getType();
02306       if (WasConstQualified && !Field->isMutable())
02307         ObjType.addConst();
02308 
02309       if (ObjType.isVolatileQualified()) {
02310         if (Info.getLangOpts().CPlusPlus) {
02311           // FIXME: Include a description of the path to the volatile subobject.
02312           Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
02313             << handler.AccessKind << 2 << Field;
02314           Info.Note(Field->getLocation(), diag::note_declared_at);
02315         } else {
02316           Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
02317         }
02318         return handler.failed();
02319       }
02320 
02321       LastField = Field;
02322     } else {
02323       // Next subobject is a base class.
02324       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
02325       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
02326       O = &O->getStructBase(getBaseIndex(Derived, Base));
02327 
02328       bool WasConstQualified = ObjType.isConstQualified();
02329       ObjType = Info.Ctx.getRecordType(Base);
02330       if (WasConstQualified)
02331         ObjType.addConst();
02332     }
02333   }
02334 }
02335 
02336 namespace {
02337 struct ExtractSubobjectHandler {
02338   EvalInfo &Info;
02339   APValue &Result;
02340 
02341   static const AccessKinds AccessKind = AK_Read;
02342 
02343   typedef bool result_type;
02344   bool failed() { return false; }
02345   bool found(APValue &Subobj, QualType SubobjType) {
02346     Result = Subobj;
02347     return true;
02348   }
02349   bool found(APSInt &Value, QualType SubobjType) {
02350     Result = APValue(Value);
02351     return true;
02352   }
02353   bool found(APFloat &Value, QualType SubobjType) {
02354     Result = APValue(Value);
02355     return true;
02356   }
02357   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
02358     Result = APValue(extractStringLiteralCharacter(
02359         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
02360     return true;
02361   }
02362 };
02363 } // end anonymous namespace
02364 
02365 const AccessKinds ExtractSubobjectHandler::AccessKind;
02366 
02367 /// Extract the designated sub-object of an rvalue.
02368 static bool extractSubobject(EvalInfo &Info, const Expr *E,
02369                              const CompleteObject &Obj,
02370                              const SubobjectDesignator &Sub,
02371                              APValue &Result) {
02372   ExtractSubobjectHandler Handler = { Info, Result };
02373   return findSubobject(Info, E, Obj, Sub, Handler);
02374 }
02375 
02376 namespace {
02377 struct ModifySubobjectHandler {
02378   EvalInfo &Info;
02379   APValue &NewVal;
02380   const Expr *E;
02381 
02382   typedef bool result_type;
02383   static const AccessKinds AccessKind = AK_Assign;
02384 
02385   bool checkConst(QualType QT) {
02386     // Assigning to a const object has undefined behavior.
02387     if (QT.isConstQualified()) {
02388       Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
02389       return false;
02390     }
02391     return true;
02392   }
02393 
02394   bool failed() { return false; }
02395   bool found(APValue &Subobj, QualType SubobjType) {
02396     if (!checkConst(SubobjType))
02397       return false;
02398     // We've been given ownership of NewVal, so just swap it in.
02399     Subobj.swap(NewVal);
02400     return true;
02401   }
02402   bool found(APSInt &Value, QualType SubobjType) {
02403     if (!checkConst(SubobjType))
02404       return false;
02405     if (!NewVal.isInt()) {
02406       // Maybe trying to write a cast pointer value into a complex?
02407       Info.Diag(E);
02408       return false;
02409     }
02410     Value = NewVal.getInt();
02411     return true;
02412   }
02413   bool found(APFloat &Value, QualType SubobjType) {
02414     if (!checkConst(SubobjType))
02415       return false;
02416     Value = NewVal.getFloat();
02417     return true;
02418   }
02419   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
02420     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
02421   }
02422 };
02423 } // end anonymous namespace
02424 
02425 const AccessKinds ModifySubobjectHandler::AccessKind;
02426 
02427 /// Update the designated sub-object of an rvalue to the given value.
02428 static bool modifySubobject(EvalInfo &Info, const Expr *E,
02429                             const CompleteObject &Obj,
02430                             const SubobjectDesignator &Sub,
02431                             APValue &NewVal) {
02432   ModifySubobjectHandler Handler = { Info, NewVal, E };
02433   return findSubobject(Info, E, Obj, Sub, Handler);
02434 }
02435 
02436 /// Find the position where two subobject designators diverge, or equivalently
02437 /// the length of the common initial subsequence.
02438 static unsigned FindDesignatorMismatch(QualType ObjType,
02439                                        const SubobjectDesignator &A,
02440                                        const SubobjectDesignator &B,
02441                                        bool &WasArrayIndex) {
02442   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
02443   for (/**/; I != N; ++I) {
02444     if (!ObjType.isNull() &&
02445         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
02446       // Next subobject is an array element.
02447       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
02448         WasArrayIndex = true;
02449         return I;
02450       }
02451       if (ObjType->isAnyComplexType())
02452         ObjType = ObjType->castAs<ComplexType>()->getElementType();
02453       else
02454         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
02455     } else {
02456       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
02457         WasArrayIndex = false;
02458         return I;
02459       }
02460       if (const FieldDecl *FD = getAsField(A.Entries[I]))
02461         // Next subobject is a field.
02462         ObjType = FD->getType();
02463       else
02464         // Next subobject is a base class.
02465         ObjType = QualType();
02466     }
02467   }
02468   WasArrayIndex = false;
02469   return I;
02470 }
02471 
02472 /// Determine whether the given subobject designators refer to elements of the
02473 /// same array object.
02474 static bool AreElementsOfSameArray(QualType ObjType,
02475                                    const SubobjectDesignator &A,
02476                                    const SubobjectDesignator &B) {
02477   if (A.Entries.size() != B.Entries.size())
02478     return false;
02479 
02480   bool IsArray = A.MostDerivedArraySize != 0;
02481   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
02482     // A is a subobject of the array element.
02483     return false;
02484 
02485   // If A (and B) designates an array element, the last entry will be the array
02486   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
02487   // of length 1' case, and the entire path must match.
02488   bool WasArrayIndex;
02489   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
02490   return CommonLength >= A.Entries.size() - IsArray;
02491 }
02492 
02493 /// Find the complete object to which an LValue refers.
02494 CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
02495                                   const LValue &LVal, QualType LValType) {
02496   if (!LVal.Base) {
02497     Info.Diag(E, diag::note_constexpr_access_null) << AK;
02498     return CompleteObject();
02499   }
02500 
02501   CallStackFrame *Frame = nullptr;
02502   if (LVal.CallIndex) {
02503     Frame = Info.getCallFrame(LVal.CallIndex);
02504     if (!Frame) {
02505       Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
02506         << AK << LVal.Base.is<const ValueDecl*>();
02507       NoteLValueLocation(Info, LVal.Base);
02508       return CompleteObject();
02509     }
02510   }
02511 
02512   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
02513   // is not a constant expression (even if the object is non-volatile). We also
02514   // apply this rule to C++98, in order to conform to the expected 'volatile'
02515   // semantics.
02516   if (LValType.isVolatileQualified()) {
02517     if (Info.getLangOpts().CPlusPlus)
02518       Info.Diag(E, diag::note_constexpr_access_volatile_type)
02519         << AK << LValType;
02520     else
02521       Info.Diag(E);
02522     return CompleteObject();
02523   }
02524 
02525   // Compute value storage location and type of base object.
02526   APValue *BaseVal = nullptr;
02527   QualType BaseType = getType(LVal.Base);
02528 
02529   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
02530     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
02531     // In C++11, constexpr, non-volatile variables initialized with constant
02532     // expressions are constant expressions too. Inside constexpr functions,
02533     // parameters are constant expressions even if they're non-const.
02534     // In C++1y, objects local to a constant expression (those with a Frame) are
02535     // both readable and writable inside constant expressions.
02536     // In C, such things can also be folded, although they are not ICEs.
02537     const VarDecl *VD = dyn_cast<VarDecl>(D);
02538     if (VD) {
02539       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
02540         VD = VDef;
02541     }
02542     if (!VD || VD->isInvalidDecl()) {
02543       Info.Diag(E);
02544       return CompleteObject();
02545     }
02546 
02547     // Accesses of volatile-qualified objects are not allowed.
02548     if (BaseType.isVolatileQualified()) {
02549       if (Info.getLangOpts().CPlusPlus) {
02550         Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
02551           << AK << 1 << VD;
02552         Info.Note(VD->getLocation(), diag::note_declared_at);
02553       } else {
02554         Info.Diag(E);
02555       }
02556       return CompleteObject();
02557     }
02558 
02559     // Unless we're looking at a local variable or argument in a constexpr call,
02560     // the variable we're reading must be const.
02561     if (!Frame) {
02562       if (Info.getLangOpts().CPlusPlus14 &&
02563           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
02564         // OK, we can read and modify an object if we're in the process of
02565         // evaluating its initializer, because its lifetime began in this
02566         // evaluation.
02567       } else if (AK != AK_Read) {
02568         // All the remaining cases only permit reading.
02569         Info.Diag(E, diag::note_constexpr_modify_global);
02570         return CompleteObject();
02571       } else if (VD->isConstexpr()) {
02572         // OK, we can read this variable.
02573       } else if (BaseType->isIntegralOrEnumerationType()) {
02574         if (!BaseType.isConstQualified()) {
02575           if (Info.getLangOpts().CPlusPlus) {
02576             Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
02577             Info.Note(VD->getLocation(), diag::note_declared_at);
02578           } else {
02579             Info.Diag(E);
02580           }
02581           return CompleteObject();
02582         }
02583       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
02584         // We support folding of const floating-point types, in order to make
02585         // static const data members of such types (supported as an extension)
02586         // more useful.
02587         if (Info.getLangOpts().CPlusPlus11) {
02588           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
02589           Info.Note(VD->getLocation(), diag::note_declared_at);
02590         } else {
02591           Info.CCEDiag(E);
02592         }
02593       } else {
02594         // FIXME: Allow folding of values of any literal type in all languages.
02595         if (Info.getLangOpts().CPlusPlus11) {
02596           Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
02597           Info.Note(VD->getLocation(), diag::note_declared_at);
02598         } else {
02599           Info.Diag(E);
02600         }
02601         return CompleteObject();
02602       }
02603     }
02604 
02605     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
02606       return CompleteObject();
02607   } else {
02608     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
02609 
02610     if (!Frame) {
02611       if (const MaterializeTemporaryExpr *MTE =
02612               dyn_cast<MaterializeTemporaryExpr>(Base)) {
02613         assert(MTE->getStorageDuration() == SD_Static &&
02614                "should have a frame for a non-global materialized temporary");
02615 
02616         // Per C++1y [expr.const]p2:
02617         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
02618         //   - a [...] glvalue of integral or enumeration type that refers to
02619         //     a non-volatile const object [...]
02620         //   [...]
02621         //   - a [...] glvalue of literal type that refers to a non-volatile
02622         //     object whose lifetime began within the evaluation of e.
02623         //
02624         // C++11 misses the 'began within the evaluation of e' check and
02625         // instead allows all temporaries, including things like:
02626         //   int &&r = 1;
02627         //   int x = ++r;
02628         //   constexpr int k = r;
02629         // Therefore we use the C++1y rules in C++11 too.
02630         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
02631         const ValueDecl *ED = MTE->getExtendingDecl();
02632         if (!(BaseType.isConstQualified() &&
02633               BaseType->isIntegralOrEnumerationType()) &&
02634             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
02635           Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
02636           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
02637           return CompleteObject();
02638         }
02639 
02640         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
02641         assert(BaseVal && "got reference to unevaluated temporary");
02642       } else {
02643         Info.Diag(E);
02644         return CompleteObject();
02645       }
02646     } else {
02647       BaseVal = Frame->getTemporary(Base);
02648       assert(BaseVal && "missing value for temporary");
02649     }
02650 
02651     // Volatile temporary objects cannot be accessed in constant expressions.
02652     if (BaseType.isVolatileQualified()) {
02653       if (Info.getLangOpts().CPlusPlus) {
02654         Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
02655           << AK << 0;
02656         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
02657       } else {
02658         Info.Diag(E);
02659       }
02660       return CompleteObject();
02661     }
02662   }
02663 
02664   // During the construction of an object, it is not yet 'const'.
02665   // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
02666   // and this doesn't do quite the right thing for const subobjects of the
02667   // object under construction.
02668   if (LVal.getLValueBase() == Info.EvaluatingDecl) {
02669     BaseType = Info.Ctx.getCanonicalType(BaseType);
02670     BaseType.removeLocalConst();
02671   }
02672 
02673   // In C++1y, we can't safely access any mutable state when we might be
02674   // evaluating after an unmodeled side effect or an evaluation failure.
02675   //
02676   // FIXME: Not all local state is mutable. Allow local constant subobjects
02677   // to be read here (but take care with 'mutable' fields).
02678   if (Frame && Info.getLangOpts().CPlusPlus14 &&
02679       (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
02680     return CompleteObject();
02681 
02682   return CompleteObject(BaseVal, BaseType);
02683 }
02684 
02685 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
02686 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
02687 /// glvalue referred to by an entity of reference type.
02688 ///
02689 /// \param Info - Information about the ongoing evaluation.
02690 /// \param Conv - The expression for which we are performing the conversion.
02691 ///               Used for diagnostics.
02692 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
02693 ///               case of a non-class type).
02694 /// \param LVal - The glvalue on which we are attempting to perform this action.
02695 /// \param RVal - The produced value will be placed here.
02696 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
02697                                            QualType Type,
02698                                            const LValue &LVal, APValue &RVal) {
02699   if (LVal.Designator.Invalid)
02700     return false;
02701 
02702   // Check for special cases where there is no existing APValue to look at.
02703   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
02704   if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
02705       !Type.isVolatileQualified()) {
02706     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
02707       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
02708       // initializer until now for such expressions. Such an expression can't be
02709       // an ICE in C, so this only matters for fold.
02710       assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
02711       if (Type.isVolatileQualified()) {
02712         Info.Diag(Conv);
02713         return false;
02714       }
02715       APValue Lit;
02716       if (!Evaluate(Lit, Info, CLE->getInitializer()))
02717         return false;
02718       CompleteObject LitObj(&Lit, Base->getType());
02719       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
02720     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
02721       // We represent a string literal array as an lvalue pointing at the
02722       // corresponding expression, rather than building an array of chars.
02723       // FIXME: Support ObjCEncodeExpr, MakeStringConstant
02724       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
02725       CompleteObject StrObj(&Str, Base->getType());
02726       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
02727     }
02728   }
02729 
02730   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
02731   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
02732 }
02733 
02734 /// Perform an assignment of Val to LVal. Takes ownership of Val.
02735 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
02736                              QualType LValType, APValue &Val) {
02737   if (LVal.Designator.Invalid)
02738     return false;
02739 
02740   if (!Info.getLangOpts().CPlusPlus14) {
02741     Info.Diag(E);
02742     return false;
02743   }
02744 
02745   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
02746   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
02747 }
02748 
02749 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
02750   return T->isSignedIntegerType() &&
02751          Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
02752 }
02753 
02754 namespace {
02755 struct CompoundAssignSubobjectHandler {
02756   EvalInfo &Info;
02757   const Expr *E;
02758   QualType PromotedLHSType;
02759   BinaryOperatorKind Opcode;
02760   const APValue &RHS;
02761 
02762   static const AccessKinds AccessKind = AK_Assign;
02763 
02764   typedef bool result_type;
02765 
02766   bool checkConst(QualType QT) {
02767     // Assigning to a const object has undefined behavior.
02768     if (QT.isConstQualified()) {
02769       Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
02770       return false;
02771     }
02772     return true;
02773   }
02774 
02775   bool failed() { return false; }
02776   bool found(APValue &Subobj, QualType SubobjType) {
02777     switch (Subobj.getKind()) {
02778     case APValue::Int:
02779       return found(Subobj.getInt(), SubobjType);
02780     case APValue::Float:
02781       return found(Subobj.getFloat(), SubobjType);
02782     case APValue::ComplexInt:
02783     case APValue::ComplexFloat:
02784       // FIXME: Implement complex compound assignment.
02785       Info.Diag(E);
02786       return false;
02787     case APValue::LValue:
02788       return foundPointer(Subobj, SubobjType);
02789     default:
02790       // FIXME: can this happen?
02791       Info.Diag(E);
02792       return false;
02793     }
02794   }
02795   bool found(APSInt &Value, QualType SubobjType) {
02796     if (!checkConst(SubobjType))
02797       return false;
02798 
02799     if (!SubobjType->isIntegerType() || !RHS.isInt()) {
02800       // We don't support compound assignment on integer-cast-to-pointer
02801       // values.
02802       Info.Diag(E);
02803       return false;
02804     }
02805 
02806     APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
02807                                     SubobjType, Value);
02808     if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
02809       return false;
02810     Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
02811     return true;
02812   }
02813   bool found(APFloat &Value, QualType SubobjType) {
02814     return checkConst(SubobjType) &&
02815            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
02816                                   Value) &&
02817            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
02818            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
02819   }
02820   bool foundPointer(APValue &Subobj, QualType SubobjType) {
02821     if (!checkConst(SubobjType))
02822       return false;
02823 
02824     QualType PointeeType;
02825     if (const PointerType *PT = SubobjType->getAs<PointerType>())
02826       PointeeType = PT->getPointeeType();
02827 
02828     if (PointeeType.isNull() || !RHS.isInt() ||
02829         (Opcode != BO_Add && Opcode != BO_Sub)) {
02830       Info.Diag(E);
02831       return false;
02832     }
02833 
02834     int64_t Offset = getExtValue(RHS.getInt());
02835     if (Opcode == BO_Sub)
02836       Offset = -Offset;
02837 
02838     LValue LVal;
02839     LVal.setFrom(Info.Ctx, Subobj);
02840     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
02841       return false;
02842     LVal.moveInto(Subobj);
02843     return true;
02844   }
02845   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
02846     llvm_unreachable("shouldn't encounter string elements here");
02847   }
02848 };
02849 } // end anonymous namespace
02850 
02851 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
02852 
02853 /// Perform a compound assignment of LVal <op>= RVal.
02854 static bool handleCompoundAssignment(
02855     EvalInfo &Info, const Expr *E,
02856     const LValue &LVal, QualType LValType, QualType PromotedLValType,
02857     BinaryOperatorKind Opcode, const APValue &RVal) {
02858   if (LVal.Designator.Invalid)
02859     return false;
02860 
02861   if (!Info.getLangOpts().CPlusPlus14) {
02862     Info.Diag(E);
02863     return false;
02864   }
02865 
02866   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
02867   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
02868                                              RVal };
02869   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
02870 }
02871 
02872 namespace {
02873 struct IncDecSubobjectHandler {
02874   EvalInfo &Info;
02875   const Expr *E;
02876   AccessKinds AccessKind;
02877   APValue *Old;
02878 
02879   typedef bool result_type;
02880 
02881   bool checkConst(QualType QT) {
02882     // Assigning to a const object has undefined behavior.
02883     if (QT.isConstQualified()) {
02884       Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
02885       return false;
02886     }
02887     return true;
02888   }
02889 
02890   bool failed() { return false; }
02891   bool found(APValue &Subobj, QualType SubobjType) {
02892     // Stash the old value. Also clear Old, so we don't clobber it later
02893     // if we're post-incrementing a complex.
02894     if (Old) {
02895       *Old = Subobj;
02896       Old = nullptr;
02897     }
02898 
02899     switch (Subobj.getKind()) {
02900     case APValue::Int:
02901       return found(Subobj.getInt(), SubobjType);
02902     case APValue::Float:
02903       return found(Subobj.getFloat(), SubobjType);
02904     case APValue::ComplexInt:
02905       return found(Subobj.getComplexIntReal(),
02906                    SubobjType->castAs<ComplexType>()->getElementType()
02907                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
02908     case APValue::ComplexFloat:
02909       return found(Subobj.getComplexFloatReal(),
02910                    SubobjType->castAs<ComplexType>()->getElementType()
02911                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
02912     case APValue::LValue:
02913       return foundPointer(Subobj, SubobjType);
02914     default:
02915       // FIXME: can this happen?
02916       Info.Diag(E);
02917       return false;
02918     }
02919   }
02920   bool found(APSInt &Value, QualType SubobjType) {
02921     if (!checkConst(SubobjType))
02922       return false;
02923 
02924     if (!SubobjType->isIntegerType()) {
02925       // We don't support increment / decrement on integer-cast-to-pointer
02926       // values.
02927       Info.Diag(E);
02928       return false;
02929     }
02930 
02931     if (Old) *Old = APValue(Value);
02932 
02933     // bool arithmetic promotes to int, and the conversion back to bool
02934     // doesn't reduce mod 2^n, so special-case it.
02935     if (SubobjType->isBooleanType()) {
02936       if (AccessKind == AK_Increment)
02937         Value = 1;
02938       else
02939         Value = !Value;
02940       return true;
02941     }
02942 
02943     bool WasNegative = Value.isNegative();
02944     if (AccessKind == AK_Increment) {
02945       ++Value;
02946 
02947       if (!WasNegative && Value.isNegative() &&
02948           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
02949         APSInt ActualValue(Value, /*IsUnsigned*/true);
02950         HandleOverflow(Info, E, ActualValue, SubobjType);
02951       }
02952     } else {
02953       --Value;
02954 
02955       if (WasNegative && !Value.isNegative() &&
02956           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
02957         unsigned BitWidth = Value.getBitWidth();
02958         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
02959         ActualValue.setBit(BitWidth);
02960         HandleOverflow(Info, E, ActualValue, SubobjType);
02961       }
02962     }
02963     return true;
02964   }
02965   bool found(APFloat &Value, QualType SubobjType) {
02966     if (!checkConst(SubobjType))
02967       return false;
02968 
02969     if (Old) *Old = APValue(Value);
02970 
02971     APFloat One(Value.getSemantics(), 1);
02972     if (AccessKind == AK_Increment)
02973       Value.add(One, APFloat::rmNearestTiesToEven);
02974     else
02975       Value.subtract(One, APFloat::rmNearestTiesToEven);
02976     return true;
02977   }
02978   bool foundPointer(APValue &Subobj, QualType SubobjType) {
02979     if (!checkConst(SubobjType))
02980       return false;
02981 
02982     QualType PointeeType;
02983     if (const PointerType *PT = SubobjType->getAs<PointerType>())
02984       PointeeType = PT->getPointeeType();
02985     else {
02986       Info.Diag(E);
02987       return false;
02988     }
02989 
02990     LValue LVal;
02991     LVal.setFrom(Info.Ctx, Subobj);
02992     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
02993                                      AccessKind == AK_Increment ? 1 : -1))
02994       return false;
02995     LVal.moveInto(Subobj);
02996     return true;
02997   }
02998   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
02999     llvm_unreachable("shouldn't encounter string elements here");
03000   }
03001 };
03002 } // end anonymous namespace
03003 
03004 /// Perform an increment or decrement on LVal.
03005 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
03006                          QualType LValType, bool IsIncrement, APValue *Old) {
03007   if (LVal.Designator.Invalid)
03008     return false;
03009 
03010   if (!Info.getLangOpts().CPlusPlus14) {
03011     Info.Diag(E);
03012     return false;
03013   }
03014 
03015   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
03016   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
03017   IncDecSubobjectHandler Handler = { Info, E, AK, Old };
03018   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
03019 }
03020 
03021 /// Build an lvalue for the object argument of a member function call.
03022 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
03023                                    LValue &This) {
03024   if (Object->getType()->isPointerType())
03025     return EvaluatePointer(Object, This, Info);
03026 
03027   if (Object->isGLValue())
03028     return EvaluateLValue(Object, This, Info);
03029 
03030   if (Object->getType()->isLiteralType(Info.Ctx))
03031     return EvaluateTemporary(Object, This, Info);
03032 
03033   Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
03034   return false;
03035 }
03036 
03037 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
03038 /// lvalue referring to the result.
03039 ///
03040 /// \param Info - Information about the ongoing evaluation.
03041 /// \param LV - An lvalue referring to the base of the member pointer.
03042 /// \param RHS - The member pointer expression.
03043 /// \param IncludeMember - Specifies whether the member itself is included in
03044 ///        the resulting LValue subobject designator. This is not possible when
03045 ///        creating a bound member function.
03046 /// \return The field or method declaration to which the member pointer refers,
03047 ///         or 0 if evaluation fails.
03048 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
03049                                                   QualType LVType,
03050                                                   LValue &LV,
03051                                                   const Expr *RHS,
03052                                                   bool IncludeMember = true) {
03053   MemberPtr MemPtr;
03054   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
03055     return nullptr;
03056 
03057   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
03058   // member value, the behavior is undefined.
03059   if (!MemPtr.getDecl()) {
03060     // FIXME: Specific diagnostic.
03061     Info.Diag(RHS);
03062     return nullptr;
03063   }
03064 
03065   if (MemPtr.isDerivedMember()) {
03066     // This is a member of some derived class. Truncate LV appropriately.
03067     // The end of the derived-to-base path for the base object must match the
03068     // derived-to-base path for the member pointer.
03069     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
03070         LV.Designator.Entries.size()) {
03071       Info.Diag(RHS);
03072       return nullptr;
03073     }
03074     unsigned PathLengthToMember =
03075         LV.Designator.Entries.size() - MemPtr.Path.size();
03076     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
03077       const CXXRecordDecl *LVDecl = getAsBaseClass(
03078           LV.Designator.Entries[PathLengthToMember + I]);
03079       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
03080       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
03081         Info.Diag(RHS);
03082         return nullptr;
03083       }
03084     }
03085 
03086     // Truncate the lvalue to the appropriate derived class.
03087     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
03088                             PathLengthToMember))
03089       return nullptr;
03090   } else if (!MemPtr.Path.empty()) {
03091     // Extend the LValue path with the member pointer's path.
03092     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
03093                                   MemPtr.Path.size() + IncludeMember);
03094 
03095     // Walk down to the appropriate base class.
03096     if (const PointerType *PT = LVType->getAs<PointerType>())
03097       LVType = PT->getPointeeType();
03098     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
03099     assert(RD && "member pointer access on non-class-type expression");
03100     // The first class in the path is that of the lvalue.
03101     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
03102       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
03103       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
03104         return nullptr;
03105       RD = Base;
03106     }
03107     // Finally cast to the class containing the member.
03108     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
03109                                 MemPtr.getContainingRecord()))
03110       return nullptr;
03111   }
03112 
03113   // Add the member. Note that we cannot build bound member functions here.
03114   if (IncludeMember) {
03115     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
03116       if (!HandleLValueMember(Info, RHS, LV, FD))
03117         return nullptr;
03118     } else if (const IndirectFieldDecl *IFD =
03119                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
03120       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
03121         return nullptr;
03122     } else {
03123       llvm_unreachable("can't construct reference to bound member function");
03124     }
03125   }
03126 
03127   return MemPtr.getDecl();
03128 }
03129 
03130 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
03131                                                   const BinaryOperator *BO,
03132                                                   LValue &LV,
03133                                                   bool IncludeMember = true) {
03134   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
03135 
03136   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
03137     if (Info.keepEvaluatingAfterFailure()) {
03138       MemberPtr MemPtr;
03139       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
03140     }
03141     return nullptr;
03142   }
03143 
03144   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
03145                                    BO->getRHS(), IncludeMember);
03146 }
03147 
03148 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
03149 /// the provided lvalue, which currently refers to the base object.
03150 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
03151                                     LValue &Result) {
03152   SubobjectDesignator &D = Result.Designator;
03153   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
03154     return false;
03155 
03156   QualType TargetQT = E->getType();
03157   if (const PointerType *PT = TargetQT->getAs<PointerType>())
03158     TargetQT = PT->getPointeeType();
03159 
03160   // Check this cast lands within the final derived-to-base subobject path.
03161   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
03162     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
03163       << D.MostDerivedType << TargetQT;
03164     return false;
03165   }
03166 
03167   // Check the type of the final cast. We don't need to check the path,
03168   // since a cast can only be formed if the path is unique.
03169   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
03170   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
03171   const CXXRecordDecl *FinalType;
03172   if (NewEntriesSize == D.MostDerivedPathLength)
03173     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
03174   else
03175     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
03176   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
03177     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
03178       << D.MostDerivedType << TargetQT;
03179     return false;
03180   }
03181 
03182   // Truncate the lvalue to the appropriate derived class.
03183   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
03184 }
03185 
03186 namespace {
03187 enum EvalStmtResult {
03188   /// Evaluation failed.
03189   ESR_Failed,
03190   /// Hit a 'return' statement.
03191   ESR_Returned,
03192   /// Evaluation succeeded.
03193   ESR_Succeeded,
03194   /// Hit a 'continue' statement.
03195   ESR_Continue,
03196   /// Hit a 'break' statement.
03197   ESR_Break,
03198   /// Still scanning for 'case' or 'default' statement.
03199   ESR_CaseNotFound
03200 };
03201 }
03202 
03203 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
03204   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
03205     // We don't need to evaluate the initializer for a static local.
03206     if (!VD->hasLocalStorage())
03207       return true;
03208 
03209     LValue Result;
03210     Result.set(VD, Info.CurrentCall->Index);
03211     APValue &Val = Info.CurrentCall->createTemporary(VD, true);
03212 
03213     const Expr *InitE = VD->getInit();
03214     if (!InitE) {
03215       Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
03216         << false << VD->getType();
03217       Val = APValue();
03218       return false;
03219     }
03220 
03221     if (InitE->isValueDependent())
03222       return false;
03223 
03224     if (!EvaluateInPlace(Val, Info, Result, InitE)) {
03225       // Wipe out any partially-computed value, to allow tracking that this
03226       // evaluation failed.
03227       Val = APValue();
03228       return false;
03229     }
03230   }
03231 
03232   return true;
03233 }
03234 
03235 /// Evaluate a condition (either a variable declaration or an expression).
03236 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
03237                          const Expr *Cond, bool &Result) {
03238   FullExpressionRAII Scope(Info);
03239   if (CondDecl && !EvaluateDecl(Info, CondDecl))
03240     return false;
03241   return EvaluateAsBooleanCondition(Cond, Result, Info);
03242 }
03243 
03244 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
03245                                    const Stmt *S,
03246                                    const SwitchCase *SC = nullptr);
03247 
03248 /// Evaluate the body of a loop, and translate the result as appropriate.
03249 static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
03250                                        const Stmt *Body,
03251                                        const SwitchCase *Case = nullptr) {
03252   BlockScopeRAII Scope(Info);
03253   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
03254   case ESR_Break:
03255     return ESR_Succeeded;
03256   case ESR_Succeeded:
03257   case ESR_Continue:
03258     return ESR_Continue;
03259   case ESR_Failed:
03260   case ESR_Returned:
03261   case ESR_CaseNotFound:
03262     return ESR;
03263   }
03264   llvm_unreachable("Invalid EvalStmtResult!");
03265 }
03266 
03267 /// Evaluate a switch statement.
03268 static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
03269                                      const SwitchStmt *SS) {
03270   BlockScopeRAII Scope(Info);
03271 
03272   // Evaluate the switch condition.
03273   APSInt Value;
03274   {
03275     FullExpressionRAII Scope(Info);
03276     if (SS->getConditionVariable() &&
03277         !EvaluateDecl(Info, SS->getConditionVariable()))
03278       return ESR_Failed;
03279     if (!EvaluateInteger(SS->getCond(), Value, Info))
03280       return ESR_Failed;
03281   }
03282 
03283   // Find the switch case corresponding to the value of the condition.
03284   // FIXME: Cache this lookup.
03285   const SwitchCase *Found = nullptr;
03286   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
03287        SC = SC->getNextSwitchCase()) {
03288     if (isa<DefaultStmt>(SC)) {
03289       Found = SC;
03290       continue;
03291     }
03292 
03293     const CaseStmt *CS = cast<CaseStmt>(SC);
03294     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
03295     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
03296                               : LHS;
03297     if (LHS <= Value && Value <= RHS) {
03298       Found = SC;
03299       break;
03300     }
03301   }
03302 
03303   if (!Found)
03304     return ESR_Succeeded;
03305 
03306   // Search the switch body for the switch case and evaluate it from there.
03307   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
03308   case ESR_Break:
03309     return ESR_Succeeded;
03310   case ESR_Succeeded:
03311   case ESR_Continue:
03312   case ESR_Failed:
03313   case ESR_Returned:
03314     return ESR;
03315   case ESR_CaseNotFound:
03316     // This can only happen if the switch case is nested within a statement
03317     // expression. We have no intention of supporting that.
03318     Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
03319     return ESR_Failed;
03320   }
03321   llvm_unreachable("Invalid EvalStmtResult!");
03322 }
03323 
03324 // Evaluate a statement.
03325 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
03326                                    const Stmt *S, const SwitchCase *Case) {
03327   if (!Info.nextStep(S))
03328     return ESR_Failed;
03329 
03330   // If we're hunting down a 'case' or 'default' label, recurse through
03331   // substatements until we hit the label.
03332   if (Case) {
03333     // FIXME: We don't start the lifetime of objects whose initialization we
03334     // jump over. However, such objects must be of class type with a trivial
03335     // default constructor that initialize all subobjects, so must be empty,
03336     // so this almost never matters.
03337     switch (S->getStmtClass()) {
03338     case Stmt::CompoundStmtClass:
03339       // FIXME: Precompute which substatement of a compound statement we
03340       // would jump to, and go straight there rather than performing a
03341       // linear scan each time.
03342     case Stmt::LabelStmtClass:
03343     case Stmt::AttributedStmtClass:
03344     case Stmt::DoStmtClass:
03345       break;
03346 
03347     case Stmt::CaseStmtClass:
03348     case Stmt::DefaultStmtClass:
03349       if (Case == S)
03350         Case = nullptr;
03351       break;
03352 
03353     case Stmt::IfStmtClass: {
03354       // FIXME: Precompute which side of an 'if' we would jump to, and go
03355       // straight there rather than scanning both sides.
03356       const IfStmt *IS = cast<IfStmt>(S);
03357 
03358       // Wrap the evaluation in a block scope, in case it's a DeclStmt
03359       // preceded by our switch label.
03360       BlockScopeRAII Scope(Info);
03361 
03362       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
03363       if (ESR != ESR_CaseNotFound || !IS->getElse())
03364         return ESR;
03365       return EvaluateStmt(Result, Info, IS->getElse(), Case);
03366     }
03367 
03368     case Stmt::WhileStmtClass: {
03369       EvalStmtResult ESR =
03370           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
03371       if (ESR != ESR_Continue)
03372         return ESR;
03373       break;
03374     }
03375 
03376     case Stmt::ForStmtClass: {
03377       const ForStmt *FS = cast<ForStmt>(S);
03378       EvalStmtResult ESR =
03379           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
03380       if (ESR != ESR_Continue)
03381         return ESR;
03382       if (FS->getInc()) {
03383         FullExpressionRAII IncScope(Info);
03384         if (!EvaluateIgnoredValue(Info, FS->getInc()))
03385           return ESR_Failed;
03386       }
03387       break;
03388     }
03389 
03390     case Stmt::DeclStmtClass:
03391       // FIXME: If the variable has initialization that can't be jumped over,
03392       // bail out of any immediately-surrounding compound-statement too.
03393     default:
03394       return ESR_CaseNotFound;
03395     }
03396   }
03397 
03398   switch (S->getStmtClass()) {
03399   default:
03400     if (const Expr *E = dyn_cast<Expr>(S)) {
03401       // Don't bother evaluating beyond an expression-statement which couldn't
03402       // be evaluated.
03403       FullExpressionRAII Scope(Info);
03404       if (!EvaluateIgnoredValue(Info, E))
03405         return ESR_Failed;
03406       return ESR_Succeeded;
03407     }
03408 
03409     Info.Diag(S->getLocStart());
03410     return ESR_Failed;
03411 
03412   case Stmt::NullStmtClass:
03413     return ESR_Succeeded;
03414 
03415   case Stmt::DeclStmtClass: {
03416     const DeclStmt *DS = cast<DeclStmt>(S);
03417     for (const auto *DclIt : DS->decls()) {
03418       // Each declaration initialization is its own full-expression.
03419       // FIXME: This isn't quite right; if we're performing aggregate
03420       // initialization, each braced subexpression is its own full-expression.
03421       FullExpressionRAII Scope(Info);
03422       if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
03423         return ESR_Failed;
03424     }
03425     return ESR_Succeeded;
03426   }
03427 
03428   case Stmt::ReturnStmtClass: {
03429     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
03430     FullExpressionRAII Scope(Info);
03431     if (RetExpr && !Evaluate(Result, Info, RetExpr))
03432       return ESR_Failed;
03433     return ESR_Returned;
03434   }
03435 
03436   case Stmt::CompoundStmtClass: {
03437     BlockScopeRAII Scope(Info);
03438 
03439     const CompoundStmt *CS = cast<CompoundStmt>(S);
03440     for (const auto *BI : CS->body()) {
03441       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
03442       if (ESR == ESR_Succeeded)
03443         Case = nullptr;
03444       else if (ESR != ESR_CaseNotFound)
03445         return ESR;
03446     }
03447     return Case ? ESR_CaseNotFound : ESR_Succeeded;
03448   }
03449 
03450   case Stmt::IfStmtClass: {
03451     const IfStmt *IS = cast<IfStmt>(S);
03452 
03453     // Evaluate the condition, as either a var decl or as an expression.
03454     BlockScopeRAII Scope(Info);
03455     bool Cond;
03456     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
03457       return ESR_Failed;
03458 
03459     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
03460       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
03461       if (ESR != ESR_Succeeded)
03462         return ESR;
03463     }
03464     return ESR_Succeeded;
03465   }
03466 
03467   case Stmt::WhileStmtClass: {
03468     const WhileStmt *WS = cast<WhileStmt>(S);
03469     while (true) {
03470       BlockScopeRAII Scope(Info);
03471       bool Continue;
03472       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
03473                         Continue))
03474         return ESR_Failed;
03475       if (!Continue)
03476         break;
03477 
03478       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
03479       if (ESR != ESR_Continue)
03480         return ESR;
03481     }
03482     return ESR_Succeeded;
03483   }
03484 
03485   case Stmt::DoStmtClass: {
03486     const DoStmt *DS = cast<DoStmt>(S);
03487     bool Continue;
03488     do {
03489       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
03490       if (ESR != ESR_Continue)
03491         return ESR;
03492       Case = nullptr;
03493 
03494       FullExpressionRAII CondScope(Info);
03495       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
03496         return ESR_Failed;
03497     } while (Continue);
03498     return ESR_Succeeded;
03499   }
03500 
03501   case Stmt::ForStmtClass: {
03502     const ForStmt *FS = cast<ForStmt>(S);
03503     BlockScopeRAII Scope(Info);
03504     if (FS->getInit()) {
03505       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
03506       if (ESR != ESR_Succeeded)
03507         return ESR;
03508     }
03509     while (true) {
03510       BlockScopeRAII Scope(Info);
03511       bool Continue = true;
03512       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
03513                                          FS->getCond(), Continue))
03514         return ESR_Failed;
03515       if (!Continue)
03516         break;
03517 
03518       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
03519       if (ESR != ESR_Continue)
03520         return ESR;
03521 
03522       if (FS->getInc()) {
03523         FullExpressionRAII IncScope(Info);
03524         if (!EvaluateIgnoredValue(Info, FS->getInc()))
03525           return ESR_Failed;
03526       }
03527     }
03528     return ESR_Succeeded;
03529   }
03530 
03531   case Stmt::CXXForRangeStmtClass: {
03532     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
03533     BlockScopeRAII Scope(Info);
03534 
03535     // Initialize the __range variable.
03536     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
03537     if (ESR != ESR_Succeeded)
03538       return ESR;
03539 
03540     // Create the __begin and __end iterators.
03541     ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
03542     if (ESR != ESR_Succeeded)
03543       return ESR;
03544 
03545     while (true) {
03546       // Condition: __begin != __end.
03547       {
03548         bool Continue = true;
03549         FullExpressionRAII CondExpr(Info);
03550         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
03551           return ESR_Failed;
03552         if (!Continue)
03553           break;
03554       }
03555 
03556       // User's variable declaration, initialized by *__begin.
03557       BlockScopeRAII InnerScope(Info);
03558       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
03559       if (ESR != ESR_Succeeded)
03560         return ESR;
03561 
03562       // Loop body.
03563       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
03564       if (ESR != ESR_Continue)
03565         return ESR;
03566 
03567       // Increment: ++__begin
03568       if (!EvaluateIgnoredValue(Info, FS->getInc()))
03569         return ESR_Failed;
03570     }
03571 
03572     return ESR_Succeeded;
03573   }
03574 
03575   case Stmt::SwitchStmtClass:
03576     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
03577 
03578   case Stmt::ContinueStmtClass:
03579     return ESR_Continue;
03580 
03581   case Stmt::BreakStmtClass:
03582     return ESR_Break;
03583 
03584   case Stmt::LabelStmtClass:
03585     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
03586 
03587   case Stmt::AttributedStmtClass:
03588     // As a general principle, C++11 attributes can be ignored without
03589     // any semantic impact.
03590     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
03591                         Case);
03592 
03593   case Stmt::CaseStmtClass:
03594   case Stmt::DefaultStmtClass:
03595     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
03596   }
03597 }
03598 
03599 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
03600 /// default constructor. If so, we'll fold it whether or not it's marked as
03601 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
03602 /// so we need special handling.
03603 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
03604                                            const CXXConstructorDecl *CD,
03605                                            bool IsValueInitialization) {
03606   if (!CD->isTrivial() || !CD->isDefaultConstructor())
03607     return false;
03608 
03609   // Value-initialization does not call a trivial default constructor, so such a
03610   // call is a core constant expression whether or not the constructor is
03611   // constexpr.
03612   if (!CD->isConstexpr() && !IsValueInitialization) {
03613     if (Info.getLangOpts().CPlusPlus11) {
03614       // FIXME: If DiagDecl is an implicitly-declared special member function,
03615       // we should be much more explicit about why it's not constexpr.
03616       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
03617         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
03618       Info.Note(CD->getLocation(), diag::note_declared_at);
03619     } else {
03620       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
03621     }
03622   }
03623   return true;
03624 }
03625 
03626 /// CheckConstexprFunction - Check that a function can be called in a constant
03627 /// expression.
03628 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
03629                                    const FunctionDecl *Declaration,
03630                                    const FunctionDecl *Definition) {
03631   // Potential constant expressions can contain calls to declared, but not yet
03632   // defined, constexpr functions.
03633   if (Info.checkingPotentialConstantExpression() && !Definition &&
03634       Declaration->isConstexpr())
03635     return false;
03636 
03637   // Bail out with no diagnostic if the function declaration itself is invalid.
03638   // We will have produced a relevant diagnostic while parsing it.
03639   if (Declaration->isInvalidDecl())
03640     return false;
03641 
03642   // Can we evaluate this function call?
03643   if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
03644     return true;
03645 
03646   if (Info.getLangOpts().CPlusPlus11) {
03647     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
03648     // FIXME: If DiagDecl is an implicitly-declared special member function, we
03649     // should be much more explicit about why it's not constexpr.
03650     Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
03651       << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
03652       << DiagDecl;
03653     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
03654   } else {
03655     Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
03656   }
03657   return false;
03658 }
03659 
03660 namespace {
03661 typedef SmallVector<APValue, 8> ArgVector;
03662 }
03663 
03664 /// EvaluateArgs - Evaluate the arguments to a function call.
03665 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
03666                          EvalInfo &Info) {
03667   bool Success = true;
03668   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
03669        I != E; ++I) {
03670     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
03671       // If we're checking for a potential constant expression, evaluate all
03672       // initializers even if some of them fail.
03673       if (!Info.keepEvaluatingAfterFailure())
03674         return false;
03675       Success = false;
03676     }
03677   }
03678   return Success;
03679 }
03680 
03681 /// Evaluate a function call.
03682 static bool HandleFunctionCall(SourceLocation CallLoc,
03683                                const FunctionDecl *Callee, const LValue *This,
03684                                ArrayRef<const Expr*> Args, const Stmt *Body,
03685                                EvalInfo &Info, APValue &Result) {
03686   ArgVector ArgValues(Args.size());
03687   if (!EvaluateArgs(Args, ArgValues, Info))
03688     return false;
03689 
03690   if (!Info.CheckCallLimit(CallLoc))
03691     return false;
03692 
03693   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
03694 
03695   // For a trivial copy or move assignment, perform an APValue copy. This is
03696   // essential for unions, where the operations performed by the assignment
03697   // operator cannot be represented as statements.
03698   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
03699   if (MD && MD->isDefaulted() && MD->isTrivial()) {
03700     assert(This &&
03701            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
03702     LValue RHS;
03703     RHS.setFrom(Info.Ctx, ArgValues[0]);
03704     APValue RHSValue;
03705     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
03706                                         RHS, RHSValue))
03707       return false;
03708     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
03709                           RHSValue))
03710       return false;
03711     This->moveInto(Result);
03712     return true;
03713   }
03714 
03715   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
03716   if (ESR == ESR_Succeeded) {
03717     if (Callee->getReturnType()->isVoidType())
03718       return true;
03719     Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
03720   }
03721   return ESR == ESR_Returned;
03722 }
03723 
03724 /// Evaluate a constructor call.
03725 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
03726                                   ArrayRef<const Expr*> Args,
03727                                   const CXXConstructorDecl *Definition,
03728                                   EvalInfo &Info, APValue &Result) {
03729   ArgVector ArgValues(Args.size());
03730   if (!EvaluateArgs(Args, ArgValues, Info))
03731     return false;
03732 
03733   if (!Info.CheckCallLimit(CallLoc))
03734     return false;
03735 
03736   const CXXRecordDecl *RD = Definition->getParent();
03737   if (RD->getNumVBases()) {
03738     Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
03739     return false;
03740   }
03741 
03742   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
03743 
03744   // If it's a delegating constructor, just delegate.
03745   if (Definition->isDelegatingConstructor()) {
03746     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
03747     {
03748       FullExpressionRAII InitScope(Info);
03749       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
03750         return false;
03751     }
03752     return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
03753   }
03754 
03755   // For a trivial copy or move constructor, perform an APValue copy. This is
03756   // essential for unions, where the operations performed by the constructor
03757   // cannot be represented by ctor-initializers.
03758   if (Definition->isDefaulted() &&
03759       ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
03760        (Definition->isMoveConstructor() && Definition->isTrivial()))) {
03761     LValue RHS;
03762     RHS.setFrom(Info.Ctx, ArgValues[0]);
03763     return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
03764                                           RHS, Result);
03765   }
03766 
03767   // Reserve space for the struct members.
03768   if (!RD->isUnion() && Result.isUninit())
03769     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
03770                      std::distance(RD->field_begin(), RD->field_end()));
03771 
03772   if (RD->isInvalidDecl()) return false;
03773   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
03774 
03775   // A scope for temporaries lifetime-extended by reference members.
03776   BlockScopeRAII LifetimeExtendedScope(Info);
03777 
03778   bool Success = true;
03779   unsigned BasesSeen = 0;
03780 #ifndef NDEBUG
03781   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
03782 #endif
03783   for (const auto *I : Definition->inits()) {
03784     LValue Subobject = This;
03785     APValue *Value = &Result;
03786 
03787     // Determine the subobject to initialize.
03788     FieldDecl *FD = nullptr;
03789     if (I->isBaseInitializer()) {
03790       QualType BaseType(I->getBaseClass(), 0);
03791 #ifndef NDEBUG
03792       // Non-virtual base classes are initialized in the order in the class
03793       // definition. We have already checked for virtual base classes.
03794       assert(!BaseIt->isVirtual() && "virtual base for literal type");
03795       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
03796              "base class initializers not in expected order");
03797       ++BaseIt;
03798 #endif
03799       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
03800                                   BaseType->getAsCXXRecordDecl(), &Layout))
03801         return false;
03802       Value = &Result.getStructBase(BasesSeen++);
03803     } else if ((FD = I->getMember())) {
03804       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
03805         return false;
03806       if (RD->isUnion()) {
03807         Result = APValue(FD);
03808         Value = &Result.getUnionValue();
03809       } else {
03810         Value = &Result.getStructField(FD->getFieldIndex());
03811       }
03812     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
03813       // Walk the indirect field decl's chain to find the object to initialize,
03814       // and make sure we've initialized every step along it.
03815       for (auto *C : IFD->chain()) {
03816         FD = cast<FieldDecl>(C);
03817         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
03818         // Switch the union field if it differs. This happens if we had
03819         // preceding zero-initialization, and we're now initializing a union
03820         // subobject other than the first.
03821         // FIXME: In this case, the values of the other subobjects are
03822         // specified, since zero-initialization sets all padding bits to zero.
03823         if (Value->isUninit() ||
03824             (Value->isUnion() && Value->getUnionField() != FD)) {
03825           if (CD->isUnion())
03826             *Value = APValue(FD);
03827           else
03828             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
03829                              std::distance(CD->field_begin(), CD->field_end()));
03830         }
03831         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
03832           return false;
03833         if (CD->isUnion())
03834           Value = &Value->getUnionValue();
03835         else
03836           Value = &Value->getStructField(FD->getFieldIndex());
03837       }
03838     } else {
03839       llvm_unreachable("unknown base initializer kind");
03840     }
03841 
03842     FullExpressionRAII InitScope(Info);
03843     if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
03844         (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
03845                                                           *Value, FD))) {
03846       // If we're checking for a potential constant expression, evaluate all
03847       // initializers even if some of them fail.
03848       if (!Info.keepEvaluatingAfterFailure())
03849         return false;
03850       Success = false;
03851     }
03852   }
03853 
03854   return Success &&
03855          EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
03856 }
03857 
03858 //===----------------------------------------------------------------------===//
03859 // Generic Evaluation
03860 //===----------------------------------------------------------------------===//
03861 namespace {
03862 
03863 template <class Derived>
03864 class ExprEvaluatorBase
03865   : public ConstStmtVisitor<Derived, bool> {
03866 private:
03867   bool DerivedSuccess(const APValue &V, const Expr *E) {
03868     return static_cast<Derived*>(this)->Success(V, E);
03869   }
03870   bool DerivedZeroInitialization(const Expr *E) {
03871     return static_cast<Derived*>(this)->ZeroInitialization(E);
03872   }
03873 
03874   // Check whether a conditional operator with a non-constant condition is a
03875   // potential constant expression. If neither arm is a potential constant
03876   // expression, then the conditional operator is not either.
03877   template<typename ConditionalOperator>
03878   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
03879     assert(Info.checkingPotentialConstantExpression());
03880 
03881     // Speculatively evaluate both arms.
03882     {
03883       SmallVector<PartialDiagnosticAt, 8> Diag;
03884       SpeculativeEvaluationRAII Speculate(Info, &Diag);
03885 
03886       StmtVisitorTy::Visit(E->getFalseExpr());
03887       if (Diag.empty())
03888         return;
03889 
03890       Diag.clear();
03891       StmtVisitorTy::Visit(E->getTrueExpr());
03892       if (Diag.empty())
03893         return;
03894     }
03895 
03896     Error(E, diag::note_constexpr_conditional_never_const);
03897   }
03898 
03899 
03900   template<typename ConditionalOperator>
03901   bool HandleConditionalOperator(const ConditionalOperator *E) {
03902     bool BoolResult;
03903     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
03904       if (Info.checkingPotentialConstantExpression())
03905         CheckPotentialConstantConditional(E);
03906       return false;
03907     }
03908 
03909     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
03910     return StmtVisitorTy::Visit(EvalExpr);
03911   }
03912 
03913 protected:
03914   EvalInfo &Info;
03915   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
03916   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
03917 
03918   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
03919     return Info.CCEDiag(E, D);
03920   }
03921 
03922   bool ZeroInitialization(const Expr *E) { return Error(E); }
03923 
03924 public:
03925   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
03926 
03927   EvalInfo &getEvalInfo() { return Info; }
03928 
03929   /// Report an evaluation error. This should only be called when an error is
03930   /// first discovered. When propagating an error, just return false.
03931   bool Error(const Expr *E, diag::kind D) {
03932     Info.Diag(E, D);
03933     return false;
03934   }
03935   bool Error(const Expr *E) {
03936     return Error(E, diag::note_invalid_subexpr_in_const_expr);
03937   }
03938 
03939   bool VisitStmt(const Stmt *) {
03940     llvm_unreachable("Expression evaluator should not be called on stmts");
03941   }
03942   bool VisitExpr(const Expr *E) {
03943     return Error(E);
03944   }
03945 
03946   bool VisitParenExpr(const ParenExpr *E)
03947     { return StmtVisitorTy::Visit(E->getSubExpr()); }
03948   bool VisitUnaryExtension(const UnaryOperator *E)
03949     { return StmtVisitorTy::Visit(E->getSubExpr()); }
03950   bool VisitUnaryPlus(const UnaryOperator *E)
03951     { return StmtVisitorTy::Visit(E->getSubExpr()); }
03952   bool VisitChooseExpr(const ChooseExpr *E)
03953     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
03954   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
03955     { return StmtVisitorTy::Visit(E->getResultExpr()); }
03956   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
03957     { return StmtVisitorTy::Visit(E->getReplacement()); }
03958   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
03959     { return StmtVisitorTy::Visit(E->getExpr()); }
03960   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
03961     // The initializer may not have been parsed yet, or might be erroneous.
03962     if (!E->getExpr())
03963       return Error(E);
03964     return StmtVisitorTy::Visit(E->getExpr());
03965   }
03966   // We cannot create any objects for which cleanups are required, so there is
03967   // nothing to do here; all cleanups must come from unevaluated subexpressions.
03968   bool VisitExprWithCleanups(const ExprWithCleanups *E)
03969     { return StmtVisitorTy::Visit(E->getSubExpr()); }
03970 
03971   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
03972     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
03973     return static_cast<Derived*>(this)->VisitCastExpr(E);
03974   }
03975   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
03976     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
03977     return static_cast<Derived*>(this)->VisitCastExpr(E);
03978   }
03979 
03980   bool VisitBinaryOperator(const BinaryOperator *E) {
03981     switch (E->getOpcode()) {
03982     default:
03983       return Error(E);
03984 
03985     case BO_Comma:
03986       VisitIgnoredValue(E->getLHS());
03987       return StmtVisitorTy::Visit(E->getRHS());
03988 
03989     case BO_PtrMemD:
03990     case BO_PtrMemI: {
03991       LValue Obj;
03992       if (!HandleMemberPointerAccess(Info, E, Obj))
03993         return false;
03994       APValue Result;
03995       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
03996         return false;
03997       return DerivedSuccess(Result, E);
03998     }
03999     }
04000   }
04001 
04002   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
04003     // Evaluate and cache the common expression. We treat it as a temporary,
04004     // even though it's not quite the same thing.
04005     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
04006                   Info, E->getCommon()))
04007       return false;
04008 
04009     return HandleConditionalOperator(E);
04010   }
04011 
04012   bool VisitConditionalOperator(const ConditionalOperator *E) {
04013     bool IsBcpCall = false;
04014     // If the condition (ignoring parens) is a __builtin_constant_p call,
04015     // the result is a constant expression if it can be folded without
04016     // side-effects. This is an important GNU extension. See GCC PR38377
04017     // for discussion.
04018     if (const CallExpr *CallCE =
04019           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
04020       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
04021         IsBcpCall = true;
04022 
04023     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
04024     // constant expression; we can't check whether it's potentially foldable.
04025     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
04026       return false;
04027 
04028     FoldConstant Fold(Info, IsBcpCall);
04029     if (!HandleConditionalOperator(E)) {
04030       Fold.keepDiagnostics();
04031       return false;
04032     }
04033 
04034     return true;
04035   }
04036 
04037   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
04038     if (APValue *Value = Info.CurrentCall->getTemporary(E))
04039       return DerivedSuccess(*Value, E);
04040 
04041     const Expr *Source = E->getSourceExpr();
04042     if (!Source)
04043       return Error(E);
04044     if (Source == E) { // sanity checking.
04045       assert(0 && "OpaqueValueExpr recursively refers to itself");
04046       return Error(E);
04047     }
04048     return StmtVisitorTy::Visit(Source);
04049   }
04050 
04051   bool VisitCallExpr(const CallExpr *E) {
04052     const Expr *Callee = E->getCallee()->IgnoreParens();
04053     QualType CalleeType = Callee->getType();
04054 
04055     const FunctionDecl *FD = nullptr;
04056     LValue *This = nullptr, ThisVal;
04057     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
04058     bool HasQualifier = false;
04059 
04060     // Extract function decl and 'this' pointer from the callee.
04061     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
04062       const ValueDecl *Member = nullptr;
04063       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
04064         // Explicit bound member calls, such as x.f() or p->g();
04065         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
04066           return false;
04067         Member = ME->getMemberDecl();
04068         This = &ThisVal;
04069         HasQualifier = ME->hasQualifier();
04070       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
04071         // Indirect bound member calls ('.*' or '->*').
04072         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
04073         if (!Member) return false;
04074         This = &ThisVal;
04075       } else
04076         return Error(Callee);
04077 
04078       FD = dyn_cast<FunctionDecl>(Member);
04079       if (!FD)
04080         return Error(Callee);
04081     } else if (CalleeType->isFunctionPointerType()) {
04082       LValue Call;
04083       if (!EvaluatePointer(Callee, Call, Info))
04084         return false;
04085 
04086       if (!Call.getLValueOffset().isZero())
04087         return Error(Callee);
04088       FD = dyn_cast_or_null<FunctionDecl>(
04089                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
04090       if (!FD)
04091         return Error(Callee);
04092 
04093       // Overloaded operator calls to member functions are represented as normal
04094       // calls with '*this' as the first argument.
04095       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
04096       if (MD && !MD->isStatic()) {
04097         // FIXME: When selecting an implicit conversion for an overloaded
04098         // operator delete, we sometimes try to evaluate calls to conversion
04099         // operators without a 'this' parameter!
04100         if (Args.empty())
04101           return Error(E);
04102 
04103         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
04104           return false;
04105         This = &ThisVal;
04106         Args = Args.slice(1);
04107       }
04108 
04109       // Don't call function pointers which have been cast to some other type.
04110       if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
04111         return Error(E);
04112     } else
04113       return Error(E);
04114 
04115     if (This && !This->checkSubobject(Info, E, CSK_This))
04116       return false;
04117 
04118     // DR1358 allows virtual constexpr functions in some cases. Don't allow
04119     // calls to such functions in constant expressions.
04120     if (This && !HasQualifier &&
04121         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
04122       return Error(E, diag::note_constexpr_virtual_call);
04123 
04124     const FunctionDecl *Definition = nullptr;
04125     Stmt *Body = FD->getBody(Definition);
04126     APValue Result;
04127 
04128     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
04129         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
04130                             Info, Result))
04131       return false;
04132 
04133     return DerivedSuccess(Result, E);
04134   }
04135 
04136   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
04137     return StmtVisitorTy::Visit(E->getInitializer());
04138   }
04139   bool VisitInitListExpr(const InitListExpr *E) {
04140     if (E->getNumInits() == 0)
04141       return DerivedZeroInitialization(E);
04142     if (E->getNumInits() == 1)
04143       return StmtVisitorTy::Visit(E->getInit(0));
04144     return Error(E);
04145   }
04146   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
04147     return DerivedZeroInitialization(E);
04148   }
04149   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
04150     return DerivedZeroInitialization(E);
04151   }
04152   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
04153     return DerivedZeroInitialization(E);
04154   }
04155 
04156   /// A member expression where the object is a prvalue is itself a prvalue.
04157   bool VisitMemberExpr(const MemberExpr *E) {
04158     assert(!E->isArrow() && "missing call to bound member function?");
04159 
04160     APValue Val;
04161     if (!Evaluate(Val, Info, E->getBase()))
04162       return false;
04163 
04164     QualType BaseTy = E->getBase()->getType();
04165 
04166     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
04167     if (!FD) return Error(E);
04168     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
04169     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
04170            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
04171 
04172     CompleteObject Obj(&Val, BaseTy);
04173     SubobjectDesignator Designator(BaseTy);
04174     Designator.addDeclUnchecked(FD);
04175 
04176     APValue Result;
04177     return extractSubobject(Info, E, Obj, Designator, Result) &&
04178            DerivedSuccess(Result, E);
04179   }
04180 
04181   bool VisitCastExpr(const CastExpr *E) {
04182     switch (E->getCastKind()) {
04183     default:
04184       break;
04185 
04186     case CK_AtomicToNonAtomic: {
04187       APValue AtomicVal;
04188       if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
04189         return false;
04190       return DerivedSuccess(AtomicVal, E);
04191     }
04192 
04193     case CK_NoOp:
04194     case CK_UserDefinedConversion:
04195       return StmtVisitorTy::Visit(E->getSubExpr());
04196 
04197     case CK_LValueToRValue: {
04198       LValue LVal;
04199       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
04200         return false;
04201       APValue RVal;
04202       // Note, we use the subexpression's type in order to retain cv-qualifiers.
04203       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
04204                                           LVal, RVal))
04205         return false;
04206       return DerivedSuccess(RVal, E);
04207     }
04208     }
04209 
04210     return Error(E);
04211   }
04212 
04213   bool VisitUnaryPostInc(const UnaryOperator *UO) {
04214     return VisitUnaryPostIncDec(UO);
04215   }
04216   bool VisitUnaryPostDec(const UnaryOperator *UO) {
04217     return VisitUnaryPostIncDec(UO);
04218   }
04219   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
04220     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
04221       return Error(UO);
04222 
04223     LValue LVal;
04224     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
04225       return false;
04226     APValue RVal;
04227     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
04228                       UO->isIncrementOp(), &RVal))
04229       return false;
04230     return DerivedSuccess(RVal, UO);
04231   }
04232 
04233   bool VisitStmtExpr(const StmtExpr *E) {
04234     // We will have checked the full-expressions inside the statement expression
04235     // when they were completed, and don't need to check them again now.
04236     if (Info.checkingForOverflow())
04237       return Error(E);
04238 
04239     BlockScopeRAII Scope(Info);
04240     const CompoundStmt *CS = E->getSubStmt();
04241     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
04242                                            BE = CS->body_end();
04243          /**/; ++BI) {
04244       if (BI + 1 == BE) {
04245         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
04246         if (!FinalExpr) {
04247           Info.Diag((*BI)->getLocStart(),
04248                     diag::note_constexpr_stmt_expr_unsupported);
04249           return false;
04250         }
04251         return this->Visit(FinalExpr);
04252       }
04253 
04254       APValue ReturnValue;
04255       EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
04256       if (ESR != ESR_Succeeded) {
04257         // FIXME: If the statement-expression terminated due to 'return',
04258         // 'break', or 'continue', it would be nice to propagate that to
04259         // the outer statement evaluation rather than bailing out.
04260         if (ESR != ESR_Failed)
04261           Info.Diag((*BI)->getLocStart(),
04262                     diag::note_constexpr_stmt_expr_unsupported);
04263         return false;
04264       }
04265     }
04266   }
04267 
04268   /// Visit a value which is evaluated, but whose value is ignored.
04269   void VisitIgnoredValue(const Expr *E) {
04270     EvaluateIgnoredValue(Info, E);
04271   }
04272 };
04273 
04274 }
04275 
04276 //===----------------------------------------------------------------------===//
04277 // Common base class for lvalue and temporary evaluation.
04278 //===----------------------------------------------------------------------===//
04279 namespace {
04280 template<class Derived>
04281 class LValueExprEvaluatorBase
04282   : public ExprEvaluatorBase<Derived> {
04283 protected:
04284   LValue &Result;
04285   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
04286   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
04287 
04288   bool Success(APValue::LValueBase B) {
04289     Result.set(B);
04290     return true;
04291   }
04292 
04293 public:
04294   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
04295     ExprEvaluatorBaseTy(Info), Result(Result) {}
04296 
04297   bool Success(const APValue &V, const Expr *E) {
04298     Result.setFrom(this->Info.Ctx, V);
04299     return true;
04300   }
04301 
04302   bool VisitMemberExpr(const MemberExpr *E) {
04303     // Handle non-static data members.
04304     QualType BaseTy;
04305     if (E->isArrow()) {
04306       if (!EvaluatePointer(E->getBase(), Result, this->Info))
04307         return false;
04308       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
04309     } else if (E->getBase()->isRValue()) {
04310       assert(E->getBase()->getType()->isRecordType());
04311       if (!EvaluateTemporary(E->getBase(), Result, this->Info))
04312         return false;
04313       BaseTy = E->getBase()->getType();
04314     } else {
04315       if (!this->Visit(E->getBase()))
04316         return false;
04317       BaseTy = E->getBase()->getType();
04318     }
04319 
04320     const ValueDecl *MD = E->getMemberDecl();
04321     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
04322       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
04323              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
04324       (void)BaseTy;
04325       if (!HandleLValueMember(this->Info, E, Result, FD))
04326         return false;
04327     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
04328       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
04329         return false;
04330     } else
04331       return this->Error(E);
04332 
04333     if (MD->getType()->isReferenceType()) {
04334       APValue RefValue;
04335       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
04336                                           RefValue))
04337         return false;
04338       return Success(RefValue, E);
04339     }
04340     return true;
04341   }
04342 
04343   bool VisitBinaryOperator(const BinaryOperator *E) {
04344     switch (E->getOpcode()) {
04345     default:
04346       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
04347 
04348     case BO_PtrMemD:
04349     case BO_PtrMemI:
04350       return HandleMemberPointerAccess(this->Info, E, Result);
04351     }
04352   }
04353 
04354   bool VisitCastExpr(const CastExpr *E) {
04355     switch (E->getCastKind()) {
04356     default:
04357       return ExprEvaluatorBaseTy::VisitCastExpr(E);
04358 
04359     case CK_DerivedToBase:
04360     case CK_UncheckedDerivedToBase:
04361       if (!this->Visit(E->getSubExpr()))
04362         return false;
04363 
04364       // Now figure out the necessary offset to add to the base LV to get from
04365       // the derived class to the base class.
04366       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
04367                                   Result);
04368     }
04369   }
04370 };
04371 }
04372 
04373 //===----------------------------------------------------------------------===//
04374 // LValue Evaluation
04375 //
04376 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
04377 // function designators (in C), decl references to void objects (in C), and
04378 // temporaries (if building with -Wno-address-of-temporary).
04379 //
04380 // LValue evaluation produces values comprising a base expression of one of the
04381 // following types:
04382 // - Declarations
04383 //  * VarDecl
04384 //  * FunctionDecl
04385 // - Literals
04386 //  * CompoundLiteralExpr in C
04387 //  * StringLiteral
04388 //  * CXXTypeidExpr
04389 //  * PredefinedExpr
04390 //  * ObjCStringLiteralExpr
04391 //  * ObjCEncodeExpr
04392 //  * AddrLabelExpr
04393 //  * BlockExpr
04394 //  * CallExpr for a MakeStringConstant builtin
04395 // - Locals and temporaries
04396 //  * MaterializeTemporaryExpr
04397 //  * Any Expr, with a CallIndex indicating the function in which the temporary
04398 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
04399 //    from the AST (FIXME).
04400 //  * A MaterializeTemporaryExpr that has static storage duration, with no
04401 //    CallIndex, for a lifetime-extended temporary.
04402 // plus an offset in bytes.
04403 //===----------------------------------------------------------------------===//
04404 namespace {
04405 class LValueExprEvaluator
04406   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
04407 public:
04408   LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
04409     LValueExprEvaluatorBaseTy(Info, Result) {}
04410 
04411   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
04412   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
04413 
04414   bool VisitDeclRefExpr(const DeclRefExpr *E);
04415   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
04416   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
04417   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
04418   bool VisitMemberExpr(const MemberExpr *E);
04419   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
04420   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
04421   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
04422   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
04423   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
04424   bool VisitUnaryDeref(const UnaryOperator *E);
04425   bool VisitUnaryReal(const UnaryOperator *E);
04426   bool VisitUnaryImag(const UnaryOperator *E);
04427   bool VisitUnaryPreInc(const UnaryOperator *UO) {
04428     return VisitUnaryPreIncDec(UO);
04429   }
04430   bool VisitUnaryPreDec(const UnaryOperator *UO) {
04431     return VisitUnaryPreIncDec(UO);
04432   }
04433   bool VisitBinAssign(const BinaryOperator *BO);
04434   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
04435 
04436   bool VisitCastExpr(const CastExpr *E) {
04437     switch (E->getCastKind()) {
04438     default:
04439       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
04440 
04441     case CK_LValueBitCast:
04442       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
04443       if (!Visit(E->getSubExpr()))
04444         return false;
04445       Result.Designator.setInvalid();
04446       return true;
04447 
04448     case CK_BaseToDerived:
04449       if (!Visit(E->getSubExpr()))
04450         return false;
04451       return HandleBaseToDerivedCast(Info, E, Result);
04452     }
04453   }
04454 };
04455 } // end anonymous namespace
04456 
04457 /// Evaluate an expression as an lvalue. This can be legitimately called on
04458 /// expressions which are not glvalues, in two cases:
04459 ///  * function designators in C, and
04460 ///  * "extern void" objects
04461 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
04462   assert(E->isGLValue() || E->getType()->isFunctionType() ||
04463          E->getType()->isVoidType());
04464   return LValueExprEvaluator(Info, Result).Visit(E);
04465 }
04466 
04467 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
04468   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
04469     return Success(FD);
04470   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
04471     return VisitVarDecl(E, VD);
04472   return Error(E);
04473 }
04474 
04475 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
04476   CallStackFrame *Frame = nullptr;
04477   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
04478     Frame = Info.CurrentCall;
04479 
04480   if (!VD->getType()->isReferenceType()) {
04481     if (Frame) {
04482       Result.set(VD, Frame->Index);
04483       return true;
04484     }
04485     return Success(VD);
04486   }
04487 
04488   APValue *V;
04489   if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
04490     return false;
04491   if (V->isUninit()) {
04492     if (!Info.checkingPotentialConstantExpression())
04493       Info.Diag(E, diag::note_constexpr_use_uninit_reference);
04494     return false;
04495   }
04496   return Success(*V, E);
04497 }
04498 
04499 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
04500     const MaterializeTemporaryExpr *E) {
04501   // Walk through the expression to find the materialized temporary itself.
04502   SmallVector<const Expr *, 2> CommaLHSs;
04503   SmallVector<SubobjectAdjustment, 2> Adjustments;
04504   const Expr *Inner = E->GetTemporaryExpr()->
04505       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
04506 
04507   // If we passed any comma operators, evaluate their LHSs.
04508   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
04509     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
04510       return false;
04511 
04512   // A materialized temporary with static storage duration can appear within the
04513   // result of a constant expression evaluation, so we need to preserve its
04514   // value for use outside this evaluation.
04515   APValue *Value;
04516   if (E->getStorageDuration() == SD_Static) {
04517     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
04518     *Value = APValue();
04519     Result.set(E);
04520   } else {
04521     Value = &Info.CurrentCall->
04522         createTemporary(E, E->getStorageDuration() == SD_Automatic);
04523     Result.set(E, Info.CurrentCall->Index);
04524   }
04525 
04526   QualType Type = Inner->getType();
04527 
04528   // Materialize the temporary itself.
04529   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
04530       (E->getStorageDuration() == SD_Static &&
04531        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
04532     *Value = APValue();
04533     return false;
04534   }
04535 
04536   // Adjust our lvalue to refer to the desired subobject.
04537   for (unsigned I = Adjustments.size(); I != 0; /**/) {
04538     --I;
04539     switch (Adjustments[I].Kind) {
04540     case SubobjectAdjustment::DerivedToBaseAdjustment:
04541       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
04542                                 Type, Result))
04543         return false;
04544       Type = Adjustments[I].DerivedToBase.BasePath->getType();
04545       break;
04546 
04547     case SubobjectAdjustment::FieldAdjustment:
04548       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
04549         return false;
04550       Type = Adjustments[I].Field->getType();
04551       break;
04552 
04553     case SubobjectAdjustment::MemberPointerAdjustment:
04554       if (!HandleMemberPointerAccess(this->Info, Type, Result,
04555                                      Adjustments[I].Ptr.RHS))
04556         return false;
04557       Type = Adjustments[I].Ptr.MPT->getPointeeType();
04558       break;
04559     }
04560   }
04561 
04562   return true;
04563 }
04564 
04565 bool
04566 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
04567   assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
04568   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
04569   // only see this when folding in C, so there's no standard to follow here.
04570   return Success(E);
04571 }
04572 
04573 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
04574   if (!E->isPotentiallyEvaluated())
04575     return Success(E);
04576 
04577   Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
04578     << E->getExprOperand()->getType()
04579     << E->getExprOperand()->getSourceRange();
04580   return false;
04581 }
04582 
04583 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
04584   return Success(E);
04585 }
04586 
04587 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
04588   // Handle static data members.
04589   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
04590     VisitIgnoredValue(E->getBase());
04591     return VisitVarDecl(E, VD);
04592   }
04593 
04594   // Handle static member functions.
04595   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
04596     if (MD->isStatic()) {
04597       VisitIgnoredValue(E->getBase());
04598       return Success(MD);
04599     }
04600   }
04601 
04602   // Handle non-static data members.
04603   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
04604 }
04605 
04606 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
04607   // FIXME: Deal with vectors as array subscript bases.
04608   if (E->getBase()->getType()->isVectorType())
04609     return Error(E);
04610 
04611   if (!EvaluatePointer(E->getBase(), Result, Info))
04612     return false;
04613 
04614   APSInt Index;
04615   if (!EvaluateInteger(E->getIdx(), Index, Info))
04616     return false;
04617 
04618   return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
04619                                      getExtValue(Index));
04620 }
04621 
04622 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
04623   return EvaluatePointer(E->getSubExpr(), Result, Info);
04624 }
04625 
04626 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
04627   if (!Visit(E->getSubExpr()))
04628     return false;
04629   // __real is a no-op on scalar lvalues.
04630   if (E->getSubExpr()->getType()->isAnyComplexType())
04631     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
04632   return true;
04633 }
04634 
04635 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
04636   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
04637          "lvalue __imag__ on scalar?");
04638   if (!Visit(E->getSubExpr()))
04639     return false;
04640   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
04641   return true;
04642 }
04643 
04644 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
04645   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
04646     return Error(UO);
04647 
04648   if (!this->Visit(UO->getSubExpr()))
04649     return false;
04650 
04651   return handleIncDec(
04652       this->Info, UO, Result, UO->getSubExpr()->getType(),
04653       UO->isIncrementOp(), nullptr);
04654 }
04655 
04656 bool LValueExprEvaluator::VisitCompoundAssignOperator(
04657     const CompoundAssignOperator *CAO) {
04658   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
04659     return Error(CAO);
04660 
04661   APValue RHS;
04662 
04663   // The overall lvalue result is the result of evaluating the LHS.
04664   if (!this->Visit(CAO->getLHS())) {
04665     if (Info.keepEvaluatingAfterFailure())
04666       Evaluate(RHS, this->Info, CAO->getRHS());
04667     return false;
04668   }
04669 
04670   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
04671     return false;
04672 
04673   return handleCompoundAssignment(
04674       this->Info, CAO,
04675       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
04676       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
04677 }
04678 
04679 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
04680   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
04681     return Error(E);
04682 
04683   APValue NewVal;
04684 
04685   if (!this->Visit(E->getLHS())) {
04686     if (Info.keepEvaluatingAfterFailure())
04687       Evaluate(NewVal, this->Info, E->getRHS());
04688     return false;
04689   }
04690 
04691   if (!Evaluate(NewVal, this->Info, E->getRHS()))
04692     return false;
04693 
04694   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
04695                           NewVal);
04696 }
04697 
04698 //===----------------------------------------------------------------------===//
04699 // Pointer Evaluation
04700 //===----------------------------------------------------------------------===//
04701 
04702 namespace {
04703 class PointerExprEvaluator
04704   : public ExprEvaluatorBase<PointerExprEvaluator> {
04705   LValue &Result;
04706 
04707   bool Success(const Expr *E) {
04708     Result.set(E);
04709     return true;
04710   }
04711 public:
04712 
04713   PointerExprEvaluator(EvalInfo &info, LValue &Result)
04714     : ExprEvaluatorBaseTy(info), Result(Result) {}
04715 
04716   bool Success(const APValue &V, const Expr *E) {
04717     Result.setFrom(Info.Ctx, V);
04718     return true;
04719   }
04720   bool ZeroInitialization(const Expr *E) {
04721     return Success((Expr*)nullptr);
04722   }
04723 
04724   bool VisitBinaryOperator(const BinaryOperator *E);
04725   bool VisitCastExpr(const CastExpr* E);
04726   bool VisitUnaryAddrOf(const UnaryOperator *E);
04727   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
04728       { return Success(E); }
04729   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
04730       { return Success(E); }    
04731   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
04732       { return Success(E); }
04733   bool VisitCallExpr(const CallExpr *E);
04734   bool VisitBlockExpr(const BlockExpr *E) {
04735     if (!E->getBlockDecl()->hasCaptures())
04736       return Success(E);
04737     return Error(E);
04738   }
04739   bool VisitCXXThisExpr(const CXXThisExpr *E) {
04740     // Can't look at 'this' when checking a potential constant expression.
04741     if (Info.checkingPotentialConstantExpression())
04742       return false;
04743     if (!Info.CurrentCall->This) {
04744       if (Info.getLangOpts().CPlusPlus11)
04745         Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
04746       else
04747         Info.Diag(E);
04748       return false;
04749     }
04750     Result = *Info.CurrentCall->This;
04751     return true;
04752   }
04753 
04754   // FIXME: Missing: @protocol, @selector
04755 };
04756 } // end anonymous namespace
04757 
04758 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
04759   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
04760   return PointerExprEvaluator(Info, Result).Visit(E);
04761 }
04762 
04763 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
04764   if (E->getOpcode() != BO_Add &&
04765       E->getOpcode() != BO_Sub)
04766     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
04767 
04768   const Expr *PExp = E->getLHS();
04769   const Expr *IExp = E->getRHS();
04770   if (IExp->getType()->isPointerType())
04771     std::swap(PExp, IExp);
04772 
04773   bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
04774   if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
04775     return false;
04776 
04777   llvm::APSInt Offset;
04778   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
04779     return false;
04780 
04781   int64_t AdditionalOffset = getExtValue(Offset);
04782   if (E->getOpcode() == BO_Sub)
04783     AdditionalOffset = -AdditionalOffset;
04784 
04785   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
04786   return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
04787                                      AdditionalOffset);
04788 }
04789 
04790 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
04791   return EvaluateLValue(E->getSubExpr(), Result, Info);
04792 }
04793 
04794 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
04795   const Expr* SubExpr = E->getSubExpr();
04796 
04797   switch (E->getCastKind()) {
04798   default:
04799     break;
04800 
04801   case CK_BitCast:
04802   case CK_CPointerToObjCPointerCast:
04803   case CK_BlockPointerToObjCPointerCast:
04804   case CK_AnyPointerToBlockPointerCast:
04805     if (!Visit(SubExpr))
04806       return false;
04807     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
04808     // permitted in constant expressions in C++11. Bitcasts from cv void* are
04809     // also static_casts, but we disallow them as a resolution to DR1312.
04810     if (!E->getType()->isVoidPointerType()) {
04811       Result.Designator.setInvalid();
04812       if (SubExpr->getType()->isVoidPointerType())
04813         CCEDiag(E, diag::note_constexpr_invalid_cast)
04814           << 3 << SubExpr->getType();
04815       else
04816         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
04817     }
04818     return true;
04819 
04820   case CK_DerivedToBase:
04821   case CK_UncheckedDerivedToBase:
04822     if (!EvaluatePointer(E->getSubExpr(), Result, Info))
04823       return false;
04824     if (!Result.Base && Result.Offset.isZero())
04825       return true;
04826 
04827     // Now figure out the necessary offset to add to the base LV to get from
04828     // the derived class to the base class.
04829     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
04830                                   castAs<PointerType>()->getPointeeType(),
04831                                 Result);
04832 
04833   case CK_BaseToDerived:
04834     if (!Visit(E->getSubExpr()))
04835       return false;
04836     if (!Result.Base && Result.Offset.isZero())
04837       return true;
04838     return HandleBaseToDerivedCast(Info, E, Result);
04839 
04840   case CK_NullToPointer:
04841     VisitIgnoredValue(E->getSubExpr());
04842     return ZeroInitialization(E);
04843 
04844   case CK_IntegralToPointer: {
04845     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
04846 
04847     APValue Value;
04848     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
04849       break;
04850 
04851     if (Value.isInt()) {
04852       unsigned Size = Info.Ctx.getTypeSize(E->getType());
04853       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
04854       Result.Base = (Expr*)nullptr;
04855       Result.Offset = CharUnits::fromQuantity(N);
04856       Result.CallIndex = 0;
04857       Result.Designator.setInvalid();
04858       return true;
04859     } else {
04860       // Cast is of an lvalue, no need to change value.
04861       Result.setFrom(Info.Ctx, Value);
04862       return true;
04863     }
04864   }
04865   case CK_ArrayToPointerDecay:
04866     if (SubExpr->isGLValue()) {
04867       if (!EvaluateLValue(SubExpr, Result, Info))
04868         return false;
04869     } else {
04870       Result.set(SubExpr, Info.CurrentCall->Index);
04871       if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
04872                            Info, Result, SubExpr))
04873         return false;
04874     }
04875     // The result is a pointer to the first element of the array.
04876     if (const ConstantArrayType *CAT
04877           = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
04878       Result.addArray(Info, E, CAT);
04879     else
04880       Result.Designator.setInvalid();
04881     return true;
04882 
04883   case CK_FunctionToPointerDecay:
04884     return EvaluateLValue(SubExpr, Result, Info);
04885   }
04886 
04887   return ExprEvaluatorBaseTy::VisitCastExpr(E);
04888 }
04889 
04890 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
04891   // C++ [expr.alignof]p3:
04892   //     When alignof is applied to a reference type, the result is the
04893   //     alignment of the referenced type.
04894   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
04895     T = Ref->getPointeeType();
04896 
04897   // __alignof is defined to return the preferred alignment.
04898   return Info.Ctx.toCharUnitsFromBits(
04899     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
04900 }
04901 
04902 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
04903   E = E->IgnoreParens();
04904 
04905   // The kinds of expressions that we have special-case logic here for
04906   // should be kept up to date with the special checks for those
04907   // expressions in Sema.
04908 
04909   // alignof decl is always accepted, even if it doesn't make sense: we default
04910   // to 1 in those cases.
04911   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
04912     return Info.Ctx.getDeclAlign(DRE->getDecl(),
04913                                  /*RefAsPointee*/true);
04914 
04915   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
04916     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
04917                                  /*RefAsPointee*/true);
04918 
04919   return GetAlignOfType(Info, E->getType());
04920 }
04921 
04922 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
04923   if (IsStringLiteralCall(E))
04924     return Success(E);
04925 
04926   switch (E->getBuiltinCallee()) {
04927   case Builtin::BI__builtin_addressof:
04928     return EvaluateLValue(E->getArg(0), Result, Info);
04929   case Builtin::BI__builtin_assume_aligned: {
04930     // We need to be very careful here because: if the pointer does not have the
04931     // asserted alignment, then the behavior is undefined, and undefined
04932     // behavior is non-constant.
04933     if (!EvaluatePointer(E->getArg(0), Result, Info))
04934       return false;
04935 
04936     LValue OffsetResult(Result);
04937     APSInt Alignment;
04938     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
04939       return false;
04940     CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
04941 
04942     if (E->getNumArgs() > 2) {
04943       APSInt Offset;
04944       if (!EvaluateInteger(E->getArg(2), Offset, Info))
04945         return false;
04946 
04947       int64_t AdditionalOffset = -getExtValue(Offset);
04948       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
04949     }
04950 
04951     // If there is a base object, then it must have the correct alignment.
04952     if (OffsetResult.Base) {
04953       CharUnits BaseAlignment;
04954       if (const ValueDecl *VD =
04955           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
04956         BaseAlignment = Info.Ctx.getDeclAlign(VD);
04957       } else {
04958         BaseAlignment =
04959           GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
04960       }
04961 
04962       if (BaseAlignment < Align) {
04963         Result.Designator.setInvalid();
04964   // FIXME: Quantities here cast to integers because the plural modifier
04965   // does not work on APSInts yet.
04966         CCEDiag(E->getArg(0),
04967                 diag::note_constexpr_baa_insufficient_alignment) << 0
04968           << (int) BaseAlignment.getQuantity()
04969           << (unsigned) getExtValue(Alignment);
04970         return false;
04971       }
04972     }
04973 
04974     // The offset must also have the correct alignment.
04975     if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
04976       Result.Designator.setInvalid();
04977       APSInt Offset(64, false);
04978       Offset = OffsetResult.Offset.getQuantity();
04979 
04980       if (OffsetResult.Base)
04981         CCEDiag(E->getArg(0),
04982                 diag::note_constexpr_baa_insufficient_alignment) << 1
04983           << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
04984       else
04985         CCEDiag(E->getArg(0),
04986                 diag::note_constexpr_baa_value_insufficient_alignment)
04987           << Offset << (unsigned) getExtValue(Alignment);
04988 
04989       return false;
04990     }
04991 
04992     return true;
04993   }
04994   default:
04995     return ExprEvaluatorBaseTy::VisitCallExpr(E);
04996   }
04997 }
04998 
04999 //===----------------------------------------------------------------------===//
05000 // Member Pointer Evaluation
05001 //===----------------------------------------------------------------------===//
05002 
05003 namespace {
05004 class MemberPointerExprEvaluator
05005   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
05006   MemberPtr &Result;
05007 
05008   bool Success(const ValueDecl *D) {
05009     Result = MemberPtr(D);
05010     return true;
05011   }
05012 public:
05013 
05014   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
05015     : ExprEvaluatorBaseTy(Info), Result(Result) {}
05016 
05017   bool Success(const APValue &V, const Expr *E) {
05018     Result.setFrom(V);
05019     return true;
05020   }
05021   bool ZeroInitialization(const Expr *E) {
05022     return Success((const ValueDecl*)nullptr);
05023   }
05024 
05025   bool VisitCastExpr(const CastExpr *E);
05026   bool VisitUnaryAddrOf(const UnaryOperator *E);
05027 };
05028 } // end anonymous namespace
05029 
05030 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
05031                                   EvalInfo &Info) {
05032   assert(E->isRValue() && E->getType()->isMemberPointerType());
05033   return MemberPointerExprEvaluator(Info, Result).Visit(E);
05034 }
05035 
05036 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
05037   switch (E->getCastKind()) {
05038   default:
05039     return ExprEvaluatorBaseTy::VisitCastExpr(E);
05040 
05041   case CK_NullToMemberPointer:
05042     VisitIgnoredValue(E->getSubExpr());
05043     return ZeroInitialization(E);
05044 
05045   case CK_BaseToDerivedMemberPointer: {
05046     if (!Visit(E->getSubExpr()))
05047       return false;
05048     if (E->path_empty())
05049       return true;
05050     // Base-to-derived member pointer casts store the path in derived-to-base
05051     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
05052     // the wrong end of the derived->base arc, so stagger the path by one class.
05053     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
05054     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
05055          PathI != PathE; ++PathI) {
05056       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
05057       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
05058       if (!Result.castToDerived(Derived))
05059         return Error(E);
05060     }
05061     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
05062     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
05063       return Error(E);
05064     return true;
05065   }
05066 
05067   case CK_DerivedToBaseMemberPointer:
05068     if (!Visit(E->getSubExpr()))
05069       return false;
05070     for (CastExpr::path_const_iterator PathI = E->path_begin(),
05071          PathE = E->path_end(); PathI != PathE; ++PathI) {
05072       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
05073       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
05074       if (!Result.castToBase(Base))
05075         return Error(E);
05076     }
05077     return true;
05078   }
05079 }
05080 
05081 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
05082   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
05083   // member can be formed.
05084   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
05085 }
05086 
05087 //===----------------------------------------------------------------------===//
05088 // Record Evaluation
05089 //===----------------------------------------------------------------------===//
05090 
05091 namespace {
05092   class RecordExprEvaluator
05093   : public ExprEvaluatorBase<RecordExprEvaluator> {
05094     const LValue &This;
05095     APValue &Result;
05096   public:
05097 
05098     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
05099       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
05100 
05101     bool Success(const APValue &V, const Expr *E) {
05102       Result = V;
05103       return true;
05104     }
05105     bool ZeroInitialization(const Expr *E);
05106 
05107     bool VisitCastExpr(const CastExpr *E);
05108     bool VisitInitListExpr(const InitListExpr *E);
05109     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
05110     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
05111   };
05112 }
05113 
05114 /// Perform zero-initialization on an object of non-union class type.
05115 /// C++11 [dcl.init]p5:
05116 ///  To zero-initialize an object or reference of type T means:
05117 ///    [...]
05118 ///    -- if T is a (possibly cv-qualified) non-union class type,
05119 ///       each non-static data member and each base-class subobject is
05120 ///       zero-initialized
05121 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
05122                                           const RecordDecl *RD,
05123                                           const LValue &This, APValue &Result) {
05124   assert(!RD->isUnion() && "Expected non-union class type");
05125   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
05126   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
05127                    std::distance(RD->field_begin(), RD->field_end()));
05128 
05129   if (RD->isInvalidDecl()) return false;
05130   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
05131 
05132   if (CD) {
05133     unsigned Index = 0;
05134     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
05135            End = CD->bases_end(); I != End; ++I, ++Index) {
05136       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
05137       LValue Subobject = This;
05138       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
05139         return false;
05140       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
05141                                          Result.getStructBase(Index)))
05142         return false;
05143     }
05144   }
05145 
05146   for (const auto *I : RD->fields()) {
05147     // -- if T is a reference type, no initialization is performed.
05148     if (I->getType()->isReferenceType())
05149       continue;
05150 
05151     LValue Subobject = This;
05152     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
05153       return false;
05154 
05155     ImplicitValueInitExpr VIE(I->getType());
05156     if (!EvaluateInPlace(
05157           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
05158       return false;
05159   }
05160 
05161   return true;
05162 }
05163 
05164 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
05165   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
05166   if (RD->isInvalidDecl()) return false;
05167   if (RD->isUnion()) {
05168     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
05169     // object's first non-static named data member is zero-initialized
05170     RecordDecl::field_iterator I = RD->field_begin();
05171     if (I == RD->field_end()) {
05172       Result = APValue((const FieldDecl*)nullptr);
05173       return true;
05174     }
05175 
05176     LValue Subobject = This;
05177     if (!HandleLValueMember(Info, E, Subobject, *I))
05178       return false;
05179     Result = APValue(*I);
05180     ImplicitValueInitExpr VIE(I->getType());
05181     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
05182   }
05183 
05184   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
05185     Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
05186     return false;
05187   }
05188 
05189   return HandleClassZeroInitialization(Info, E, RD, This, Result);
05190 }
05191 
05192 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
05193   switch (E->getCastKind()) {
05194   default:
05195     return ExprEvaluatorBaseTy::VisitCastExpr(E);
05196 
05197   case CK_ConstructorConversion:
05198     return Visit(E->getSubExpr());
05199 
05200   case CK_DerivedToBase:
05201   case CK_UncheckedDerivedToBase: {
05202     APValue DerivedObject;
05203     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
05204       return false;
05205     if (!DerivedObject.isStruct())
05206       return Error(E->getSubExpr());
05207 
05208     // Derived-to-base rvalue conversion: just slice off the derived part.
05209     APValue *Value = &DerivedObject;
05210     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
05211     for (CastExpr::path_const_iterator PathI = E->path_begin(),
05212          PathE = E->path_end(); PathI != PathE; ++PathI) {
05213       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
05214       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
05215       Value = &Value->getStructBase(getBaseIndex(RD, Base));
05216       RD = Base;
05217     }
05218     Result = *Value;
05219     return true;
05220   }
05221   }
05222 }
05223 
05224 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
05225   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
05226   if (RD->isInvalidDecl()) return false;
05227   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
05228 
05229   if (RD->isUnion()) {
05230     const FieldDecl *Field = E->getInitializedFieldInUnion();
05231     Result = APValue(Field);
05232     if (!Field)
05233       return true;
05234 
05235     // If the initializer list for a union does not contain any elements, the
05236     // first element of the union is value-initialized.
05237     // FIXME: The element should be initialized from an initializer list.
05238     //        Is this difference ever observable for initializer lists which
05239     //        we don't build?
05240     ImplicitValueInitExpr VIE(Field->getType());
05241     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
05242 
05243     LValue Subobject = This;
05244     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
05245       return false;
05246 
05247     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
05248     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
05249                                   isa<CXXDefaultInitExpr>(InitExpr));
05250 
05251     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
05252   }
05253 
05254   assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
05255          "initializer list for class with base classes");
05256   Result = APValue(APValue::UninitStruct(), 0,
05257                    std::distance(RD->field_begin(), RD->field_end()));
05258   unsigned ElementNo = 0;
05259   bool Success = true;
05260   for (const auto *Field : RD->fields()) {
05261     // Anonymous bit-fields are not considered members of the class for
05262     // purposes of aggregate initialization.
05263     if (Field->isUnnamedBitfield())
05264       continue;
05265 
05266     LValue Subobject = This;
05267 
05268     bool HaveInit = ElementNo < E->getNumInits();
05269 
05270     // FIXME: Diagnostics here should point to the end of the initializer
05271     // list, not the start.
05272     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
05273                             Subobject, Field, &Layout))
05274       return false;
05275 
05276     // Perform an implicit value-initialization for members beyond the end of
05277     // the initializer list.
05278     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
05279     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
05280 
05281     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
05282     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
05283                                   isa<CXXDefaultInitExpr>(Init));
05284 
05285     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
05286     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
05287         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
05288                                                        FieldVal, Field))) {
05289       if (!Info.keepEvaluatingAfterFailure())
05290         return false;
05291       Success = false;
05292     }
05293   }
05294 
05295   return Success;
05296 }
05297 
05298 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
05299   const CXXConstructorDecl *FD = E->getConstructor();
05300   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
05301 
05302   bool ZeroInit = E->requiresZeroInitialization();
05303   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
05304     // If we've already performed zero-initialization, we're already done.
05305     if (!Result.isUninit())
05306       return true;
05307 
05308     // We can get here in two different ways:
05309     //  1) We're performing value-initialization, and should zero-initialize
05310     //     the object, or
05311     //  2) We're performing default-initialization of an object with a trivial
05312     //     constexpr default constructor, in which case we should start the
05313     //     lifetimes of all the base subobjects (there can be no data member
05314     //     subobjects in this case) per [basic.life]p1.
05315     // Either way, ZeroInitialization is appropriate.
05316     return ZeroInitialization(E);
05317   }
05318 
05319   const FunctionDecl *Definition = nullptr;
05320   FD->getBody(Definition);
05321 
05322   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
05323     return false;
05324 
05325   // Avoid materializing a temporary for an elidable copy/move constructor.
05326   if (E->isElidable() && !ZeroInit)
05327     if (const MaterializeTemporaryExpr *ME
05328           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
05329       return Visit(ME->GetTemporaryExpr());
05330 
05331   if (ZeroInit && !ZeroInitialization(E))
05332     return false;
05333 
05334   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
05335   return HandleConstructorCall(E->getExprLoc(), This, Args,
05336                                cast<CXXConstructorDecl>(Definition), Info,
05337                                Result);
05338 }
05339 
05340 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
05341     const CXXStdInitializerListExpr *E) {
05342   const ConstantArrayType *ArrayType =
05343       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
05344 
05345   LValue Array;
05346   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
05347     return false;
05348 
05349   // Get a pointer to the first element of the array.
05350   Array.addArray(Info, E, ArrayType);
05351 
05352   // FIXME: Perform the checks on the field types in SemaInit.
05353   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
05354   RecordDecl::field_iterator Field = Record->field_begin();
05355   if (Field == Record->field_end())
05356     return Error(E);
05357 
05358   // Start pointer.
05359   if (!Field->getType()->isPointerType() ||
05360       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
05361                             ArrayType->getElementType()))
05362     return Error(E);
05363 
05364   // FIXME: What if the initializer_list type has base classes, etc?
05365   Result = APValue(APValue::UninitStruct(), 0, 2);
05366   Array.moveInto(Result.getStructField(0));
05367 
05368   if (++Field == Record->field_end())
05369     return Error(E);
05370 
05371   if (Field->getType()->isPointerType() &&
05372       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
05373                            ArrayType->getElementType())) {
05374     // End pointer.
05375     if (!HandleLValueArrayAdjustment(Info, E, Array,
05376                                      ArrayType->getElementType(),
05377                                      ArrayType->getSize().getZExtValue()))
05378       return false;
05379     Array.moveInto(Result.getStructField(1));
05380   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
05381     // Length.
05382     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
05383   else
05384     return Error(E);
05385 
05386   if (++Field != Record->field_end())
05387     return Error(E);
05388 
05389   return true;
05390 }
05391 
05392 static bool EvaluateRecord(const Expr *E, const LValue &This,
05393                            APValue &Result, EvalInfo &Info) {
05394   assert(E->isRValue() && E->getType()->isRecordType() &&
05395          "can't evaluate expression as a record rvalue");
05396   return RecordExprEvaluator(Info, This, Result).Visit(E);
05397 }
05398 
05399 //===----------------------------------------------------------------------===//
05400 // Temporary Evaluation
05401 //
05402 // Temporaries are represented in the AST as rvalues, but generally behave like
05403 // lvalues. The full-object of which the temporary is a subobject is implicitly
05404 // materialized so that a reference can bind to it.
05405 //===----------------------------------------------------------------------===//
05406 namespace {
05407 class TemporaryExprEvaluator
05408   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
05409 public:
05410   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
05411     LValueExprEvaluatorBaseTy(Info, Result) {}
05412 
05413   /// Visit an expression which constructs the value of this temporary.
05414   bool VisitConstructExpr(const Expr *E) {
05415     Result.set(E, Info.CurrentCall->Index);
05416     return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
05417                            Info, Result, E);
05418   }
05419 
05420   bool VisitCastExpr(const CastExpr *E) {
05421     switch (E->getCastKind()) {
05422     default:
05423       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
05424 
05425     case CK_ConstructorConversion:
05426       return VisitConstructExpr(E->getSubExpr());
05427     }
05428   }
05429   bool VisitInitListExpr(const InitListExpr *E) {
05430     return VisitConstructExpr(E);
05431   }
05432   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
05433     return VisitConstructExpr(E);
05434   }
05435   bool VisitCallExpr(const CallExpr *E) {
05436     return VisitConstructExpr(E);
05437   }
05438 };
05439 } // end anonymous namespace
05440 
05441 /// Evaluate an expression of record type as a temporary.
05442 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
05443   assert(E->isRValue() && E->getType()->isRecordType());
05444   return TemporaryExprEvaluator(Info, Result).Visit(E);
05445 }
05446 
05447 //===----------------------------------------------------------------------===//
05448 // Vector Evaluation
05449 //===----------------------------------------------------------------------===//
05450 
05451 namespace {
05452   class VectorExprEvaluator
05453   : public ExprEvaluatorBase<VectorExprEvaluator> {
05454     APValue &Result;
05455   public:
05456 
05457     VectorExprEvaluator(EvalInfo &info, APValue &Result)
05458       : ExprEvaluatorBaseTy(info), Result(Result) {}
05459 
05460     bool Success(const ArrayRef<APValue> &V, const Expr *E) {
05461       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
05462       // FIXME: remove this APValue copy.
05463       Result = APValue(V.data(), V.size());
05464       return true;
05465     }
05466     bool Success(const APValue &V, const Expr *E) {
05467       assert(V.isVector());
05468       Result = V;
05469       return true;
05470     }
05471     bool ZeroInitialization(const Expr *E);
05472 
05473     bool VisitUnaryReal(const UnaryOperator *E)
05474       { return Visit(E->getSubExpr()); }
05475     bool VisitCastExpr(const CastExpr* E);
05476     bool VisitInitListExpr(const InitListExpr *E);
05477     bool VisitUnaryImag(const UnaryOperator *E);
05478     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
05479     //                 binary comparisons, binary and/or/xor,
05480     //                 shufflevector, ExtVectorElementExpr
05481   };
05482 } // end anonymous namespace
05483 
05484 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
05485   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
05486   return VectorExprEvaluator(Info, Result).Visit(E);
05487 }
05488 
05489 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
05490   const VectorType *VTy = E->getType()->castAs<VectorType>();
05491   unsigned NElts = VTy->getNumElements();
05492 
05493   const Expr *SE = E->getSubExpr();
05494   QualType SETy = SE->getType();
05495 
05496   switch (E->getCastKind()) {
05497   case CK_VectorSplat: {
05498     APValue Val = APValue();
05499     if (SETy->isIntegerType()) {
05500       APSInt IntResult;
05501       if (!EvaluateInteger(SE, IntResult, Info))
05502          return false;
05503       Val = APValue(IntResult);
05504     } else if (SETy->isRealFloatingType()) {
05505        APFloat F(0.0);
05506        if (!EvaluateFloat(SE, F, Info))
05507          return false;
05508        Val = APValue(F);
05509     } else {
05510       return Error(E);
05511     }
05512 
05513     // Splat and create vector APValue.
05514     SmallVector<APValue, 4> Elts(NElts, Val);
05515     return Success(Elts, E);
05516   }
05517   case CK_BitCast: {
05518     // Evaluate the operand into an APInt we can extract from.
05519     llvm::APInt SValInt;
05520     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
05521       return false;
05522     // Extract the elements
05523     QualType EltTy = VTy->getElementType();
05524     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
05525     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
05526     SmallVector<APValue, 4> Elts;
05527     if (EltTy->isRealFloatingType()) {
05528       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
05529       unsigned FloatEltSize = EltSize;
05530       if (&Sem == &APFloat::x87DoubleExtended)
05531         FloatEltSize = 80;
05532       for (unsigned i = 0; i < NElts; i++) {
05533         llvm::APInt Elt;
05534         if (BigEndian)
05535           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
05536         else
05537           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
05538         Elts.push_back(APValue(APFloat(Sem, Elt)));
05539       }
05540     } else if (EltTy->isIntegerType()) {
05541       for (unsigned i = 0; i < NElts; i++) {
05542         llvm::APInt Elt;
05543         if (BigEndian)
05544           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
05545         else
05546           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
05547         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
05548       }
05549     } else {
05550       return Error(E);
05551     }
05552     return Success(Elts, E);
05553   }
05554   default:
05555     return ExprEvaluatorBaseTy::VisitCastExpr(E);
05556   }
05557 }
05558 
05559 bool
05560 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
05561   const VectorType *VT = E->getType()->castAs<VectorType>();
05562   unsigned NumInits = E->getNumInits();
05563   unsigned NumElements = VT->getNumElements();
05564 
05565   QualType EltTy = VT->getElementType();
05566   SmallVector<APValue, 4> Elements;
05567 
05568   // The number of initializers can be less than the number of
05569   // vector elements. For OpenCL, this can be due to nested vector
05570   // initialization. For GCC compatibility, missing trailing elements 
05571   // should be initialized with zeroes.
05572   unsigned CountInits = 0, CountElts = 0;
05573   while (CountElts < NumElements) {
05574     // Handle nested vector initialization.
05575     if (CountInits < NumInits 
05576         && E->getInit(CountInits)->getType()->isVectorType()) {
05577       APValue v;
05578       if (!EvaluateVector(E->getInit(CountInits), v, Info))
05579         return Error(E);
05580       unsigned vlen = v.getVectorLength();
05581       for (unsigned j = 0; j < vlen; j++) 
05582         Elements.push_back(v.getVectorElt(j));
05583       CountElts += vlen;
05584     } else if (EltTy->isIntegerType()) {
05585       llvm::APSInt sInt(32);
05586       if (CountInits < NumInits) {
05587         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
05588           return false;
05589       } else // trailing integer zero.
05590         sInt = Info.Ctx.MakeIntValue(0, EltTy);
05591       Elements.push_back(APValue(sInt));
05592       CountElts++;
05593     } else {
05594       llvm::APFloat f(0.0);
05595       if (CountInits < NumInits) {
05596         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
05597           return false;
05598       } else // trailing float zero.
05599         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
05600       Elements.push_back(APValue(f));
05601       CountElts++;
05602     }
05603     CountInits++;
05604   }
05605   return Success(Elements, E);
05606 }
05607 
05608 bool
05609 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
05610   const VectorType *VT = E->getType()->getAs<VectorType>();
05611   QualType EltTy = VT->getElementType();
05612   APValue ZeroElement;
05613   if (EltTy->isIntegerType())
05614     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
05615   else
05616     ZeroElement =
05617         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
05618 
05619   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
05620   return Success(Elements, E);
05621 }
05622 
05623 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
05624   VisitIgnoredValue(E->getSubExpr());
05625   return ZeroInitialization(E);
05626 }
05627 
05628 //===----------------------------------------------------------------------===//
05629 // Array Evaluation
05630 //===----------------------------------------------------------------------===//
05631 
05632 namespace {
05633   class ArrayExprEvaluator
05634   : public ExprEvaluatorBase<ArrayExprEvaluator> {
05635     const LValue &This;
05636     APValue &Result;
05637   public:
05638 
05639     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
05640       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
05641 
05642     bool Success(const APValue &V, const Expr *E) {
05643       assert((V.isArray() || V.isLValue()) &&
05644              "expected array or string literal");
05645       Result = V;
05646       return true;
05647     }
05648 
05649     bool ZeroInitialization(const Expr *E) {
05650       const ConstantArrayType *CAT =
05651           Info.Ctx.getAsConstantArrayType(E->getType());
05652       if (!CAT)
05653         return Error(E);
05654 
05655       Result = APValue(APValue::UninitArray(), 0,
05656                        CAT->getSize().getZExtValue());
05657       if (!Result.hasArrayFiller()) return true;
05658 
05659       // Zero-initialize all elements.
05660       LValue Subobject = This;
05661       Subobject.addArray(Info, E, CAT);
05662       ImplicitValueInitExpr VIE(CAT->getElementType());
05663       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
05664     }
05665 
05666     bool VisitInitListExpr(const InitListExpr *E);
05667     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
05668     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
05669                                const LValue &Subobject,
05670                                APValue *Value, QualType Type);
05671   };
05672 } // end anonymous namespace
05673 
05674 static bool EvaluateArray(const Expr *E, const LValue &This,
05675                           APValue &Result, EvalInfo &Info) {
05676   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
05677   return ArrayExprEvaluator(Info, This, Result).Visit(E);
05678 }
05679 
05680 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
05681   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
05682   if (!CAT)
05683     return Error(E);
05684 
05685   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
05686   // an appropriately-typed string literal enclosed in braces.
05687   if (E->isStringLiteralInit()) {
05688     LValue LV;
05689     if (!EvaluateLValue(E->getInit(0), LV, Info))
05690       return false;
05691     APValue Val;
05692     LV.moveInto(Val);
05693     return Success(Val, E);
05694   }
05695 
05696   bool Success = true;
05697 
05698   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
05699          "zero-initialized array shouldn't have any initialized elts");
05700   APValue Filler;
05701   if (Result.isArray() && Result.hasArrayFiller())
05702     Filler = Result.getArrayFiller();
05703 
05704   unsigned NumEltsToInit = E->getNumInits();
05705   unsigned NumElts = CAT->getSize().getZExtValue();
05706   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
05707 
05708   // If the initializer might depend on the array index, run it for each
05709   // array element. For now, just whitelist non-class value-initialization.
05710   if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
05711     NumEltsToInit = NumElts;
05712 
05713   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
05714 
05715   // If the array was previously zero-initialized, preserve the
05716   // zero-initialized values.
05717   if (!Filler.isUninit()) {
05718     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
05719       Result.getArrayInitializedElt(I) = Filler;
05720     if (Result.hasArrayFiller())
05721       Result.getArrayFiller() = Filler;
05722   }
05723 
05724   LValue Subobject = This;
05725   Subobject.addArray(Info, E, CAT);
05726   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
05727     const Expr *Init =
05728         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
05729     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
05730                          Info, Subobject, Init) ||
05731         !HandleLValueArrayAdjustment(Info, Init, Subobject,
05732                                      CAT->getElementType(), 1)) {
05733       if (!Info.keepEvaluatingAfterFailure())
05734         return false;
05735       Success = false;
05736     }
05737   }
05738 
05739   if (!Result.hasArrayFiller())
05740     return Success;
05741 
05742   // If we get here, we have a trivial filler, which we can just evaluate
05743   // once and splat over the rest of the array elements.
05744   assert(FillerExpr && "no array filler for incomplete init list");
05745   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
05746                          FillerExpr) && Success;
05747 }
05748 
05749 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
05750   return VisitCXXConstructExpr(E, This, &Result, E->getType());
05751 }
05752 
05753 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
05754                                                const LValue &Subobject,
05755                                                APValue *Value,
05756                                                QualType Type) {
05757   bool HadZeroInit = !Value->isUninit();
05758 
05759   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
05760     unsigned N = CAT->getSize().getZExtValue();
05761 
05762     // Preserve the array filler if we had prior zero-initialization.
05763     APValue Filler =
05764       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
05765                                              : APValue();
05766 
05767     *Value = APValue(APValue::UninitArray(), N, N);
05768 
05769     if (HadZeroInit)
05770       for (unsigned I = 0; I != N; ++I)
05771         Value->getArrayInitializedElt(I) = Filler;
05772 
05773     // Initialize the elements.
05774     LValue ArrayElt = Subobject;
05775     ArrayElt.addArray(Info, E, CAT);
05776     for (unsigned I = 0; I != N; ++I)
05777       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
05778                                  CAT->getElementType()) ||
05779           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
05780                                        CAT->getElementType(), 1))
05781         return false;
05782 
05783     return true;
05784   }
05785 
05786   if (!Type->isRecordType())
05787     return Error(E);
05788 
05789   const CXXConstructorDecl *FD = E->getConstructor();
05790 
05791   bool ZeroInit = E->requiresZeroInitialization();
05792   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
05793     if (HadZeroInit)
05794       return true;
05795 
05796     // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
05797     ImplicitValueInitExpr VIE(Type);
05798     return EvaluateInPlace(*Value, Info, Subobject, &VIE);
05799   }
05800 
05801   const FunctionDecl *Definition = nullptr;
05802   FD->getBody(Definition);
05803 
05804   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
05805     return false;
05806 
05807   if (ZeroInit && !HadZeroInit) {
05808     ImplicitValueInitExpr VIE(Type);
05809     if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
05810       return false;
05811   }
05812 
05813   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
05814   return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
05815                                cast<CXXConstructorDecl>(Definition),
05816                                Info, *Value);
05817 }
05818 
05819 //===----------------------------------------------------------------------===//
05820 // Integer Evaluation
05821 //
05822 // As a GNU extension, we support casting pointers to sufficiently-wide integer
05823 // types and back in constant folding. Integer values are thus represented
05824 // either as an integer-valued APValue, or as an lvalue-valued APValue.
05825 //===----------------------------------------------------------------------===//
05826 
05827 namespace {
05828 class IntExprEvaluator
05829   : public ExprEvaluatorBase<IntExprEvaluator> {
05830   APValue &Result;
05831 public:
05832   IntExprEvaluator(EvalInfo &info, APValue &result)
05833     : ExprEvaluatorBaseTy(info), Result(result) {}
05834 
05835   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
05836     assert(E->getType()->isIntegralOrEnumerationType() &&
05837            "Invalid evaluation result.");
05838     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
05839            "Invalid evaluation result.");
05840     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
05841            "Invalid evaluation result.");
05842     Result = APValue(SI);
05843     return true;
05844   }
05845   bool Success(const llvm::APSInt &SI, const Expr *E) {
05846     return Success(SI, E, Result);
05847   }
05848 
05849   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
05850     assert(E->getType()->isIntegralOrEnumerationType() && 
05851            "Invalid evaluation result.");
05852     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
05853            "Invalid evaluation result.");
05854     Result = APValue(APSInt(I));
05855     Result.getInt().setIsUnsigned(
05856                             E->getType()->isUnsignedIntegerOrEnumerationType());
05857     return true;
05858   }
05859   bool Success(const llvm::APInt &I, const Expr *E) {
05860     return Success(I, E, Result);
05861   }
05862 
05863   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
05864     assert(E->getType()->isIntegralOrEnumerationType() && 
05865            "Invalid evaluation result.");
05866     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
05867     return true;
05868   }
05869   bool Success(uint64_t Value, const Expr *E) {
05870     return Success(Value, E, Result);
05871   }
05872 
05873   bool Success(CharUnits Size, const Expr *E) {
05874     return Success(Size.getQuantity(), E);
05875   }
05876 
05877   bool Success(const APValue &V, const Expr *E) {
05878     if (V.isLValue() || V.isAddrLabelDiff()) {
05879       Result = V;
05880       return true;
05881     }
05882     return Success(V.getInt(), E);
05883   }
05884 
05885   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
05886 
05887   //===--------------------------------------------------------------------===//
05888   //                            Visitor Methods
05889   //===--------------------------------------------------------------------===//
05890 
05891   bool VisitIntegerLiteral(const IntegerLiteral *E) {
05892     return Success(E->getValue(), E);
05893   }
05894   bool VisitCharacterLiteral(const CharacterLiteral *E) {
05895     return Success(E->getValue(), E);
05896   }
05897 
05898   bool CheckReferencedDecl(const Expr *E, const Decl *D);
05899   bool VisitDeclRefExpr(const DeclRefExpr *E) {
05900     if (CheckReferencedDecl(E, E->getDecl()))
05901       return true;
05902 
05903     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
05904   }
05905   bool VisitMemberExpr(const MemberExpr *E) {
05906     if (CheckReferencedDecl(E, E->getMemberDecl())) {
05907       VisitIgnoredValue(E->getBase());
05908       return true;
05909     }
05910 
05911     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
05912   }
05913 
05914   bool VisitCallExpr(const CallExpr *E);
05915   bool VisitBinaryOperator(const BinaryOperator *E);
05916   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
05917   bool VisitUnaryOperator(const UnaryOperator *E);
05918 
05919   bool VisitCastExpr(const CastExpr* E);
05920   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
05921 
05922   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
05923     return Success(E->getValue(), E);
05924   }
05925 
05926   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
05927     return Success(E->getValue(), E);
05928   }
05929     
05930   // Note, GNU defines __null as an integer, not a pointer.
05931   bool VisitGNUNullExpr(const GNUNullExpr *E) {
05932     return ZeroInitialization(E);
05933   }
05934 
05935   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
05936     return Success(E->getValue(), E);
05937   }
05938 
05939   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
05940     return Success(E->getValue(), E);
05941   }
05942 
05943   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
05944     return Success(E->getValue(), E);
05945   }
05946 
05947   bool VisitUnaryReal(const UnaryOperator *E);
05948   bool VisitUnaryImag(const UnaryOperator *E);
05949 
05950   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
05951   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
05952 
05953 private:
05954   static QualType GetObjectType(APValue::LValueBase B);
05955   bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
05956   // FIXME: Missing: array subscript of vector, member of vector
05957 };
05958 } // end anonymous namespace
05959 
05960 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
05961 /// produce either the integer value or a pointer.
05962 ///
05963 /// GCC has a heinous extension which folds casts between pointer types and
05964 /// pointer-sized integral types. We support this by allowing the evaluation of
05965 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
05966 /// Some simple arithmetic on such values is supported (they are treated much
05967 /// like char*).
05968 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
05969                                     EvalInfo &Info) {
05970   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
05971   return IntExprEvaluator(Info, Result).Visit(E);
05972 }
05973 
05974 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
05975   APValue Val;
05976   if (!EvaluateIntegerOrLValue(E, Val, Info))
05977     return false;
05978   if (!Val.isInt()) {
05979     // FIXME: It would be better to produce the diagnostic for casting
05980     //        a pointer to an integer.
05981     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
05982     return false;
05983   }
05984   Result = Val.getInt();
05985   return true;
05986 }
05987 
05988 /// Check whether the given declaration can be directly converted to an integral
05989 /// rvalue. If not, no diagnostic is produced; there are other things we can
05990 /// try.
05991 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
05992   // Enums are integer constant exprs.
05993   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
05994     // Check for signedness/width mismatches between E type and ECD value.
05995     bool SameSign = (ECD->getInitVal().isSigned()
05996                      == E->getType()->isSignedIntegerOrEnumerationType());
05997     bool SameWidth = (ECD->getInitVal().getBitWidth()
05998                       == Info.Ctx.getIntWidth(E->getType()));
05999     if (SameSign && SameWidth)
06000       return Success(ECD->getInitVal(), E);
06001     else {
06002       // Get rid of mismatch (otherwise Success assertions will fail)
06003       // by computing a new value matching the type of E.
06004       llvm::APSInt Val = ECD->getInitVal();
06005       if (!SameSign)
06006         Val.setIsSigned(!ECD->getInitVal().isSigned());
06007       if (!SameWidth)
06008         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
06009       return Success(Val, E);
06010     }
06011   }
06012   return false;
06013 }
06014 
06015 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
06016 /// as GCC.
06017 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
06018   // The following enum mimics the values returned by GCC.
06019   // FIXME: Does GCC differ between lvalue and rvalue references here?
06020   enum gcc_type_class {
06021     no_type_class = -1,
06022     void_type_class, integer_type_class, char_type_class,
06023     enumeral_type_class, boolean_type_class,
06024     pointer_type_class, reference_type_class, offset_type_class,
06025     real_type_class, complex_type_class,
06026     function_type_class, method_type_class,
06027     record_type_class, union_type_class,
06028     array_type_class, string_type_class,
06029     lang_type_class
06030   };
06031 
06032   // If no argument was supplied, default to "no_type_class". This isn't
06033   // ideal, however it is what gcc does.
06034   if (E->getNumArgs() == 0)
06035     return no_type_class;
06036 
06037   QualType ArgTy = E->getArg(0)->getType();
06038   if (ArgTy->isVoidType())
06039     return void_type_class;
06040   else if (ArgTy->isEnumeralType())
06041     return enumeral_type_class;
06042   else if (ArgTy->isBooleanType())
06043     return boolean_type_class;
06044   else if (ArgTy->isCharType())
06045     return string_type_class; // gcc doesn't appear to use char_type_class
06046   else if (ArgTy->isIntegerType())
06047     return integer_type_class;
06048   else if (ArgTy->isPointerType())
06049     return pointer_type_class;
06050   else if (ArgTy->isReferenceType())
06051     return reference_type_class;
06052   else if (ArgTy->isRealType())
06053     return real_type_class;
06054   else if (ArgTy->isComplexType())
06055     return complex_type_class;
06056   else if (ArgTy->isFunctionType())
06057     return function_type_class;
06058   else if (ArgTy->isStructureOrClassType())
06059     return record_type_class;
06060   else if (ArgTy->isUnionType())
06061     return union_type_class;
06062   else if (ArgTy->isArrayType())
06063     return array_type_class;
06064   else if (ArgTy->isUnionType())
06065     return union_type_class;
06066   else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
06067     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
06068 }
06069 
06070 /// EvaluateBuiltinConstantPForLValue - Determine the result of
06071 /// __builtin_constant_p when applied to the given lvalue.
06072 ///
06073 /// An lvalue is only "constant" if it is a pointer or reference to the first
06074 /// character of a string literal.
06075 template<typename LValue>
06076 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
06077   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
06078   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
06079 }
06080 
06081 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
06082 /// GCC as we can manage.
06083 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
06084   QualType ArgType = Arg->getType();
06085 
06086   // __builtin_constant_p always has one operand. The rules which gcc follows
06087   // are not precisely documented, but are as follows:
06088   //
06089   //  - If the operand is of integral, floating, complex or enumeration type,
06090   //    and can be folded to a known value of that type, it returns 1.
06091   //  - If the operand and can be folded to a pointer to the first character
06092   //    of a string literal (or such a pointer cast to an integral type), it
06093   //    returns 1.
06094   //
06095   // Otherwise, it returns 0.
06096   //
06097   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
06098   // its support for this does not currently work.
06099   if (ArgType->isIntegralOrEnumerationType()) {
06100     Expr::EvalResult Result;
06101     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
06102       return false;
06103 
06104     APValue &V = Result.Val;
06105     if (V.getKind() == APValue::Int)
06106       return true;
06107 
06108     return EvaluateBuiltinConstantPForLValue(V);
06109   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
06110     return Arg->isEvaluatable(Ctx);
06111   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
06112     LValue LV;
06113     Expr::EvalStatus Status;
06114     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
06115     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
06116                           : EvaluatePointer(Arg, LV, Info)) &&
06117         !Status.HasSideEffects)
06118       return EvaluateBuiltinConstantPForLValue(LV);
06119   }
06120 
06121   // Anything else isn't considered to be sufficiently constant.
06122   return false;
06123 }
06124 
06125 /// Retrieves the "underlying object type" of the given expression,
06126 /// as used by __builtin_object_size.
06127 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
06128   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
06129     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
06130       return VD->getType();
06131   } else if (const Expr *E = B.get<const Expr*>()) {
06132     if (isa<CompoundLiteralExpr>(E))
06133       return E->getType();
06134   }
06135 
06136   return QualType();
06137 }
06138 
06139 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
06140   LValue Base;
06141 
06142   {
06143     // The operand of __builtin_object_size is never evaluated for side-effects.
06144     // If there are any, but we can determine the pointed-to object anyway, then
06145     // ignore the side-effects.
06146     SpeculativeEvaluationRAII SpeculativeEval(Info);
06147     if (!EvaluatePointer(E->getArg(0), Base, Info))
06148       return false;
06149   }
06150 
06151   if (!Base.getLValueBase()) {
06152     // It is not possible to determine which objects ptr points to at compile time,
06153     // __builtin_object_size should return (size_t) -1 for type 0 or 1
06154     // and (size_t) 0 for type 2 or 3.
06155     llvm::APSInt TypeIntVaue;
06156     const Expr *ExprType = E->getArg(1);
06157     if (!ExprType->EvaluateAsInt(TypeIntVaue, Info.Ctx))
06158       return false;
06159     if (TypeIntVaue == 0 || TypeIntVaue == 1)
06160       return Success(-1, E);
06161     if (TypeIntVaue == 2 || TypeIntVaue == 3)
06162       return Success(0, E);
06163     return Error(E);
06164   }
06165 
06166   QualType T = GetObjectType(Base.getLValueBase());
06167   if (T.isNull() ||
06168       T->isIncompleteType() ||
06169       T->isFunctionType() ||
06170       T->isVariablyModifiedType() ||
06171       T->isDependentType())
06172     return Error(E);
06173 
06174   CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
06175   CharUnits Offset = Base.getLValueOffset();
06176 
06177   if (!Offset.isNegative() && Offset <= Size)
06178     Size -= Offset;
06179   else
06180     Size = CharUnits::Zero();
06181   return Success(Size, E);
06182 }
06183 
06184 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
06185   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
06186   default:
06187     return ExprEvaluatorBaseTy::VisitCallExpr(E);
06188 
06189   case Builtin::BI__builtin_object_size: {
06190     if (TryEvaluateBuiltinObjectSize(E))
06191       return true;
06192 
06193     // If evaluating the argument has side-effects, we can't determine the size
06194     // of the object, and so we lower it to unknown now. CodeGen relies on us to
06195     // handle all cases where the expression has side-effects.
06196     if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
06197       if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
06198         return Success(-1ULL, E);
06199       return Success(0, E);
06200     }
06201 
06202     // Expression had no side effects, but we couldn't statically determine the
06203     // size of the referenced object.
06204     switch (Info.EvalMode) {
06205     case EvalInfo::EM_ConstantExpression:
06206     case EvalInfo::EM_PotentialConstantExpression:
06207     case EvalInfo::EM_ConstantFold:
06208     case EvalInfo::EM_EvaluateForOverflow:
06209     case EvalInfo::EM_IgnoreSideEffects:
06210       return Error(E);
06211     case EvalInfo::EM_ConstantExpressionUnevaluated:
06212     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
06213       return Success(-1ULL, E);
06214     }
06215   }
06216 
06217   case Builtin::BI__builtin_bswap16:
06218   case Builtin::BI__builtin_bswap32:
06219   case Builtin::BI__builtin_bswap64: {
06220     APSInt Val;
06221     if (!EvaluateInteger(E->getArg(0), Val, Info))
06222       return false;
06223 
06224     return Success(Val.byteSwap(), E);
06225   }
06226 
06227   case Builtin::BI__builtin_classify_type:
06228     return Success(EvaluateBuiltinClassifyType(E), E);
06229 
06230   // FIXME: BI__builtin_clrsb
06231   // FIXME: BI__builtin_clrsbl
06232   // FIXME: BI__builtin_clrsbll
06233 
06234   case Builtin::BI__builtin_clz:
06235   case Builtin::BI__builtin_clzl:
06236   case Builtin::BI__builtin_clzll:
06237   case Builtin::BI__builtin_clzs: {
06238     APSInt Val;
06239     if (!EvaluateInteger(E->getArg(0), Val, Info))
06240       return false;
06241     if (!Val)
06242       return Error(E);
06243 
06244     return Success(Val.countLeadingZeros(), E);
06245   }
06246 
06247   case Builtin::BI__builtin_constant_p:
06248     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
06249 
06250   case Builtin::BI__builtin_ctz:
06251   case Builtin::BI__builtin_ctzl:
06252   case Builtin::BI__builtin_ctzll:
06253   case Builtin::BI__builtin_ctzs: {
06254     APSInt Val;
06255     if (!EvaluateInteger(E->getArg(0), Val, Info))
06256       return false;
06257     if (!Val)
06258       return Error(E);
06259 
06260     return Success(Val.countTrailingZeros(), E);
06261   }
06262 
06263   case Builtin::BI__builtin_eh_return_data_regno: {
06264     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
06265     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
06266     return Success(Operand, E);
06267   }
06268 
06269   case Builtin::BI__builtin_expect:
06270     return Visit(E->getArg(0));
06271 
06272   case Builtin::BI__builtin_ffs:
06273   case Builtin::BI__builtin_ffsl:
06274   case Builtin::BI__builtin_ffsll: {
06275     APSInt Val;
06276     if (!EvaluateInteger(E->getArg(0), Val, Info))
06277       return false;
06278 
06279     unsigned N = Val.countTrailingZeros();
06280     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
06281   }
06282 
06283   case Builtin::BI__builtin_fpclassify: {
06284     APFloat Val(0.0);
06285     if (!EvaluateFloat(E->getArg(5), Val, Info))
06286       return false;
06287     unsigned Arg;
06288     switch (Val.getCategory()) {
06289     case APFloat::fcNaN: Arg = 0; break;
06290     case APFloat::fcInfinity: Arg = 1; break;
06291     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
06292     case APFloat::fcZero: Arg = 4; break;
06293     }
06294     return Visit(E->getArg(Arg));
06295   }
06296 
06297   case Builtin::BI__builtin_isinf_sign: {
06298     APFloat Val(0.0);
06299     return EvaluateFloat(E->getArg(0), Val, Info) &&
06300            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
06301   }
06302 
06303   case Builtin::BI__builtin_isinf: {
06304     APFloat Val(0.0);
06305     return EvaluateFloat(E->getArg(0), Val, Info) &&
06306            Success(Val.isInfinity() ? 1 : 0, E);
06307   }
06308 
06309   case Builtin::BI__builtin_isfinite: {
06310     APFloat Val(0.0);
06311     return EvaluateFloat(E->getArg(0), Val, Info) &&
06312            Success(Val.isFinite() ? 1 : 0, E);
06313   }
06314 
06315   case Builtin::BI__builtin_isnan: {
06316     APFloat Val(0.0);
06317     return EvaluateFloat(E->getArg(0), Val, Info) &&
06318            Success(Val.isNaN() ? 1 : 0, E);
06319   }
06320 
06321   case Builtin::BI__builtin_isnormal: {
06322     APFloat Val(0.0);
06323     return EvaluateFloat(E->getArg(0), Val, Info) &&
06324            Success(Val.isNormal() ? 1 : 0, E);
06325   }
06326 
06327   case Builtin::BI__builtin_parity:
06328   case Builtin::BI__builtin_parityl:
06329   case Builtin::BI__builtin_parityll: {
06330     APSInt Val;
06331     if (!EvaluateInteger(E->getArg(0), Val, Info))
06332       return false;
06333 
06334     return Success(Val.countPopulation() % 2, E);
06335   }
06336 
06337   case Builtin::BI__builtin_popcount:
06338   case Builtin::BI__builtin_popcountl:
06339   case Builtin::BI__builtin_popcountll: {
06340     APSInt Val;
06341     if (!EvaluateInteger(E->getArg(0), Val, Info))
06342       return false;
06343 
06344     return Success(Val.countPopulation(), E);
06345   }
06346 
06347   case Builtin::BIstrlen:
06348     // A call to strlen is not a constant expression.
06349     if (Info.getLangOpts().CPlusPlus11)
06350       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
06351         << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
06352     else
06353       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
06354     // Fall through.
06355   case Builtin::BI__builtin_strlen: {
06356     // As an extension, we support __builtin_strlen() as a constant expression,
06357     // and support folding strlen() to a constant.
06358     LValue String;
06359     if (!EvaluatePointer(E->getArg(0), String, Info))
06360       return false;
06361 
06362     // Fast path: if it's a string literal, search the string value.
06363     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
06364             String.getLValueBase().dyn_cast<const Expr *>())) {
06365       // The string literal may have embedded null characters. Find the first
06366       // one and truncate there.
06367       StringRef Str = S->getBytes();
06368       int64_t Off = String.Offset.getQuantity();
06369       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
06370           S->getCharByteWidth() == 1) {
06371         Str = Str.substr(Off);
06372 
06373         StringRef::size_type Pos = Str.find(0);
06374         if (Pos != StringRef::npos)
06375           Str = Str.substr(0, Pos);
06376 
06377         return Success(Str.size(), E);
06378       }
06379 
06380       // Fall through to slow path to issue appropriate diagnostic.
06381     }
06382 
06383     // Slow path: scan the bytes of the string looking for the terminating 0.
06384     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
06385     for (uint64_t Strlen = 0; /**/; ++Strlen) {
06386       APValue Char;
06387       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
06388           !Char.isInt())
06389         return false;
06390       if (!Char.getInt())
06391         return Success(Strlen, E);
06392       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
06393         return false;
06394     }
06395   }
06396 
06397   case Builtin::BI__atomic_always_lock_free:
06398   case Builtin::BI__atomic_is_lock_free:
06399   case Builtin::BI__c11_atomic_is_lock_free: {
06400     APSInt SizeVal;
06401     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
06402       return false;
06403 
06404     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
06405     // of two less than the maximum inline atomic width, we know it is
06406     // lock-free.  If the size isn't a power of two, or greater than the
06407     // maximum alignment where we promote atomics, we know it is not lock-free
06408     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
06409     // the answer can only be determined at runtime; for example, 16-byte
06410     // atomics have lock-free implementations on some, but not all,
06411     // x86-64 processors.
06412 
06413     // Check power-of-two.
06414     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
06415     if (Size.isPowerOfTwo()) {
06416       // Check against inlining width.
06417       unsigned InlineWidthBits =
06418           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
06419       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
06420         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
06421             Size == CharUnits::One() ||
06422             E->getArg(1)->isNullPointerConstant(Info.Ctx,
06423                                                 Expr::NPC_NeverValueDependent))
06424           // OK, we will inline appropriately-aligned operations of this size,
06425           // and _Atomic(T) is appropriately-aligned.
06426           return Success(1, E);
06427 
06428         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
06429           castAs<PointerType>()->getPointeeType();
06430         if (!PointeeType->isIncompleteType() &&
06431             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
06432           // OK, we will inline operations on this object.
06433           return Success(1, E);
06434         }
06435       }
06436     }
06437 
06438     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
06439         Success(0, E) : Error(E);
06440   }
06441   }
06442 }
06443 
06444 static bool HasSameBase(const LValue &A, const LValue &B) {
06445   if (!A.getLValueBase())
06446     return !B.getLValueBase();
06447   if (!B.getLValueBase())
06448     return false;
06449 
06450   if (A.getLValueBase().getOpaqueValue() !=
06451       B.getLValueBase().getOpaqueValue()) {
06452     const Decl *ADecl = GetLValueBaseDecl(A);
06453     if (!ADecl)
06454       return false;
06455     const Decl *BDecl = GetLValueBaseDecl(B);
06456     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
06457       return false;
06458   }
06459 
06460   return IsGlobalLValue(A.getLValueBase()) ||
06461          A.getLValueCallIndex() == B.getLValueCallIndex();
06462 }
06463 
06464 /// \brief Determine whether this is a pointer past the end of the complete
06465 /// object referred to by the lvalue.
06466 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
06467                                             const LValue &LV) {
06468   // A null pointer can be viewed as being "past the end" but we don't
06469   // choose to look at it that way here.
06470   if (!LV.getLValueBase())
06471     return false;
06472 
06473   // If the designator is valid and refers to a subobject, we're not pointing
06474   // past the end.
06475   if (!LV.getLValueDesignator().Invalid &&
06476       !LV.getLValueDesignator().isOnePastTheEnd())
06477     return false;
06478 
06479   // We're a past-the-end pointer if we point to the byte after the object,
06480   // no matter what our type or path is.
06481   auto Size = Ctx.getTypeSizeInChars(getType(LV.getLValueBase()));
06482   return LV.getLValueOffset() == Size;
06483 }
06484 
06485 namespace {
06486 
06487 /// \brief Data recursive integer evaluator of certain binary operators.
06488 ///
06489 /// We use a data recursive algorithm for binary operators so that we are able
06490 /// to handle extreme cases of chained binary operators without causing stack
06491 /// overflow.
06492 class DataRecursiveIntBinOpEvaluator {
06493   struct EvalResult {
06494     APValue Val;
06495     bool Failed;
06496 
06497     EvalResult() : Failed(false) { }
06498 
06499     void swap(EvalResult &RHS) {
06500       Val.swap(RHS.Val);
06501       Failed = RHS.Failed;
06502       RHS.Failed = false;
06503     }
06504   };
06505 
06506   struct Job {
06507     const Expr *E;
06508     EvalResult LHSResult; // meaningful only for binary operator expression.
06509     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
06510 
06511     Job() : StoredInfo(nullptr) {}
06512     void startSpeculativeEval(EvalInfo &Info) {
06513       OldEvalStatus = Info.EvalStatus;
06514       Info.EvalStatus.Diag = nullptr;
06515       StoredInfo = &Info;
06516     }
06517     ~Job() {
06518       if (StoredInfo) {
06519         StoredInfo->EvalStatus = OldEvalStatus;
06520       }
06521     }
06522   private:
06523     EvalInfo *StoredInfo; // non-null if status changed.
06524     Expr::EvalStatus OldEvalStatus;
06525   };
06526 
06527   SmallVector<Job, 16> Queue;
06528 
06529   IntExprEvaluator &IntEval;
06530   EvalInfo &Info;
06531   APValue &FinalResult;
06532 
06533 public:
06534   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
06535     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
06536 
06537   /// \brief True if \param E is a binary operator that we are going to handle
06538   /// data recursively.
06539   /// We handle binary operators that are comma, logical, or that have operands
06540   /// with integral or enumeration type.
06541   static bool shouldEnqueue(const BinaryOperator *E) {
06542     return E->getOpcode() == BO_Comma ||
06543            E->isLogicalOp() ||
06544            (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
06545             E->getRHS()->getType()->isIntegralOrEnumerationType());
06546   }
06547 
06548   bool Traverse(const BinaryOperator *E) {
06549     enqueue(E);
06550     EvalResult PrevResult;
06551     while (!Queue.empty())
06552       process(PrevResult);
06553 
06554     if (PrevResult.Failed) return false;
06555 
06556     FinalResult.swap(PrevResult.Val);
06557     return true;
06558   }
06559 
06560 private:
06561   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
06562     return IntEval.Success(Value, E, Result);
06563   }
06564   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
06565     return IntEval.Success(Value, E, Result);
06566   }
06567   bool Error(const Expr *E) {
06568     return IntEval.Error(E);
06569   }
06570   bool Error(const Expr *E, diag::kind D) {
06571     return IntEval.Error(E, D);
06572   }
06573 
06574   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
06575     return Info.CCEDiag(E, D);
06576   }
06577 
06578   // \brief Returns true if visiting the RHS is necessary, false otherwise.
06579   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
06580                          bool &SuppressRHSDiags);
06581 
06582   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
06583                   const BinaryOperator *E, APValue &Result);
06584 
06585   void EvaluateExpr(const Expr *E, EvalResult &Result) {
06586     Result.Failed = !Evaluate(Result.Val, Info, E);
06587     if (Result.Failed)
06588       Result.Val = APValue();
06589   }
06590 
06591   void process(EvalResult &Result);
06592 
06593   void enqueue(const Expr *E) {
06594     E = E->IgnoreParens();
06595     Queue.resize(Queue.size()+1);
06596     Queue.back().E = E;
06597     Queue.back().Kind = Job::AnyExprKind;
06598   }
06599 };
06600 
06601 }
06602 
06603 bool DataRecursiveIntBinOpEvaluator::
06604        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
06605                          bool &SuppressRHSDiags) {
06606   if (E->getOpcode() == BO_Comma) {
06607     // Ignore LHS but note if we could not evaluate it.
06608     if (LHSResult.Failed)
06609       return Info.noteSideEffect();
06610     return true;
06611   }
06612 
06613   if (E->isLogicalOp()) {
06614     bool LHSAsBool;
06615     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
06616       // We were able to evaluate the LHS, see if we can get away with not
06617       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
06618       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
06619         Success(LHSAsBool, E, LHSResult.Val);
06620         return false; // Ignore RHS
06621       }
06622     } else {
06623       LHSResult.Failed = true;
06624 
06625       // Since we weren't able to evaluate the left hand side, it
06626       // must have had side effects.
06627       if (!Info.noteSideEffect())
06628         return false;
06629 
06630       // We can't evaluate the LHS; however, sometimes the result
06631       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
06632       // Don't ignore RHS and suppress diagnostics from this arm.
06633       SuppressRHSDiags = true;
06634     }
06635 
06636     return true;
06637   }
06638 
06639   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
06640          E->getRHS()->getType()->isIntegralOrEnumerationType());
06641 
06642   if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
06643     return false; // Ignore RHS;
06644 
06645   return true;
06646 }
06647 
06648 bool DataRecursiveIntBinOpEvaluator::
06649        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
06650                   const BinaryOperator *E, APValue &Result) {
06651   if (E->getOpcode() == BO_Comma) {
06652     if (RHSResult.Failed)
06653       return false;
06654     Result = RHSResult.Val;
06655     return true;
06656   }
06657   
06658   if (E->isLogicalOp()) {
06659     bool lhsResult, rhsResult;
06660     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
06661     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
06662     
06663     if (LHSIsOK) {
06664       if (RHSIsOK) {
06665         if (E->getOpcode() == BO_LOr)
06666           return Success(lhsResult || rhsResult, E, Result);
06667         else
06668           return Success(lhsResult && rhsResult, E, Result);
06669       }
06670     } else {
06671       if (RHSIsOK) {
06672         // We can't evaluate the LHS; however, sometimes the result
06673         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
06674         if (rhsResult == (E->getOpcode() == BO_LOr))
06675           return Success(rhsResult, E, Result);
06676       }
06677     }
06678     
06679     return false;
06680   }
06681   
06682   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
06683          E->getRHS()->getType()->isIntegralOrEnumerationType());
06684   
06685   if (LHSResult.Failed || RHSResult.Failed)
06686     return false;
06687   
06688   const APValue &LHSVal = LHSResult.Val;
06689   const APValue &RHSVal = RHSResult.Val;
06690   
06691   // Handle cases like (unsigned long)&a + 4.
06692   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
06693     Result = LHSVal;
06694     CharUnits AdditionalOffset =
06695         CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
06696     if (E->getOpcode() == BO_Add)
06697       Result.getLValueOffset() += AdditionalOffset;
06698     else
06699       Result.getLValueOffset() -= AdditionalOffset;
06700     return true;
06701   }
06702   
06703   // Handle cases like 4 + (unsigned long)&a
06704   if (E->getOpcode() == BO_Add &&
06705       RHSVal.isLValue() && LHSVal.isInt()) {
06706     Result = RHSVal;
06707     Result.getLValueOffset() +=
06708         CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
06709     return true;
06710   }
06711   
06712   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
06713     // Handle (intptr_t)&&A - (intptr_t)&&B.
06714     if (!LHSVal.getLValueOffset().isZero() ||
06715         !RHSVal.getLValueOffset().isZero())
06716       return false;
06717     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
06718     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
06719     if (!LHSExpr || !RHSExpr)
06720       return false;
06721     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
06722     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
06723     if (!LHSAddrExpr || !RHSAddrExpr)
06724       return false;
06725     // Make sure both labels come from the same function.
06726     if (LHSAddrExpr->getLabel()->getDeclContext() !=
06727         RHSAddrExpr->getLabel()->getDeclContext())
06728       return false;
06729     Result = APValue(LHSAddrExpr, RHSAddrExpr);
06730     return true;
06731   }
06732 
06733   // All the remaining cases expect both operands to be an integer
06734   if (!LHSVal.isInt() || !RHSVal.isInt())
06735     return Error(E);
06736 
06737   // Set up the width and signedness manually, in case it can't be deduced
06738   // from the operation we're performing.
06739   // FIXME: Don't do this in the cases where we can deduce it.
06740   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
06741                E->getType()->isUnsignedIntegerOrEnumerationType());
06742   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
06743                          RHSVal.getInt(), Value))
06744     return false;
06745   return Success(Value, E, Result);
06746 }
06747 
06748 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
06749   Job &job = Queue.back();
06750   
06751   switch (job.Kind) {
06752     case Job::AnyExprKind: {
06753       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
06754         if (shouldEnqueue(Bop)) {
06755           job.Kind = Job::BinOpKind;
06756           enqueue(Bop->getLHS());
06757           return;
06758         }
06759       }
06760       
06761       EvaluateExpr(job.E, Result);
06762       Queue.pop_back();
06763       return;
06764     }
06765       
06766     case Job::BinOpKind: {
06767       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
06768       bool SuppressRHSDiags = false;
06769       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
06770         Queue.pop_back();
06771         return;
06772       }
06773       if (SuppressRHSDiags)
06774         job.startSpeculativeEval(Info);
06775       job.LHSResult.swap(Result);
06776       job.Kind = Job::BinOpVisitedLHSKind;
06777       enqueue(Bop->getRHS());
06778       return;
06779     }
06780       
06781     case Job::BinOpVisitedLHSKind: {
06782       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
06783       EvalResult RHS;
06784       RHS.swap(Result);
06785       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
06786       Queue.pop_back();
06787       return;
06788     }
06789   }
06790   
06791   llvm_unreachable("Invalid Job::Kind!");
06792 }
06793 
06794 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
06795   if (E->isAssignmentOp())
06796     return Error(E);
06797 
06798   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
06799     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
06800 
06801   QualType LHSTy = E->getLHS()->getType();
06802   QualType RHSTy = E->getRHS()->getType();
06803 
06804   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
06805     ComplexValue LHS, RHS;
06806     bool LHSOK;
06807     if (E->getLHS()->getType()->isRealFloatingType()) {
06808       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
06809       if (LHSOK) {
06810         LHS.makeComplexFloat();
06811         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
06812       }
06813     } else {
06814       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
06815     }
06816     if (!LHSOK && !Info.keepEvaluatingAfterFailure())
06817       return false;
06818 
06819     if (E->getRHS()->getType()->isRealFloatingType()) {
06820       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
06821         return false;
06822       RHS.makeComplexFloat();
06823       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
06824     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
06825       return false;
06826 
06827     if (LHS.isComplexFloat()) {
06828       APFloat::cmpResult CR_r =
06829         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
06830       APFloat::cmpResult CR_i =
06831         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
06832 
06833       if (E->getOpcode() == BO_EQ)
06834         return Success((CR_r == APFloat::cmpEqual &&
06835                         CR_i == APFloat::cmpEqual), E);
06836       else {
06837         assert(E->getOpcode() == BO_NE &&
06838                "Invalid complex comparison.");
06839         return Success(((CR_r == APFloat::cmpGreaterThan ||
06840                          CR_r == APFloat::cmpLessThan ||
06841                          CR_r == APFloat::cmpUnordered) ||
06842                         (CR_i == APFloat::cmpGreaterThan ||
06843                          CR_i == APFloat::cmpLessThan ||
06844                          CR_i == APFloat::cmpUnordered)), E);
06845       }
06846     } else {
06847       if (E->getOpcode() == BO_EQ)
06848         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
06849                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
06850       else {
06851         assert(E->getOpcode() == BO_NE &&
06852                "Invalid compex comparison.");
06853         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
06854                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
06855       }
06856     }
06857   }
06858 
06859   if (LHSTy->isRealFloatingType() &&
06860       RHSTy->isRealFloatingType()) {
06861     APFloat RHS(0.0), LHS(0.0);
06862 
06863     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
06864     if (!LHSOK && !Info.keepEvaluatingAfterFailure())
06865       return false;
06866 
06867     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
06868       return false;
06869 
06870     APFloat::cmpResult CR = LHS.compare(RHS);
06871 
06872     switch (E->getOpcode()) {
06873     default:
06874       llvm_unreachable("Invalid binary operator!");
06875     case BO_LT:
06876       return Success(CR == APFloat::cmpLessThan, E);
06877     case BO_GT:
06878       return Success(CR == APFloat::cmpGreaterThan, E);
06879     case BO_LE:
06880       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
06881     case BO_GE:
06882       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
06883                      E);
06884     case BO_EQ:
06885       return Success(CR == APFloat::cmpEqual, E);
06886     case BO_NE:
06887       return Success(CR == APFloat::cmpGreaterThan
06888                      || CR == APFloat::cmpLessThan
06889                      || CR == APFloat::cmpUnordered, E);
06890     }
06891   }
06892 
06893   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
06894     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
06895       LValue LHSValue, RHSValue;
06896 
06897       bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
06898       if (!LHSOK && Info.keepEvaluatingAfterFailure())
06899         return false;
06900 
06901       if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
06902         return false;
06903 
06904       // Reject differing bases from the normal codepath; we special-case
06905       // comparisons to null.
06906       if (!HasSameBase(LHSValue, RHSValue)) {
06907         if (E->getOpcode() == BO_Sub) {
06908           // Handle &&A - &&B.
06909           if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
06910             return false;
06911           const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
06912           const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
06913           if (!LHSExpr || !RHSExpr)
06914             return false;
06915           const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
06916           const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
06917           if (!LHSAddrExpr || !RHSAddrExpr)
06918             return false;
06919           // Make sure both labels come from the same function.
06920           if (LHSAddrExpr->getLabel()->getDeclContext() !=
06921               RHSAddrExpr->getLabel()->getDeclContext())
06922             return false;
06923           Result = APValue(LHSAddrExpr, RHSAddrExpr);
06924           return true;
06925         }
06926         // Inequalities and subtractions between unrelated pointers have
06927         // unspecified or undefined behavior.
06928         if (!E->isEqualityOp())
06929           return Error(E);
06930         // A constant address may compare equal to the address of a symbol.
06931         // The one exception is that address of an object cannot compare equal
06932         // to a null pointer constant.
06933         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
06934             (!RHSValue.Base && !RHSValue.Offset.isZero()))
06935           return Error(E);
06936         // It's implementation-defined whether distinct literals will have
06937         // distinct addresses. In clang, the result of such a comparison is
06938         // unspecified, so it is not a constant expression. However, we do know
06939         // that the address of a literal will be non-null.
06940         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
06941             LHSValue.Base && RHSValue.Base)
06942           return Error(E);
06943         // We can't tell whether weak symbols will end up pointing to the same
06944         // object.
06945         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
06946           return Error(E);
06947         // We can't compare the address of the start of one object with the
06948         // past-the-end address of another object, per C++ DR1652.
06949         if ((LHSValue.Base && LHSValue.Offset.isZero() &&
06950              isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
06951             (RHSValue.Base && RHSValue.Offset.isZero() &&
06952              isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
06953           return Error(E);
06954         // Pointers with different bases cannot represent the same object.
06955         // (Note that clang defaults to -fmerge-all-constants, which can
06956         // lead to inconsistent results for comparisons involving the address
06957         // of a constant; this generally doesn't matter in practice.)
06958         return Success(E->getOpcode() == BO_NE, E);
06959       }
06960 
06961       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
06962       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
06963 
06964       SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
06965       SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
06966 
06967       if (E->getOpcode() == BO_Sub) {
06968         // C++11 [expr.add]p6:
06969         //   Unless both pointers point to elements of the same array object, or
06970         //   one past the last element of the array object, the behavior is
06971         //   undefined.
06972         if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
06973             !AreElementsOfSameArray(getType(LHSValue.Base),
06974                                     LHSDesignator, RHSDesignator))
06975           CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
06976 
06977         QualType Type = E->getLHS()->getType();
06978         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
06979 
06980         CharUnits ElementSize;
06981         if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
06982           return false;
06983 
06984         // As an extension, a type may have zero size (empty struct or union in
06985         // C, array of zero length). Pointer subtraction in such cases has
06986         // undefined behavior, so is not constant.
06987         if (ElementSize.isZero()) {
06988           Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
06989             << ElementType;
06990           return false;
06991         }
06992 
06993         // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
06994         // and produce incorrect results when it overflows. Such behavior
06995         // appears to be non-conforming, but is common, so perhaps we should
06996         // assume the standard intended for such cases to be undefined behavior
06997         // and check for them.
06998 
06999         // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
07000         // overflow in the final conversion to ptrdiff_t.
07001         APSInt LHS(
07002           llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
07003         APSInt RHS(
07004           llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
07005         APSInt ElemSize(
07006           llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
07007         APSInt TrueResult = (LHS - RHS) / ElemSize;
07008         APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
07009 
07010         if (Result.extend(65) != TrueResult)
07011           HandleOverflow(Info, E, TrueResult, E->getType());
07012         return Success(Result, E);
07013       }
07014 
07015       // C++11 [expr.rel]p3:
07016       //   Pointers to void (after pointer conversions) can be compared, with a
07017       //   result defined as follows: If both pointers represent the same
07018       //   address or are both the null pointer value, the result is true if the
07019       //   operator is <= or >= and false otherwise; otherwise the result is
07020       //   unspecified.
07021       // We interpret this as applying to pointers to *cv* void.
07022       if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
07023           E->isRelationalOp())
07024         CCEDiag(E, diag::note_constexpr_void_comparison);
07025 
07026       // C++11 [expr.rel]p2:
07027       // - If two pointers point to non-static data members of the same object,
07028       //   or to subobjects or array elements fo such members, recursively, the
07029       //   pointer to the later declared member compares greater provided the
07030       //   two members have the same access control and provided their class is
07031       //   not a union.
07032       //   [...]
07033       // - Otherwise pointer comparisons are unspecified.
07034       if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
07035           E->isRelationalOp()) {
07036         bool WasArrayIndex;
07037         unsigned Mismatch =
07038           FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
07039                                  RHSDesignator, WasArrayIndex);
07040         // At the point where the designators diverge, the comparison has a
07041         // specified value if:
07042         //  - we are comparing array indices
07043         //  - we are comparing fields of a union, or fields with the same access
07044         // Otherwise, the result is unspecified and thus the comparison is not a
07045         // constant expression.
07046         if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
07047             Mismatch < RHSDesignator.Entries.size()) {
07048           const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
07049           const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
07050           if (!LF && !RF)
07051             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
07052           else if (!LF)
07053             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
07054               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
07055               << RF->getParent() << RF;
07056           else if (!RF)
07057             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
07058               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
07059               << LF->getParent() << LF;
07060           else if (!LF->getParent()->isUnion() &&
07061                    LF->getAccess() != RF->getAccess())
07062             CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
07063               << LF << LF->getAccess() << RF << RF->getAccess()
07064               << LF->getParent();
07065         }
07066       }
07067 
07068       // The comparison here must be unsigned, and performed with the same
07069       // width as the pointer.
07070       unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
07071       uint64_t CompareLHS = LHSOffset.getQuantity();
07072       uint64_t CompareRHS = RHSOffset.getQuantity();
07073       assert(PtrSize <= 64 && "Unexpected pointer width");
07074       uint64_t Mask = ~0ULL >> (64 - PtrSize);
07075       CompareLHS &= Mask;
07076       CompareRHS &= Mask;
07077 
07078       // If there is a base and this is a relational operator, we can only
07079       // compare pointers within the object in question; otherwise, the result
07080       // depends on where the object is located in memory.
07081       if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
07082         QualType BaseTy = getType(LHSValue.Base);
07083         if (BaseTy->isIncompleteType())
07084           return Error(E);
07085         CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
07086         uint64_t OffsetLimit = Size.getQuantity();
07087         if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
07088           return Error(E);
07089       }
07090 
07091       switch (E->getOpcode()) {
07092       default: llvm_unreachable("missing comparison operator");
07093       case BO_LT: return Success(CompareLHS < CompareRHS, E);
07094       case BO_GT: return Success(CompareLHS > CompareRHS, E);
07095       case BO_LE: return Success(CompareLHS <= CompareRHS, E);
07096       case BO_GE: return Success(CompareLHS >= CompareRHS, E);
07097       case BO_EQ: return Success(CompareLHS == CompareRHS, E);
07098       case BO_NE: return Success(CompareLHS != CompareRHS, E);
07099       }
07100     }
07101   }
07102 
07103   if (LHSTy->isMemberPointerType()) {
07104     assert(E->isEqualityOp() && "unexpected member pointer operation");
07105     assert(RHSTy->isMemberPointerType() && "invalid comparison");
07106 
07107     MemberPtr LHSValue, RHSValue;
07108 
07109     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
07110     if (!LHSOK && Info.keepEvaluatingAfterFailure())
07111       return false;
07112 
07113     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
07114       return false;
07115 
07116     // C++11 [expr.eq]p2:
07117     //   If both operands are null, they compare equal. Otherwise if only one is
07118     //   null, they compare unequal.
07119     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
07120       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
07121       return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
07122     }
07123 
07124     //   Otherwise if either is a pointer to a virtual member function, the
07125     //   result is unspecified.
07126     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
07127       if (MD->isVirtual())
07128         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
07129     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
07130       if (MD->isVirtual())
07131         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
07132 
07133     //   Otherwise they compare equal if and only if they would refer to the
07134     //   same member of the same most derived object or the same subobject if
07135     //   they were dereferenced with a hypothetical object of the associated
07136     //   class type.
07137     bool Equal = LHSValue == RHSValue;
07138     return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
07139   }
07140 
07141   if (LHSTy->isNullPtrType()) {
07142     assert(E->isComparisonOp() && "unexpected nullptr operation");
07143     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
07144     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
07145     // are compared, the result is true of the operator is <=, >= or ==, and
07146     // false otherwise.
07147     BinaryOperator::Opcode Opcode = E->getOpcode();
07148     return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
07149   }
07150 
07151   assert((!LHSTy->isIntegralOrEnumerationType() ||
07152           !RHSTy->isIntegralOrEnumerationType()) &&
07153          "DataRecursiveIntBinOpEvaluator should have handled integral types");
07154   // We can't continue from here for non-integral types.
07155   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
07156 }
07157 
07158 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
07159 /// a result as the expression's type.
07160 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
07161                                     const UnaryExprOrTypeTraitExpr *E) {
07162   switch(E->getKind()) {
07163   case UETT_AlignOf: {
07164     if (E->isArgumentType())
07165       return Success(GetAlignOfType(Info, E->getArgumentType()), E);
07166     else
07167       return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
07168   }
07169 
07170   case UETT_VecStep: {
07171     QualType Ty = E->getTypeOfArgument();
07172 
07173     if (Ty->isVectorType()) {
07174       unsigned n = Ty->castAs<VectorType>()->getNumElements();
07175 
07176       // The vec_step built-in functions that take a 3-component
07177       // vector return 4. (OpenCL 1.1 spec 6.11.12)
07178       if (n == 3)
07179         n = 4;
07180 
07181       return Success(n, E);
07182     } else
07183       return Success(1, E);
07184   }
07185 
07186   case UETT_SizeOf: {
07187     QualType SrcTy = E->getTypeOfArgument();
07188     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
07189     //   the result is the size of the referenced type."
07190     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
07191       SrcTy = Ref->getPointeeType();
07192 
07193     CharUnits Sizeof;
07194     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
07195       return false;
07196     return Success(Sizeof, E);
07197   }
07198   }
07199 
07200   llvm_unreachable("unknown expr/type trait");
07201 }
07202 
07203 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
07204   CharUnits Result;
07205   unsigned n = OOE->getNumComponents();
07206   if (n == 0)
07207     return Error(OOE);
07208   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
07209   for (unsigned i = 0; i != n; ++i) {
07210     OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
07211     switch (ON.getKind()) {
07212     case OffsetOfExpr::OffsetOfNode::Array: {
07213       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
07214       APSInt IdxResult;
07215       if (!EvaluateInteger(Idx, IdxResult, Info))
07216         return false;
07217       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
07218       if (!AT)
07219         return Error(OOE);
07220       CurrentType = AT->getElementType();
07221       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
07222       Result += IdxResult.getSExtValue() * ElementSize;
07223       break;
07224     }
07225 
07226     case OffsetOfExpr::OffsetOfNode::Field: {
07227       FieldDecl *MemberDecl = ON.getField();
07228       const RecordType *RT = CurrentType->getAs<RecordType>();
07229       if (!RT)
07230         return Error(OOE);
07231       RecordDecl *RD = RT->getDecl();
07232       if (RD->isInvalidDecl()) return false;
07233       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
07234       unsigned i = MemberDecl->getFieldIndex();
07235       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
07236       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
07237       CurrentType = MemberDecl->getType().getNonReferenceType();
07238       break;
07239     }
07240 
07241     case OffsetOfExpr::OffsetOfNode::Identifier:
07242       llvm_unreachable("dependent __builtin_offsetof");
07243 
07244     case OffsetOfExpr::OffsetOfNode::Base: {
07245       CXXBaseSpecifier *BaseSpec = ON.getBase();
07246       if (BaseSpec->isVirtual())
07247         return Error(OOE);
07248 
07249       // Find the layout of the class whose base we are looking into.
07250       const RecordType *RT = CurrentType->getAs<RecordType>();
07251       if (!RT)
07252         return Error(OOE);
07253       RecordDecl *RD = RT->getDecl();
07254       if (RD->isInvalidDecl()) return false;
07255       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
07256 
07257       // Find the base class itself.
07258       CurrentType = BaseSpec->getType();
07259       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
07260       if (!BaseRT)
07261         return Error(OOE);
07262       
07263       // Add the offset to the base.
07264       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
07265       break;
07266     }
07267     }
07268   }
07269   return Success(Result, OOE);
07270 }
07271 
07272 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
07273   switch (E->getOpcode()) {
07274   default:
07275     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
07276     // See C99 6.6p3.
07277     return Error(E);
07278   case UO_Extension:
07279     // FIXME: Should extension allow i-c-e extension expressions in its scope?
07280     // If so, we could clear the diagnostic ID.
07281     return Visit(E->getSubExpr());
07282   case UO_Plus:
07283     // The result is just the value.
07284     return Visit(E->getSubExpr());
07285   case UO_Minus: {
07286     if (!Visit(E->getSubExpr()))
07287       return false;
07288     if (!Result.isInt()) return Error(E);
07289     const APSInt &Value = Result.getInt();
07290     if (Value.isSigned() && Value.isMinSignedValue())
07291       HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
07292                      E->getType());
07293     return Success(-Value, E);
07294   }
07295   case UO_Not: {
07296     if (!Visit(E->getSubExpr()))
07297       return false;
07298     if (!Result.isInt()) return Error(E);
07299     return Success(~Result.getInt(), E);
07300   }
07301   case UO_LNot: {
07302     bool bres;
07303     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
07304       return false;
07305     return Success(!bres, E);
07306   }
07307   }
07308 }
07309 
07310 /// HandleCast - This is used to evaluate implicit or explicit casts where the
07311 /// result type is integer.
07312 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
07313   const Expr *SubExpr = E->getSubExpr();
07314   QualType DestType = E->getType();
07315   QualType SrcType = SubExpr->getType();
07316 
07317   switch (E->getCastKind()) {
07318   case CK_BaseToDerived:
07319   case CK_DerivedToBase:
07320   case CK_UncheckedDerivedToBase:
07321   case CK_Dynamic:
07322   case CK_ToUnion:
07323   case CK_ArrayToPointerDecay:
07324   case CK_FunctionToPointerDecay:
07325   case CK_NullToPointer:
07326   case CK_NullToMemberPointer:
07327   case CK_BaseToDerivedMemberPointer:
07328   case CK_DerivedToBaseMemberPointer:
07329   case CK_ReinterpretMemberPointer:
07330   case CK_ConstructorConversion:
07331   case CK_IntegralToPointer:
07332   case CK_ToVoid:
07333   case CK_VectorSplat:
07334   case CK_IntegralToFloating:
07335   case CK_FloatingCast:
07336   case CK_CPointerToObjCPointerCast:
07337   case CK_BlockPointerToObjCPointerCast:
07338   case CK_AnyPointerToBlockPointerCast:
07339   case CK_ObjCObjectLValueCast:
07340   case CK_FloatingRealToComplex:
07341   case CK_FloatingComplexToReal:
07342   case CK_FloatingComplexCast:
07343   case CK_FloatingComplexToIntegralComplex:
07344   case CK_IntegralRealToComplex:
07345   case CK_IntegralComplexCast:
07346   case CK_IntegralComplexToFloatingComplex:
07347   case CK_BuiltinFnToFnPtr:
07348   case CK_ZeroToOCLEvent:
07349   case CK_NonAtomicToAtomic:
07350   case CK_AddressSpaceConversion:
07351     llvm_unreachable("invalid cast kind for integral value");
07352 
07353   case CK_BitCast:
07354   case CK_Dependent:
07355   case CK_LValueBitCast:
07356   case CK_ARCProduceObject:
07357   case CK_ARCConsumeObject:
07358   case CK_ARCReclaimReturnedObject:
07359   case CK_ARCExtendBlockObject:
07360   case CK_CopyAndAutoreleaseBlockObject:
07361     return Error(E);
07362 
07363   case CK_UserDefinedConversion:
07364   case CK_LValueToRValue:
07365   case CK_AtomicToNonAtomic:
07366   case CK_NoOp:
07367     return ExprEvaluatorBaseTy::VisitCastExpr(E);
07368 
07369   case CK_MemberPointerToBoolean:
07370   case CK_PointerToBoolean:
07371   case CK_IntegralToBoolean:
07372   case CK_FloatingToBoolean:
07373   case CK_FloatingComplexToBoolean:
07374   case CK_IntegralComplexToBoolean: {
07375     bool BoolResult;
07376     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
07377       return false;
07378     return Success(BoolResult, E);
07379   }
07380 
07381   case CK_IntegralCast: {
07382     if (!Visit(SubExpr))
07383       return false;
07384 
07385     if (!Result.isInt()) {
07386       // Allow casts of address-of-label differences if they are no-ops
07387       // or narrowing.  (The narrowing case isn't actually guaranteed to
07388       // be constant-evaluatable except in some narrow cases which are hard
07389       // to detect here.  We let it through on the assumption the user knows
07390       // what they are doing.)
07391       if (Result.isAddrLabelDiff())
07392         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
07393       // Only allow casts of lvalues if they are lossless.
07394       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
07395     }
07396 
07397     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
07398                                       Result.getInt()), E);
07399   }
07400 
07401   case CK_PointerToIntegral: {
07402     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
07403 
07404     LValue LV;
07405     if (!EvaluatePointer(SubExpr, LV, Info))
07406       return false;
07407 
07408     if (LV.getLValueBase()) {
07409       // Only allow based lvalue casts if they are lossless.
07410       // FIXME: Allow a larger integer size than the pointer size, and allow
07411       // narrowing back down to pointer width in subsequent integral casts.
07412       // FIXME: Check integer type's active bits, not its type size.
07413       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
07414         return Error(E);
07415 
07416       LV.Designator.setInvalid();
07417       LV.moveInto(Result);
07418       return true;
07419     }
07420 
07421     APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(), 
07422                                          SrcType);
07423     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
07424   }
07425 
07426   case CK_IntegralComplexToReal: {
07427     ComplexValue C;
07428     if (!EvaluateComplex(SubExpr, C, Info))
07429       return false;
07430     return Success(C.getComplexIntReal(), E);
07431   }
07432 
07433   case CK_FloatingToIntegral: {
07434     APFloat F(0.0);
07435     if (!EvaluateFloat(SubExpr, F, Info))
07436       return false;
07437 
07438     APSInt Value;
07439     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
07440       return false;
07441     return Success(Value, E);
07442   }
07443   }
07444 
07445   llvm_unreachable("unknown cast resulting in integral value");
07446 }
07447 
07448 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
07449   if (E->getSubExpr()->getType()->isAnyComplexType()) {
07450     ComplexValue LV;
07451     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
07452       return false;
07453     if (!LV.isComplexInt())
07454       return Error(E);
07455     return Success(LV.getComplexIntReal(), E);
07456   }
07457 
07458   return Visit(E->getSubExpr());
07459 }
07460 
07461 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
07462   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
07463     ComplexValue LV;
07464     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
07465       return false;
07466     if (!LV.isComplexInt())
07467       return Error(E);
07468     return Success(LV.getComplexIntImag(), E);
07469   }
07470 
07471   VisitIgnoredValue(E->getSubExpr());
07472   return Success(0, E);
07473 }
07474 
07475 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
07476   return Success(E->getPackLength(), E);
07477 }
07478 
07479 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
07480   return Success(E->getValue(), E);
07481 }
07482 
07483 //===----------------------------------------------------------------------===//
07484 // Float Evaluation
07485 //===----------------------------------------------------------------------===//
07486 
07487 namespace {
07488 class FloatExprEvaluator
07489   : public ExprEvaluatorBase<FloatExprEvaluator> {
07490   APFloat &Result;
07491 public:
07492   FloatExprEvaluator(EvalInfo &info, APFloat &result)
07493     : ExprEvaluatorBaseTy(info), Result(result) {}
07494 
07495   bool Success(const APValue &V, const Expr *e) {
07496     Result = V.getFloat();
07497     return true;
07498   }
07499 
07500   bool ZeroInitialization(const Expr *E) {
07501     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
07502     return true;
07503   }
07504 
07505   bool VisitCallExpr(const CallExpr *E);
07506 
07507   bool VisitUnaryOperator(const UnaryOperator *E);
07508   bool VisitBinaryOperator(const BinaryOperator *E);
07509   bool VisitFloatingLiteral(const FloatingLiteral *E);
07510   bool VisitCastExpr(const CastExpr *E);
07511 
07512   bool VisitUnaryReal(const UnaryOperator *E);
07513   bool VisitUnaryImag(const UnaryOperator *E);
07514 
07515   // FIXME: Missing: array subscript of vector, member of vector
07516 };
07517 } // end anonymous namespace
07518 
07519 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
07520   assert(E->isRValue() && E->getType()->isRealFloatingType());
07521   return FloatExprEvaluator(Info, Result).Visit(E);
07522 }
07523 
07524 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
07525                                   QualType ResultTy,
07526                                   const Expr *Arg,
07527                                   bool SNaN,
07528                                   llvm::APFloat &Result) {
07529   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
07530   if (!S) return false;
07531 
07532   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
07533 
07534   llvm::APInt fill;
07535 
07536   // Treat empty strings as if they were zero.
07537   if (S->getString().empty())
07538     fill = llvm::APInt(32, 0);
07539   else if (S->getString().getAsInteger(0, fill))
07540     return false;
07541 
07542   if (SNaN)
07543     Result = llvm::APFloat::getSNaN(Sem, false, &fill);
07544   else
07545     Result = llvm::APFloat::getQNaN(Sem, false, &fill);
07546   return true;
07547 }
07548 
07549 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
07550   switch (E->getBuiltinCallee()) {
07551   default:
07552     return ExprEvaluatorBaseTy::VisitCallExpr(E);
07553 
07554   case Builtin::BI__builtin_huge_val:
07555   case Builtin::BI__builtin_huge_valf:
07556   case Builtin::BI__builtin_huge_vall:
07557   case Builtin::BI__builtin_inf:
07558   case Builtin::BI__builtin_inff:
07559   case Builtin::BI__builtin_infl: {
07560     const llvm::fltSemantics &Sem =
07561       Info.Ctx.getFloatTypeSemantics(E->getType());
07562     Result = llvm::APFloat::getInf(Sem);
07563     return true;
07564   }
07565 
07566   case Builtin::BI__builtin_nans:
07567   case Builtin::BI__builtin_nansf:
07568   case Builtin::BI__builtin_nansl:
07569     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
07570                                true, Result))
07571       return Error(E);
07572     return true;
07573 
07574   case Builtin::BI__builtin_nan:
07575   case Builtin::BI__builtin_nanf:
07576   case Builtin::BI__builtin_nanl:
07577     // If this is __builtin_nan() turn this into a nan, otherwise we
07578     // can't constant fold it.
07579     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
07580                                false, Result))
07581       return Error(E);
07582     return true;
07583 
07584   case Builtin::BI__builtin_fabs:
07585   case Builtin::BI__builtin_fabsf:
07586   case Builtin::BI__builtin_fabsl:
07587     if (!EvaluateFloat(E->getArg(0), Result, Info))
07588       return false;
07589 
07590     if (Result.isNegative())
07591       Result.changeSign();
07592     return true;
07593 
07594   // FIXME: Builtin::BI__builtin_powi
07595   // FIXME: Builtin::BI__builtin_powif
07596   // FIXME: Builtin::BI__builtin_powil
07597 
07598   case Builtin::BI__builtin_copysign:
07599   case Builtin::BI__builtin_copysignf:
07600   case Builtin::BI__builtin_copysignl: {
07601     APFloat RHS(0.);
07602     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
07603         !EvaluateFloat(E->getArg(1), RHS, Info))
07604       return false;
07605     Result.copySign(RHS);
07606     return true;
07607   }
07608   }
07609 }
07610 
07611 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
07612   if (E->getSubExpr()->getType()->isAnyComplexType()) {
07613     ComplexValue CV;
07614     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
07615       return false;
07616     Result = CV.FloatReal;
07617     return true;
07618   }
07619 
07620   return Visit(E->getSubExpr());
07621 }
07622 
07623 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
07624   if (E->getSubExpr()->getType()->isAnyComplexType()) {
07625     ComplexValue CV;
07626     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
07627       return false;
07628     Result = CV.FloatImag;
07629     return true;
07630   }
07631 
07632   VisitIgnoredValue(E->getSubExpr());
07633   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
07634   Result = llvm::APFloat::getZero(Sem);
07635   return true;
07636 }
07637 
07638 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
07639   switch (E->getOpcode()) {
07640   default: return Error(E);
07641   case UO_Plus:
07642     return EvaluateFloat(E->getSubExpr(), Result, Info);
07643   case UO_Minus:
07644     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
07645       return false;
07646     Result.changeSign();
07647     return true;
07648   }
07649 }
07650 
07651 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
07652   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
07653     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
07654 
07655   APFloat RHS(0.0);
07656   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
07657   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
07658     return false;
07659   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
07660          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
07661 }
07662 
07663 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
07664   Result = E->getValue();
07665   return true;
07666 }
07667 
07668 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
07669   const Expr* SubExpr = E->getSubExpr();
07670 
07671   switch (E->getCastKind()) {
07672   default:
07673     return ExprEvaluatorBaseTy::VisitCastExpr(E);
07674 
07675   case CK_IntegralToFloating: {
07676     APSInt IntResult;
07677     return EvaluateInteger(SubExpr, IntResult, Info) &&
07678            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
07679                                 E->getType(), Result);
07680   }
07681 
07682   case CK_FloatingCast: {
07683     if (!Visit(SubExpr))
07684       return false;
07685     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
07686                                   Result);
07687   }
07688 
07689   case CK_FloatingComplexToReal: {
07690     ComplexValue V;
07691     if (!EvaluateComplex(SubExpr, V, Info))
07692       return false;
07693     Result = V.getComplexFloatReal();
07694     return true;
07695   }
07696   }
07697 }
07698 
07699 //===----------------------------------------------------------------------===//
07700 // Complex Evaluation (for float and integer)
07701 //===----------------------------------------------------------------------===//
07702 
07703 namespace {
07704 class ComplexExprEvaluator
07705   : public ExprEvaluatorBase<ComplexExprEvaluator> {
07706   ComplexValue &Result;
07707 
07708 public:
07709   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
07710     : ExprEvaluatorBaseTy(info), Result(Result) {}
07711 
07712   bool Success(const APValue &V, const Expr *e) {
07713     Result.setFrom(V);
07714     return true;
07715   }
07716 
07717   bool ZeroInitialization(const Expr *E);
07718 
07719   //===--------------------------------------------------------------------===//
07720   //                            Visitor Methods
07721   //===--------------------------------------------------------------------===//
07722 
07723   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
07724   bool VisitCastExpr(const CastExpr *E);
07725   bool VisitBinaryOperator(const BinaryOperator *E);
07726   bool VisitUnaryOperator(const UnaryOperator *E);
07727   bool VisitInitListExpr(const InitListExpr *E);
07728 };
07729 } // end anonymous namespace
07730 
07731 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
07732                             EvalInfo &Info) {
07733   assert(E->isRValue() && E->getType()->isAnyComplexType());
07734   return ComplexExprEvaluator(Info, Result).Visit(E);
07735 }
07736 
07737 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
07738   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
07739   if (ElemTy->isRealFloatingType()) {
07740     Result.makeComplexFloat();
07741     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
07742     Result.FloatReal = Zero;
07743     Result.FloatImag = Zero;
07744   } else {
07745     Result.makeComplexInt();
07746     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
07747     Result.IntReal = Zero;
07748     Result.IntImag = Zero;
07749   }
07750   return true;
07751 }
07752 
07753 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
07754   const Expr* SubExpr = E->getSubExpr();
07755 
07756   if (SubExpr->getType()->isRealFloatingType()) {
07757     Result.makeComplexFloat();
07758     APFloat &Imag = Result.FloatImag;
07759     if (!EvaluateFloat(SubExpr, Imag, Info))
07760       return false;
07761 
07762     Result.FloatReal = APFloat(Imag.getSemantics());
07763     return true;
07764   } else {
07765     assert(SubExpr->getType()->isIntegerType() &&
07766            "Unexpected imaginary literal.");
07767 
07768     Result.makeComplexInt();
07769     APSInt &Imag = Result.IntImag;
07770     if (!EvaluateInteger(SubExpr, Imag, Info))
07771       return false;
07772 
07773     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
07774     return true;
07775   }
07776 }
07777 
07778 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
07779 
07780   switch (E->getCastKind()) {
07781   case CK_BitCast:
07782   case CK_BaseToDerived:
07783   case CK_DerivedToBase:
07784   case CK_UncheckedDerivedToBase:
07785   case CK_Dynamic:
07786   case CK_ToUnion:
07787   case CK_ArrayToPointerDecay:
07788   case CK_FunctionToPointerDecay:
07789   case CK_NullToPointer:
07790   case CK_NullToMemberPointer:
07791   case CK_BaseToDerivedMemberPointer:
07792   case CK_DerivedToBaseMemberPointer:
07793   case CK_MemberPointerToBoolean:
07794   case CK_ReinterpretMemberPointer:
07795   case CK_ConstructorConversion:
07796   case CK_IntegralToPointer:
07797   case CK_PointerToIntegral:
07798   case CK_PointerToBoolean:
07799   case CK_ToVoid:
07800   case CK_VectorSplat:
07801   case CK_IntegralCast:
07802   case CK_IntegralToBoolean:
07803   case CK_IntegralToFloating:
07804   case CK_FloatingToIntegral:
07805   case CK_FloatingToBoolean:
07806   case CK_FloatingCast:
07807   case CK_CPointerToObjCPointerCast:
07808   case CK_BlockPointerToObjCPointerCast:
07809   case CK_AnyPointerToBlockPointerCast:
07810   case CK_ObjCObjectLValueCast:
07811   case CK_FloatingComplexToReal:
07812   case CK_FloatingComplexToBoolean:
07813   case CK_IntegralComplexToReal:
07814   case CK_IntegralComplexToBoolean:
07815   case CK_ARCProduceObject:
07816   case CK_ARCConsumeObject:
07817   case CK_ARCReclaimReturnedObject:
07818   case CK_ARCExtendBlockObject:
07819   case CK_CopyAndAutoreleaseBlockObject:
07820   case CK_BuiltinFnToFnPtr:
07821   case CK_ZeroToOCLEvent:
07822   case CK_NonAtomicToAtomic:
07823   case CK_AddressSpaceConversion:
07824     llvm_unreachable("invalid cast kind for complex value");
07825 
07826   case CK_LValueToRValue:
07827   case CK_AtomicToNonAtomic:
07828   case CK_NoOp:
07829     return ExprEvaluatorBaseTy::VisitCastExpr(E);
07830 
07831   case CK_Dependent:
07832   case CK_LValueBitCast:
07833   case CK_UserDefinedConversion:
07834     return Error(E);
07835 
07836   case CK_FloatingRealToComplex: {
07837     APFloat &Real = Result.FloatReal;
07838     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
07839       return false;
07840 
07841     Result.makeComplexFloat();
07842     Result.FloatImag = APFloat(Real.getSemantics());
07843     return true;
07844   }
07845 
07846   case CK_FloatingComplexCast: {
07847     if (!Visit(E->getSubExpr()))
07848       return false;
07849 
07850     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
07851     QualType From
07852       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
07853 
07854     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
07855            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
07856   }
07857 
07858   case CK_FloatingComplexToIntegralComplex: {
07859     if (!Visit(E->getSubExpr()))
07860       return false;
07861 
07862     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
07863     QualType From
07864       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
07865     Result.makeComplexInt();
07866     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
07867                                 To, Result.IntReal) &&
07868            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
07869                                 To, Result.IntImag);
07870   }
07871 
07872   case CK_IntegralRealToComplex: {
07873     APSInt &Real = Result.IntReal;
07874     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
07875       return false;
07876 
07877     Result.makeComplexInt();
07878     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
07879     return true;
07880   }
07881 
07882   case CK_IntegralComplexCast: {
07883     if (!Visit(E->getSubExpr()))
07884       return false;
07885 
07886     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
07887     QualType From
07888       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
07889 
07890     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
07891     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
07892     return true;
07893   }
07894 
07895   case CK_IntegralComplexToFloatingComplex: {
07896     if (!Visit(E->getSubExpr()))
07897       return false;
07898 
07899     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
07900     QualType From
07901       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
07902     Result.makeComplexFloat();
07903     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
07904                                 To, Result.FloatReal) &&
07905            HandleIntToFloatCast(Info, E, From, Result.IntImag,
07906                                 To, Result.FloatImag);
07907   }
07908   }
07909 
07910   llvm_unreachable("unknown cast resulting in complex value");
07911 }
07912 
07913 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
07914   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
07915     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
07916 
07917   // Track whether the LHS or RHS is real at the type system level. When this is
07918   // the case we can simplify our evaluation strategy.
07919   bool LHSReal = false, RHSReal = false;
07920 
07921   bool LHSOK;
07922   if (E->getLHS()->getType()->isRealFloatingType()) {
07923     LHSReal = true;
07924     APFloat &Real = Result.FloatReal;
07925     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
07926     if (LHSOK) {
07927       Result.makeComplexFloat();
07928       Result.FloatImag = APFloat(Real.getSemantics());
07929     }
07930   } else {
07931     LHSOK = Visit(E->getLHS());
07932   }
07933   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
07934     return false;
07935 
07936   ComplexValue RHS;
07937   if (E->getRHS()->getType()->isRealFloatingType()) {
07938     RHSReal = true;
07939     APFloat &Real = RHS.FloatReal;
07940     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
07941       return false;
07942     RHS.makeComplexFloat();
07943     RHS.FloatImag = APFloat(Real.getSemantics());
07944   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
07945     return false;
07946 
07947   assert(!(LHSReal && RHSReal) &&
07948          "Cannot have both operands of a complex operation be real.");
07949   switch (E->getOpcode()) {
07950   default: return Error(E);
07951   case BO_Add:
07952     if (Result.isComplexFloat()) {
07953       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
07954                                        APFloat::rmNearestTiesToEven);
07955       if (LHSReal)
07956         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
07957       else if (!RHSReal)
07958         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
07959                                          APFloat::rmNearestTiesToEven);
07960     } else {
07961       Result.getComplexIntReal() += RHS.getComplexIntReal();
07962       Result.getComplexIntImag() += RHS.getComplexIntImag();
07963     }
07964     break;
07965   case BO_Sub:
07966     if (Result.isComplexFloat()) {
07967       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
07968                                             APFloat::rmNearestTiesToEven);
07969       if (LHSReal) {
07970         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
07971         Result.getComplexFloatImag().changeSign();
07972       } else if (!RHSReal) {
07973         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
07974                                               APFloat::rmNearestTiesToEven);
07975       }
07976     } else {
07977       Result.getComplexIntReal() -= RHS.getComplexIntReal();
07978       Result.getComplexIntImag() -= RHS.getComplexIntImag();
07979     }
07980     break;
07981   case BO_Mul:
07982     if (Result.isComplexFloat()) {
07983       // This is an implementation of complex multiplication according to the
07984       // constraints laid out in C11 Annex G. The implemantion uses the
07985       // following naming scheme:
07986       //   (a + ib) * (c + id)
07987       ComplexValue LHS = Result;
07988       APFloat &A = LHS.getComplexFloatReal();
07989       APFloat &B = LHS.getComplexFloatImag();
07990       APFloat &C = RHS.getComplexFloatReal();
07991       APFloat &D = RHS.getComplexFloatImag();
07992       APFloat &ResR = Result.getComplexFloatReal();
07993       APFloat &ResI = Result.getComplexFloatImag();
07994       if (LHSReal) {
07995         assert(!RHSReal && "Cannot have two real operands for a complex op!");
07996         ResR = A * C;
07997         ResI = A * D;
07998       } else if (RHSReal) {
07999         ResR = C * A;
08000         ResI = C * B;
08001       } else {
08002         // In the fully general case, we need to handle NaNs and infinities
08003         // robustly.
08004         APFloat AC = A * C;
08005         APFloat BD = B * D;
08006         APFloat AD = A * D;
08007         APFloat BC = B * C;
08008         ResR = AC - BD;
08009         ResI = AD + BC;
08010         if (ResR.isNaN() && ResI.isNaN()) {
08011           bool Recalc = false;
08012           if (A.isInfinity() || B.isInfinity()) {
08013             A = APFloat::copySign(
08014                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
08015             B = APFloat::copySign(
08016                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
08017             if (C.isNaN())
08018               C = APFloat::copySign(APFloat(C.getSemantics()), C);
08019             if (D.isNaN())
08020               D = APFloat::copySign(APFloat(D.getSemantics()), D);
08021             Recalc = true;
08022           }
08023           if (C.isInfinity() || D.isInfinity()) {
08024             C = APFloat::copySign(
08025                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
08026             D = APFloat::copySign(
08027                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
08028             if (A.isNaN())
08029               A = APFloat::copySign(APFloat(A.getSemantics()), A);
08030             if (B.isNaN())
08031               B = APFloat::copySign(APFloat(B.getSemantics()), B);
08032             Recalc = true;
08033           }
08034           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
08035                           AD.isInfinity() || BC.isInfinity())) {
08036             if (A.isNaN())
08037               A = APFloat::copySign(APFloat(A.getSemantics()), A);
08038             if (B.isNaN())
08039               B = APFloat::copySign(APFloat(B.getSemantics()), B);
08040             if (C.isNaN())
08041               C = APFloat::copySign(APFloat(C.getSemantics()), C);
08042             if (D.isNaN())
08043               D = APFloat::copySign(APFloat(D.getSemantics()), D);
08044             Recalc = true;
08045           }
08046           if (Recalc) {
08047             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
08048             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
08049           }
08050         }
08051       }
08052     } else {
08053       ComplexValue LHS = Result;
08054       Result.getComplexIntReal() =
08055         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
08056          LHS.getComplexIntImag() * RHS.getComplexIntImag());
08057       Result.getComplexIntImag() =
08058         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
08059          LHS.getComplexIntImag() * RHS.getComplexIntReal());
08060     }
08061     break;
08062   case BO_Div:
08063     if (Result.isComplexFloat()) {
08064       // This is an implementation of complex division according to the
08065       // constraints laid out in C11 Annex G. The implemantion uses the
08066       // following naming scheme:
08067       //   (a + ib) / (c + id)
08068       ComplexValue LHS = Result;
08069       APFloat &A = LHS.getComplexFloatReal();
08070       APFloat &B = LHS.getComplexFloatImag();
08071       APFloat &C = RHS.getComplexFloatReal();
08072       APFloat &D = RHS.getComplexFloatImag();
08073       APFloat &ResR = Result.getComplexFloatReal();
08074       APFloat &ResI = Result.getComplexFloatImag();
08075       if (RHSReal) {
08076         ResR = A / C;
08077         ResI = B / C;
08078       } else {
08079         if (LHSReal) {
08080           // No real optimizations we can do here, stub out with zero.
08081           B = APFloat::getZero(A.getSemantics());
08082         }
08083         int DenomLogB = 0;
08084         APFloat MaxCD = maxnum(abs(C), abs(D));
08085         if (MaxCD.isFinite()) {
08086           DenomLogB = ilogb(MaxCD);
08087           C = scalbn(C, -DenomLogB);
08088           D = scalbn(D, -DenomLogB);
08089         }
08090         APFloat Denom = C * C + D * D;
08091         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
08092         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
08093         if (ResR.isNaN() && ResI.isNaN()) {
08094           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
08095             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
08096             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
08097           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
08098                      D.isFinite()) {
08099             A = APFloat::copySign(
08100                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
08101             B = APFloat::copySign(
08102                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
08103             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
08104             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
08105           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
08106             C = APFloat::copySign(
08107                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
08108             D = APFloat::copySign(
08109                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
08110             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
08111             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
08112           }
08113         }
08114       }
08115     } else {
08116       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
08117         return Error(E, diag::note_expr_divide_by_zero);
08118 
08119       ComplexValue LHS = Result;
08120       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
08121         RHS.getComplexIntImag() * RHS.getComplexIntImag();
08122       Result.getComplexIntReal() =
08123         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
08124          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
08125       Result.getComplexIntImag() =
08126         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
08127          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
08128     }
08129     break;
08130   }
08131 
08132   return true;
08133 }
08134 
08135 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
08136   // Get the operand value into 'Result'.
08137   if (!Visit(E->getSubExpr()))
08138     return false;
08139 
08140   switch (E->getOpcode()) {
08141   default:
08142     return Error(E);
08143   case UO_Extension:
08144     return true;
08145   case UO_Plus:
08146     // The result is always just the subexpr.
08147     return true;
08148   case UO_Minus:
08149     if (Result.isComplexFloat()) {
08150       Result.getComplexFloatReal().changeSign();
08151       Result.getComplexFloatImag().changeSign();
08152     }
08153     else {
08154       Result.getComplexIntReal() = -Result.getComplexIntReal();
08155       Result.getComplexIntImag() = -Result.getComplexIntImag();
08156     }
08157     return true;
08158   case UO_Not:
08159     if (Result.isComplexFloat())
08160       Result.getComplexFloatImag().changeSign();
08161     else
08162       Result.getComplexIntImag() = -Result.getComplexIntImag();
08163     return true;
08164   }
08165 }
08166 
08167 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
08168   if (E->getNumInits() == 2) {
08169     if (E->getType()->isComplexType()) {
08170       Result.makeComplexFloat();
08171       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
08172         return false;
08173       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
08174         return false;
08175     } else {
08176       Result.makeComplexInt();
08177       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
08178         return false;
08179       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
08180         return false;
08181     }
08182     return true;
08183   }
08184   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
08185 }
08186 
08187 //===----------------------------------------------------------------------===//
08188 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
08189 // implicit conversion.
08190 //===----------------------------------------------------------------------===//
08191 
08192 namespace {
08193 class AtomicExprEvaluator :
08194     public ExprEvaluatorBase<AtomicExprEvaluator> {
08195   APValue &Result;
08196 public:
08197   AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
08198       : ExprEvaluatorBaseTy(Info), Result(Result) {}
08199 
08200   bool Success(const APValue &V, const Expr *E) {
08201     Result = V;
08202     return true;
08203   }
08204 
08205   bool ZeroInitialization(const Expr *E) {
08206     ImplicitValueInitExpr VIE(
08207         E->getType()->castAs<AtomicType>()->getValueType());
08208     return Evaluate(Result, Info, &VIE);
08209   }
08210 
08211   bool VisitCastExpr(const CastExpr *E) {
08212     switch (E->getCastKind()) {
08213     default:
08214       return ExprEvaluatorBaseTy::VisitCastExpr(E);
08215     case CK_NonAtomicToAtomic:
08216       return Evaluate(Result, Info, E->getSubExpr());
08217     }
08218   }
08219 };
08220 } // end anonymous namespace
08221 
08222 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
08223   assert(E->isRValue() && E->getType()->isAtomicType());
08224   return AtomicExprEvaluator(Info, Result).Visit(E);
08225 }
08226 
08227 //===----------------------------------------------------------------------===//
08228 // Void expression evaluation, primarily for a cast to void on the LHS of a
08229 // comma operator
08230 //===----------------------------------------------------------------------===//
08231 
08232 namespace {
08233 class VoidExprEvaluator
08234   : public ExprEvaluatorBase<VoidExprEvaluator> {
08235 public:
08236   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
08237 
08238   bool Success(const APValue &V, const Expr *e) { return true; }
08239 
08240   bool VisitCastExpr(const CastExpr *E) {
08241     switch (E->getCastKind()) {
08242     default:
08243       return ExprEvaluatorBaseTy::VisitCastExpr(E);
08244     case CK_ToVoid:
08245       VisitIgnoredValue(E->getSubExpr());
08246       return true;
08247     }
08248   }
08249 
08250   bool VisitCallExpr(const CallExpr *E) {
08251     switch (E->getBuiltinCallee()) {
08252     default:
08253       return ExprEvaluatorBaseTy::VisitCallExpr(E);
08254     case Builtin::BI__assume:
08255     case Builtin::BI__builtin_assume:
08256       // The argument is not evaluated!
08257       return true;
08258     }
08259   }
08260 };
08261 } // end anonymous namespace
08262 
08263 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
08264   assert(E->isRValue() && E->getType()->isVoidType());
08265   return VoidExprEvaluator(Info).Visit(E);
08266 }
08267 
08268 //===----------------------------------------------------------------------===//
08269 // Top level Expr::EvaluateAsRValue method.
08270 //===----------------------------------------------------------------------===//
08271 
08272 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
08273   // In C, function designators are not lvalues, but we evaluate them as if they
08274   // are.
08275   QualType T = E->getType();
08276   if (E->isGLValue() || T->isFunctionType()) {
08277     LValue LV;
08278     if (!EvaluateLValue(E, LV, Info))
08279       return false;
08280     LV.moveInto(Result);
08281   } else if (T->isVectorType()) {
08282     if (!EvaluateVector(E, Result, Info))
08283       return false;
08284   } else if (T->isIntegralOrEnumerationType()) {
08285     if (!IntExprEvaluator(Info, Result).Visit(E))
08286       return false;
08287   } else if (T->hasPointerRepresentation()) {
08288     LValue LV;
08289     if (!EvaluatePointer(E, LV, Info))
08290       return false;
08291     LV.moveInto(Result);
08292   } else if (T->isRealFloatingType()) {
08293     llvm::APFloat F(0.0);
08294     if (!EvaluateFloat(E, F, Info))
08295       return false;
08296     Result = APValue(F);
08297   } else if (T->isAnyComplexType()) {
08298     ComplexValue C;
08299     if (!EvaluateComplex(E, C, Info))
08300       return false;
08301     C.moveInto(Result);
08302   } else if (T->isMemberPointerType()) {
08303     MemberPtr P;
08304     if (!EvaluateMemberPointer(E, P, Info))
08305       return false;
08306     P.moveInto(Result);
08307     return true;
08308   } else if (T->isArrayType()) {
08309     LValue LV;
08310     LV.set(E, Info.CurrentCall->Index);
08311     APValue &Value = Info.CurrentCall->createTemporary(E, false);
08312     if (!EvaluateArray(E, LV, Value, Info))
08313       return false;
08314     Result = Value;
08315   } else if (T->isRecordType()) {
08316     LValue LV;
08317     LV.set(E, Info.CurrentCall->Index);
08318     APValue &Value = Info.CurrentCall->createTemporary(E, false);
08319     if (!EvaluateRecord(E, LV, Value, Info))
08320       return false;
08321     Result = Value;
08322   } else if (T->isVoidType()) {
08323     if (!Info.getLangOpts().CPlusPlus11)
08324       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
08325         << E->getType();
08326     if (!EvaluateVoid(E, Info))
08327       return false;
08328   } else if (T->isAtomicType()) {
08329     if (!EvaluateAtomic(E, Result, Info))
08330       return false;
08331   } else if (Info.getLangOpts().CPlusPlus11) {
08332     Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
08333     return false;
08334   } else {
08335     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
08336     return false;
08337   }
08338 
08339   return true;
08340 }
08341 
08342 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
08343 /// cases, the in-place evaluation is essential, since later initializers for
08344 /// an object can indirectly refer to subobjects which were initialized earlier.
08345 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
08346                             const Expr *E, bool AllowNonLiteralTypes) {
08347   assert(!E->isValueDependent());
08348 
08349   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
08350     return false;
08351 
08352   if (E->isRValue()) {
08353     // Evaluate arrays and record types in-place, so that later initializers can
08354     // refer to earlier-initialized members of the object.
08355     if (E->getType()->isArrayType())
08356       return EvaluateArray(E, This, Result, Info);
08357     else if (E->getType()->isRecordType())
08358       return EvaluateRecord(E, This, Result, Info);
08359   }
08360 
08361   // For any other type, in-place evaluation is unimportant.
08362   return Evaluate(Result, Info, E);
08363 }
08364 
08365 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
08366 /// lvalue-to-rvalue cast if it is an lvalue.
08367 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
08368   if (E->getType().isNull())
08369     return false;
08370 
08371   if (!CheckLiteralType(Info, E))
08372     return false;
08373 
08374   if (!::Evaluate(Result, Info, E))
08375     return false;
08376 
08377   if (E->isGLValue()) {
08378     LValue LV;
08379     LV.setFrom(Info.Ctx, Result);
08380     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
08381       return false;
08382   }
08383 
08384   // Check this core constant expression is a constant expression.
08385   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
08386 }
08387 
08388 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
08389                                  const ASTContext &Ctx, bool &IsConst) {
08390   // Fast-path evaluations of integer literals, since we sometimes see files
08391   // containing vast quantities of these.
08392   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
08393     Result.Val = APValue(APSInt(L->getValue(),
08394                                 L->getType()->isUnsignedIntegerType()));
08395     IsConst = true;
08396     return true;
08397   }
08398 
08399   // This case should be rare, but we need to check it before we check on
08400   // the type below.
08401   if (Exp->getType().isNull()) {
08402     IsConst = false;
08403     return true;
08404   }
08405   
08406   // FIXME: Evaluating values of large array and record types can cause
08407   // performance problems. Only do so in C++11 for now.
08408   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
08409                           Exp->getType()->isRecordType()) &&
08410       !Ctx.getLangOpts().CPlusPlus11) {
08411     IsConst = false;
08412     return true;
08413   }
08414   return false;
08415 }
08416 
08417 
08418 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
08419 /// any crazy technique (that has nothing to do with language standards) that
08420 /// we want to.  If this function returns true, it returns the folded constant
08421 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
08422 /// will be applied to the result.
08423 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
08424   bool IsConst;
08425   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
08426     return IsConst;
08427   
08428   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
08429   return ::EvaluateAsRValue(Info, this, Result.Val);
08430 }
08431 
08432 bool Expr::EvaluateAsBooleanCondition(bool &Result,
08433                                       const ASTContext &Ctx) const {
08434   EvalResult Scratch;
08435   return EvaluateAsRValue(Scratch, Ctx) &&
08436          HandleConversionToBool(Scratch.Val, Result);
08437 }
08438 
08439 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
08440                          SideEffectsKind AllowSideEffects) const {
08441   if (!getType()->isIntegralOrEnumerationType())
08442     return false;
08443 
08444   EvalResult ExprResult;
08445   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
08446       (!AllowSideEffects && ExprResult.HasSideEffects))
08447     return false;
08448 
08449   Result = ExprResult.Val.getInt();
08450   return true;
08451 }
08452 
08453 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
08454   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
08455 
08456   LValue LV;
08457   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
08458       !CheckLValueConstantExpression(Info, getExprLoc(),
08459                                      Ctx.getLValueReferenceType(getType()), LV))
08460     return false;
08461 
08462   LV.moveInto(Result.Val);
08463   return true;
08464 }
08465 
08466 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
08467                                  const VarDecl *VD,
08468                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
08469   // FIXME: Evaluating initializers for large array and record types can cause
08470   // performance problems. Only do so in C++11 for now.
08471   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
08472       !Ctx.getLangOpts().CPlusPlus11)
08473     return false;
08474 
08475   Expr::EvalStatus EStatus;
08476   EStatus.Diag = &Notes;
08477 
08478   EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
08479   InitInfo.setEvaluatingDecl(VD, Value);
08480 
08481   LValue LVal;
08482   LVal.set(VD);
08483 
08484   // C++11 [basic.start.init]p2:
08485   //  Variables with static storage duration or thread storage duration shall be
08486   //  zero-initialized before any other initialization takes place.
08487   // This behavior is not present in C.
08488   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
08489       !VD->getType()->isReferenceType()) {
08490     ImplicitValueInitExpr VIE(VD->getType());
08491     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
08492                          /*AllowNonLiteralTypes=*/true))
08493       return false;
08494   }
08495 
08496   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
08497                        /*AllowNonLiteralTypes=*/true) ||
08498       EStatus.HasSideEffects)
08499     return false;
08500 
08501   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
08502                                  Value);
08503 }
08504 
08505 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
08506 /// constant folded, but discard the result.
08507 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
08508   EvalResult Result;
08509   return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
08510 }
08511 
08512 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
08513                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
08514   EvalResult EvalResult;
08515   EvalResult.Diag = Diag;
08516   bool Result = EvaluateAsRValue(EvalResult, Ctx);
08517   (void)Result;
08518   assert(Result && "Could not evaluate expression");
08519   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
08520 
08521   return EvalResult.Val.getInt();
08522 }
08523 
08524 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
08525   bool IsConst;
08526   EvalResult EvalResult;
08527   if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
08528     EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
08529     (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
08530   }
08531 }
08532 
08533 bool Expr::EvalResult::isGlobalLValue() const {
08534   assert(Val.isLValue());
08535   return IsGlobalLValue(Val.getLValueBase());
08536 }
08537 
08538 
08539 /// isIntegerConstantExpr - this recursive routine will test if an expression is
08540 /// an integer constant expression.
08541 
08542 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
08543 /// comma, etc
08544 
08545 // CheckICE - This function does the fundamental ICE checking: the returned
08546 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
08547 // and a (possibly null) SourceLocation indicating the location of the problem.
08548 //
08549 // Note that to reduce code duplication, this helper does no evaluation
08550 // itself; the caller checks whether the expression is evaluatable, and
08551 // in the rare cases where CheckICE actually cares about the evaluated
08552 // value, it calls into Evalute.
08553 
08554 namespace {
08555 
08556 enum ICEKind {
08557   /// This expression is an ICE.
08558   IK_ICE,
08559   /// This expression is not an ICE, but if it isn't evaluated, it's
08560   /// a legal subexpression for an ICE. This return value is used to handle
08561   /// the comma operator in C99 mode, and non-constant subexpressions.
08562   IK_ICEIfUnevaluated,
08563   /// This expression is not an ICE, and is not a legal subexpression for one.
08564   IK_NotICE
08565 };
08566 
08567 struct ICEDiag {
08568   ICEKind Kind;
08569   SourceLocation Loc;
08570 
08571   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
08572 };
08573 
08574 }
08575 
08576 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
08577 
08578 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
08579 
08580 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
08581   Expr::EvalResult EVResult;
08582   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
08583       !EVResult.Val.isInt())
08584     return ICEDiag(IK_NotICE, E->getLocStart());
08585 
08586   return NoDiag();
08587 }
08588 
08589 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
08590   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
08591   if (!E->getType()->isIntegralOrEnumerationType())
08592     return ICEDiag(IK_NotICE, E->getLocStart());
08593 
08594   switch (E->getStmtClass()) {
08595 #define ABSTRACT_STMT(Node)
08596 #define STMT(Node, Base) case Expr::Node##Class:
08597 #define EXPR(Node, Base)
08598 #include "clang/AST/StmtNodes.inc"
08599   case Expr::PredefinedExprClass:
08600   case Expr::FloatingLiteralClass:
08601   case Expr::ImaginaryLiteralClass:
08602   case Expr::StringLiteralClass:
08603   case Expr::ArraySubscriptExprClass:
08604   case Expr::MemberExprClass:
08605   case Expr::CompoundAssignOperatorClass:
08606   case Expr::CompoundLiteralExprClass:
08607   case Expr::ExtVectorElementExprClass:
08608   case Expr::DesignatedInitExprClass:
08609   case Expr::ImplicitValueInitExprClass:
08610   case Expr::ParenListExprClass:
08611   case Expr::VAArgExprClass:
08612   case Expr::AddrLabelExprClass:
08613   case Expr::StmtExprClass:
08614   case Expr::CXXMemberCallExprClass:
08615   case Expr::CUDAKernelCallExprClass:
08616   case Expr::CXXDynamicCastExprClass:
08617   case Expr::CXXTypeidExprClass:
08618   case Expr::CXXUuidofExprClass:
08619   case Expr::MSPropertyRefExprClass:
08620   case Expr::CXXNullPtrLiteralExprClass:
08621   case Expr::UserDefinedLiteralClass:
08622   case Expr::CXXThisExprClass:
08623   case Expr::CXXThrowExprClass:
08624   case Expr::CXXNewExprClass:
08625   case Expr::CXXDeleteExprClass:
08626   case Expr::CXXPseudoDestructorExprClass:
08627   case Expr::UnresolvedLookupExprClass:
08628   case Expr::TypoExprClass:
08629   case Expr::DependentScopeDeclRefExprClass:
08630   case Expr::CXXConstructExprClass:
08631   case Expr::CXXStdInitializerListExprClass:
08632   case Expr::CXXBindTemporaryExprClass:
08633   case Expr::ExprWithCleanupsClass:
08634   case Expr::CXXTemporaryObjectExprClass:
08635   case Expr::CXXUnresolvedConstructExprClass:
08636   case Expr::CXXDependentScopeMemberExprClass:
08637   case Expr::UnresolvedMemberExprClass:
08638   case Expr::ObjCStringLiteralClass:
08639   case Expr::ObjCBoxedExprClass:
08640   case Expr::ObjCArrayLiteralClass:
08641   case Expr::ObjCDictionaryLiteralClass:
08642   case Expr::ObjCEncodeExprClass:
08643   case Expr::ObjCMessageExprClass:
08644   case Expr::ObjCSelectorExprClass:
08645   case Expr::ObjCProtocolExprClass:
08646   case Expr::ObjCIvarRefExprClass:
08647   case Expr::ObjCPropertyRefExprClass:
08648   case Expr::ObjCSubscriptRefExprClass:
08649   case Expr::ObjCIsaExprClass:
08650   case Expr::ShuffleVectorExprClass:
08651   case Expr::ConvertVectorExprClass:
08652   case Expr::BlockExprClass:
08653   case Expr::NoStmtClass:
08654   case Expr::OpaqueValueExprClass:
08655   case Expr::PackExpansionExprClass:
08656   case Expr::SubstNonTypeTemplateParmPackExprClass:
08657   case Expr::FunctionParmPackExprClass:
08658   case Expr::AsTypeExprClass:
08659   case Expr::ObjCIndirectCopyRestoreExprClass:
08660   case Expr::MaterializeTemporaryExprClass:
08661   case Expr::PseudoObjectExprClass:
08662   case Expr::AtomicExprClass:
08663   case Expr::LambdaExprClass:
08664   case Expr::CXXFoldExprClass:
08665     return ICEDiag(IK_NotICE, E->getLocStart());
08666 
08667   case Expr::InitListExprClass: {
08668     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
08669     // form "T x = { a };" is equivalent to "T x = a;".
08670     // Unless we're initializing a reference, T is a scalar as it is known to be
08671     // of integral or enumeration type.
08672     if (E->isRValue())
08673       if (cast<InitListExpr>(E)->getNumInits() == 1)
08674         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
08675     return ICEDiag(IK_NotICE, E->getLocStart());
08676   }
08677 
08678   case Expr::SizeOfPackExprClass:
08679   case Expr::GNUNullExprClass:
08680     // GCC considers the GNU __null value to be an integral constant expression.
08681     return NoDiag();
08682 
08683   case Expr::SubstNonTypeTemplateParmExprClass:
08684     return
08685       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
08686 
08687   case Expr::ParenExprClass:
08688     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
08689   case Expr::GenericSelectionExprClass:
08690     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
08691   case Expr::IntegerLiteralClass:
08692   case Expr::CharacterLiteralClass:
08693   case Expr::ObjCBoolLiteralExprClass:
08694   case Expr::CXXBoolLiteralExprClass:
08695   case Expr::CXXScalarValueInitExprClass:
08696   case Expr::TypeTraitExprClass:
08697   case Expr::ArrayTypeTraitExprClass:
08698   case Expr::ExpressionTraitExprClass:
08699   case Expr::CXXNoexceptExprClass:
08700     return NoDiag();
08701   case Expr::CallExprClass:
08702   case Expr::CXXOperatorCallExprClass: {
08703     // C99 6.6/3 allows function calls within unevaluated subexpressions of
08704     // constant expressions, but they can never be ICEs because an ICE cannot
08705     // contain an operand of (pointer to) function type.
08706     const CallExpr *CE = cast<CallExpr>(E);
08707     if (CE->getBuiltinCallee())
08708       return CheckEvalInICE(E, Ctx);
08709     return ICEDiag(IK_NotICE, E->getLocStart());
08710   }
08711   case Expr::DeclRefExprClass: {
08712     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
08713       return NoDiag();
08714     const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
08715     if (Ctx.getLangOpts().CPlusPlus &&
08716         D && IsConstNonVolatile(D->getType())) {
08717       // Parameter variables are never constants.  Without this check,
08718       // getAnyInitializer() can find a default argument, which leads
08719       // to chaos.
08720       if (isa<ParmVarDecl>(D))
08721         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
08722 
08723       // C++ 7.1.5.1p2
08724       //   A variable of non-volatile const-qualified integral or enumeration
08725       //   type initialized by an ICE can be used in ICEs.
08726       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
08727         if (!Dcl->getType()->isIntegralOrEnumerationType())
08728           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
08729 
08730         const VarDecl *VD;
08731         // Look for a declaration of this variable that has an initializer, and
08732         // check whether it is an ICE.
08733         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
08734           return NoDiag();
08735         else
08736           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
08737       }
08738     }
08739     return ICEDiag(IK_NotICE, E->getLocStart());
08740   }
08741   case Expr::UnaryOperatorClass: {
08742     const UnaryOperator *Exp = cast<UnaryOperator>(E);
08743     switch (Exp->getOpcode()) {
08744     case UO_PostInc:
08745     case UO_PostDec:
08746     case UO_PreInc:
08747     case UO_PreDec:
08748     case UO_AddrOf:
08749     case UO_Deref:
08750       // C99 6.6/3 allows increment and decrement within unevaluated
08751       // subexpressions of constant expressions, but they can never be ICEs
08752       // because an ICE cannot contain an lvalue operand.
08753       return ICEDiag(IK_NotICE, E->getLocStart());
08754     case UO_Extension:
08755     case UO_LNot:
08756     case UO_Plus:
08757     case UO_Minus:
08758     case UO_Not:
08759     case UO_Real:
08760     case UO_Imag:
08761       return CheckICE(Exp->getSubExpr(), Ctx);
08762     }
08763 
08764     // OffsetOf falls through here.
08765   }
08766   case Expr::OffsetOfExprClass: {
08767     // Note that per C99, offsetof must be an ICE. And AFAIK, using
08768     // EvaluateAsRValue matches the proposed gcc behavior for cases like
08769     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
08770     // compliance: we should warn earlier for offsetof expressions with
08771     // array subscripts that aren't ICEs, and if the array subscripts
08772     // are ICEs, the value of the offsetof must be an integer constant.
08773     return CheckEvalInICE(E, Ctx);
08774   }
08775   case Expr::UnaryExprOrTypeTraitExprClass: {
08776     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
08777     if ((Exp->getKind() ==  UETT_SizeOf) &&
08778         Exp->getTypeOfArgument()->isVariableArrayType())
08779       return ICEDiag(IK_NotICE, E->getLocStart());
08780     return NoDiag();
08781   }
08782   case Expr::BinaryOperatorClass: {
08783     const BinaryOperator *Exp = cast<BinaryOperator>(E);
08784     switch (Exp->getOpcode()) {
08785     case BO_PtrMemD:
08786     case BO_PtrMemI:
08787     case BO_Assign:
08788     case BO_MulAssign:
08789     case BO_DivAssign:
08790     case BO_RemAssign:
08791     case BO_AddAssign:
08792     case BO_SubAssign:
08793     case BO_ShlAssign:
08794     case BO_ShrAssign:
08795     case BO_AndAssign:
08796     case BO_XorAssign:
08797     case BO_OrAssign:
08798       // C99 6.6/3 allows assignments within unevaluated subexpressions of
08799       // constant expressions, but they can never be ICEs because an ICE cannot
08800       // contain an lvalue operand.
08801       return ICEDiag(IK_NotICE, E->getLocStart());
08802 
08803     case BO_Mul:
08804     case BO_Div:
08805     case BO_Rem:
08806     case BO_Add:
08807     case BO_Sub:
08808     case BO_Shl:
08809     case BO_Shr:
08810     case BO_LT:
08811     case BO_GT:
08812     case BO_LE:
08813     case BO_GE:
08814     case BO_EQ:
08815     case BO_NE:
08816     case BO_And:
08817     case BO_Xor:
08818     case BO_Or:
08819     case BO_Comma: {
08820       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
08821       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
08822       if (Exp->getOpcode() == BO_Div ||
08823           Exp->getOpcode() == BO_Rem) {
08824         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
08825         // we don't evaluate one.
08826         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
08827           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
08828           if (REval == 0)
08829             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
08830           if (REval.isSigned() && REval.isAllOnesValue()) {
08831             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
08832             if (LEval.isMinSignedValue())
08833               return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
08834           }
08835         }
08836       }
08837       if (Exp->getOpcode() == BO_Comma) {
08838         if (Ctx.getLangOpts().C99) {
08839           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
08840           // if it isn't evaluated.
08841           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
08842             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
08843         } else {
08844           // In both C89 and C++, commas in ICEs are illegal.
08845           return ICEDiag(IK_NotICE, E->getLocStart());
08846         }
08847       }
08848       return Worst(LHSResult, RHSResult);
08849     }
08850     case BO_LAnd:
08851     case BO_LOr: {
08852       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
08853       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
08854       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
08855         // Rare case where the RHS has a comma "side-effect"; we need
08856         // to actually check the condition to see whether the side
08857         // with the comma is evaluated.
08858         if ((Exp->getOpcode() == BO_LAnd) !=
08859             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
08860           return RHSResult;
08861         return NoDiag();
08862       }
08863 
08864       return Worst(LHSResult, RHSResult);
08865     }
08866     }
08867   }
08868   case Expr::ImplicitCastExprClass:
08869   case Expr::CStyleCastExprClass:
08870   case Expr::CXXFunctionalCastExprClass:
08871   case Expr::CXXStaticCastExprClass:
08872   case Expr::CXXReinterpretCastExprClass:
08873   case Expr::CXXConstCastExprClass:
08874   case Expr::ObjCBridgedCastExprClass: {
08875     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
08876     if (isa<ExplicitCastExpr>(E)) {
08877       if (const FloatingLiteral *FL
08878             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
08879         unsigned DestWidth = Ctx.getIntWidth(E->getType());
08880         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
08881         APSInt IgnoredVal(DestWidth, !DestSigned);
08882         bool Ignored;
08883         // If the value does not fit in the destination type, the behavior is
08884         // undefined, so we are not required to treat it as a constant
08885         // expression.
08886         if (FL->getValue().convertToInteger(IgnoredVal,
08887                                             llvm::APFloat::rmTowardZero,
08888                                             &Ignored) & APFloat::opInvalidOp)
08889           return ICEDiag(IK_NotICE, E->getLocStart());
08890         return NoDiag();
08891       }
08892     }
08893     switch (cast<CastExpr>(E)->getCastKind()) {
08894     case CK_LValueToRValue:
08895     case CK_AtomicToNonAtomic:
08896     case CK_NonAtomicToAtomic:
08897     case CK_NoOp:
08898     case CK_IntegralToBoolean:
08899     case CK_IntegralCast:
08900       return CheckICE(SubExpr, Ctx);
08901     default:
08902       return ICEDiag(IK_NotICE, E->getLocStart());
08903     }
08904   }
08905   case Expr::BinaryConditionalOperatorClass: {
08906     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
08907     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
08908     if (CommonResult.Kind == IK_NotICE) return CommonResult;
08909     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
08910     if (FalseResult.Kind == IK_NotICE) return FalseResult;
08911     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
08912     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
08913         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
08914     return FalseResult;
08915   }
08916   case Expr::ConditionalOperatorClass: {
08917     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
08918     // If the condition (ignoring parens) is a __builtin_constant_p call,
08919     // then only the true side is actually considered in an integer constant
08920     // expression, and it is fully evaluated.  This is an important GNU
08921     // extension.  See GCC PR38377 for discussion.
08922     if (const CallExpr *CallCE
08923         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
08924       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
08925         return CheckEvalInICE(E, Ctx);
08926     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
08927     if (CondResult.Kind == IK_NotICE)
08928       return CondResult;
08929 
08930     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
08931     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
08932 
08933     if (TrueResult.Kind == IK_NotICE)
08934       return TrueResult;
08935     if (FalseResult.Kind == IK_NotICE)
08936       return FalseResult;
08937     if (CondResult.Kind == IK_ICEIfUnevaluated)
08938       return CondResult;
08939     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
08940       return NoDiag();
08941     // Rare case where the diagnostics depend on which side is evaluated
08942     // Note that if we get here, CondResult is 0, and at least one of
08943     // TrueResult and FalseResult is non-zero.
08944     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
08945       return FalseResult;
08946     return TrueResult;
08947   }
08948   case Expr::CXXDefaultArgExprClass:
08949     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
08950   case Expr::CXXDefaultInitExprClass:
08951     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
08952   case Expr::ChooseExprClass: {
08953     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
08954   }
08955   }
08956 
08957   llvm_unreachable("Invalid StmtClass!");
08958 }
08959 
08960 /// Evaluate an expression as a C++11 integral constant expression.
08961 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
08962                                                     const Expr *E,
08963                                                     llvm::APSInt *Value,
08964                                                     SourceLocation *Loc) {
08965   if (!E->getType()->isIntegralOrEnumerationType()) {
08966     if (Loc) *Loc = E->getExprLoc();
08967     return false;
08968   }
08969 
08970   APValue Result;
08971   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
08972     return false;
08973 
08974   if (!Result.isInt()) {
08975     if (Loc) *Loc = E->getExprLoc();
08976     return false;
08977   }
08978 
08979   if (Value) *Value = Result.getInt();
08980   return true;
08981 }
08982 
08983 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
08984                                  SourceLocation *Loc) const {
08985   if (Ctx.getLangOpts().CPlusPlus11)
08986     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
08987 
08988   ICEDiag D = CheckICE(this, Ctx);
08989   if (D.Kind != IK_ICE) {
08990     if (Loc) *Loc = D.Loc;
08991     return false;
08992   }
08993   return true;
08994 }
08995 
08996 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
08997                                  SourceLocation *Loc, bool isEvaluated) const {
08998   if (Ctx.getLangOpts().CPlusPlus11)
08999     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
09000 
09001   if (!isIntegerConstantExpr(Ctx, Loc))
09002     return false;
09003   if (!EvaluateAsInt(Value, Ctx))
09004     llvm_unreachable("ICE cannot be evaluated!");
09005   return true;
09006 }
09007 
09008 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
09009   return CheckICE(this, Ctx).Kind == IK_ICE;
09010 }
09011 
09012 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
09013                                SourceLocation *Loc) const {
09014   // We support this checking in C++98 mode in order to diagnose compatibility
09015   // issues.
09016   assert(Ctx.getLangOpts().CPlusPlus);
09017 
09018   // Build evaluation settings.
09019   Expr::EvalStatus Status;
09020   SmallVector<PartialDiagnosticAt, 8> Diags;
09021   Status.Diag = &Diags;
09022   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
09023 
09024   APValue Scratch;
09025   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
09026 
09027   if (!Diags.empty()) {
09028     IsConstExpr = false;
09029     if (Loc) *Loc = Diags[0].first;
09030   } else if (!IsConstExpr) {
09031     // FIXME: This shouldn't happen.
09032     if (Loc) *Loc = getExprLoc();
09033   }
09034 
09035   return IsConstExpr;
09036 }
09037 
09038 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
09039                                     const FunctionDecl *Callee,
09040                                     ArrayRef<const Expr*> Args) const {
09041   Expr::EvalStatus Status;
09042   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
09043 
09044   ArgVector ArgValues(Args.size());
09045   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
09046        I != E; ++I) {
09047     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
09048       // If evaluation fails, throw away the argument entirely.
09049       ArgValues[I - Args.begin()] = APValue();
09050     if (Info.EvalStatus.HasSideEffects)
09051       return false;
09052   }
09053 
09054   // Build fake call to Callee.
09055   CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
09056                        ArgValues.data());
09057   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
09058 }
09059 
09060 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
09061                                    SmallVectorImpl<
09062                                      PartialDiagnosticAt> &Diags) {
09063   // FIXME: It would be useful to check constexpr function templates, but at the
09064   // moment the constant expression evaluator cannot cope with the non-rigorous
09065   // ASTs which we build for dependent expressions.
09066   if (FD->isDependentContext())
09067     return true;
09068 
09069   Expr::EvalStatus Status;
09070   Status.Diag = &Diags;
09071 
09072   EvalInfo Info(FD->getASTContext(), Status,
09073                 EvalInfo::EM_PotentialConstantExpression);
09074 
09075   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
09076   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
09077 
09078   // Fabricate an arbitrary expression on the stack and pretend that it
09079   // is a temporary being used as the 'this' pointer.
09080   LValue This;
09081   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
09082   This.set(&VIE, Info.CurrentCall->Index);
09083 
09084   ArrayRef<const Expr*> Args;
09085 
09086   SourceLocation Loc = FD->getLocation();
09087 
09088   APValue Scratch;
09089   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
09090     // Evaluate the call as a constant initializer, to allow the construction
09091     // of objects of non-literal types.
09092     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
09093     HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
09094   } else
09095     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
09096                        Args, FD->getBody(), Info, Scratch);
09097 
09098   return Diags.empty();
09099 }
09100 
09101 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
09102                                               const FunctionDecl *FD,
09103                                               SmallVectorImpl<
09104                                                 PartialDiagnosticAt> &Diags) {
09105   Expr::EvalStatus Status;
09106   Status.Diag = &Diags;
09107 
09108   EvalInfo Info(FD->getASTContext(), Status,
09109                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
09110 
09111   // Fabricate a call stack frame to give the arguments a plausible cover story.
09112   ArrayRef<const Expr*> Args;
09113   ArgVector ArgValues(0);
09114   bool Success = EvaluateArgs(Args, ArgValues, Info);
09115   (void)Success;
09116   assert(Success &&
09117          "Failed to set up arguments for potential constant evaluation");
09118   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
09119 
09120   APValue ResultScratch;
09121   Evaluate(ResultScratch, Info, E);
09122   return Diags.empty();
09123 }