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