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