ExprConstant.cpp revision 5cfc7d85fe13f144c9a8b264d6de9d38dfebc383
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 rules only, at the moment), or, if folding failed too,
27//    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/CharUnits.h"
39#include "clang/AST/RecordLayout.h"
40#include "clang/AST/StmtVisitor.h"
41#include "clang/AST/TypeLoc.h"
42#include "clang/AST/ASTDiagnostic.h"
43#include "clang/AST/Expr.h"
44#include "clang/Basic/Builtins.h"
45#include "clang/Basic/TargetInfo.h"
46#include "llvm/ADT/SmallString.h"
47#include "llvm/Support/SaveAndRestore.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    return B.get<const Expr*>()->getType();
67  }
68
69  /// Get an LValue path entry, which is known to not be an array index, as a
70  /// field or base class.
71  static
72  APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
73    APValue::BaseOrMemberType Value;
74    Value.setFromOpaqueValue(E.BaseOrMember);
75    return Value;
76  }
77
78  /// Get an LValue path entry, which is known to not be an array index, as a
79  /// field declaration.
80  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
81    return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
82  }
83  /// Get an LValue path entry, which is known to not be an array index, as a
84  /// base class declaration.
85  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
86    return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
87  }
88  /// Determine whether this LValue path entry for a base class names a virtual
89  /// base class.
90  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
91    return getAsBaseOrMember(E).getInt();
92  }
93
94  /// Find the path length and type of the most-derived subobject in the given
95  /// path, and find the size of the containing array, if any.
96  static
97  unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98                                    ArrayRef<APValue::LValuePathEntry> Path,
99                                    uint64_t &ArraySize, QualType &Type) {
100    unsigned MostDerivedLength = 0;
101    Type = Base;
102    for (unsigned I = 0, N = Path.size(); I != N; ++I) {
103      if (Type->isArrayType()) {
104        const ConstantArrayType *CAT =
105          cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106        Type = CAT->getElementType();
107        ArraySize = CAT->getSize().getZExtValue();
108        MostDerivedLength = I + 1;
109      } else if (Type->isAnyComplexType()) {
110        const ComplexType *CT = Type->castAs<ComplexType>();
111        Type = CT->getElementType();
112        ArraySize = 2;
113        MostDerivedLength = I + 1;
114      } else if (const FieldDecl *FD = getAsField(Path[I])) {
115        Type = FD->getType();
116        ArraySize = 0;
117        MostDerivedLength = I + 1;
118      } else {
119        // Path[I] describes a base class.
120        ArraySize = 0;
121      }
122    }
123    return MostDerivedLength;
124  }
125
126  // The order of this enum is important for diagnostics.
127  enum CheckSubobjectKind {
128    CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
129    CSK_This, CSK_Real, CSK_Imag
130  };
131
132  /// A path from a glvalue to a subobject of that glvalue.
133  struct SubobjectDesignator {
134    /// True if the subobject was named in a manner not supported by C++11. Such
135    /// lvalues can still be folded, but they are not core constant expressions
136    /// and we cannot perform lvalue-to-rvalue conversions on them.
137    bool Invalid : 1;
138
139    /// Is this a pointer one past the end of an object?
140    bool IsOnePastTheEnd : 1;
141
142    /// The length of the path to the most-derived object of which this is a
143    /// subobject.
144    unsigned MostDerivedPathLength : 30;
145
146    /// The size of the array of which the most-derived object is an element, or
147    /// 0 if the most-derived object is not an array element.
148    uint64_t MostDerivedArraySize;
149
150    /// The type of the most derived object referred to by this address.
151    QualType MostDerivedType;
152
153    typedef APValue::LValuePathEntry PathEntry;
154
155    /// The entries on the path from the glvalue to the designated subobject.
156    SmallVector<PathEntry, 8> Entries;
157
158    SubobjectDesignator() : Invalid(true) {}
159
160    explicit SubobjectDesignator(QualType T)
161      : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162        MostDerivedArraySize(0), MostDerivedType(T) {}
163
164    SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165      : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166        MostDerivedPathLength(0), MostDerivedArraySize(0) {
167      if (!Invalid) {
168        IsOnePastTheEnd = V.isLValueOnePastTheEnd();
169        ArrayRef<PathEntry> VEntries = V.getLValuePath();
170        Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171        if (V.getLValueBase())
172          MostDerivedPathLength =
173              findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174                                       V.getLValuePath(), MostDerivedArraySize,
175                                       MostDerivedType);
176      }
177    }
178
179    void setInvalid() {
180      Invalid = true;
181      Entries.clear();
182    }
183
184    /// Determine whether this is a one-past-the-end pointer.
185    bool isOnePastTheEnd() const {
186      if (IsOnePastTheEnd)
187        return true;
188      if (MostDerivedArraySize &&
189          Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190        return true;
191      return false;
192    }
193
194    /// Check that this refers to a valid subobject.
195    bool isValidSubobject() const {
196      if (Invalid)
197        return false;
198      return !isOnePastTheEnd();
199    }
200    /// Check that this refers to a valid subobject, and if not, produce a
201    /// relevant diagnostic and set the designator as invalid.
202    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204    /// Update this designator to refer to the first element within this array.
205    void addArrayUnchecked(const ConstantArrayType *CAT) {
206      PathEntry Entry;
207      Entry.ArrayIndex = 0;
208      Entries.push_back(Entry);
209
210      // This is a most-derived object.
211      MostDerivedType = CAT->getElementType();
212      MostDerivedArraySize = CAT->getSize().getZExtValue();
213      MostDerivedPathLength = Entries.size();
214    }
215    /// Update this designator to refer to the given base or member of this
216    /// object.
217    void addDeclUnchecked(const Decl *D, bool Virtual = false) {
218      PathEntry Entry;
219      APValue::BaseOrMemberType Value(D, Virtual);
220      Entry.BaseOrMember = Value.getOpaqueValue();
221      Entries.push_back(Entry);
222
223      // If this isn't a base class, it's a new most-derived object.
224      if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225        MostDerivedType = FD->getType();
226        MostDerivedArraySize = 0;
227        MostDerivedPathLength = Entries.size();
228      }
229    }
230    /// Update this designator to refer to the given complex component.
231    void addComplexUnchecked(QualType EltTy, bool Imag) {
232      PathEntry Entry;
233      Entry.ArrayIndex = Imag;
234      Entries.push_back(Entry);
235
236      // This is technically a most-derived object, though in practice this
237      // is unlikely to matter.
238      MostDerivedType = EltTy;
239      MostDerivedArraySize = 2;
240      MostDerivedPathLength = Entries.size();
241    }
242    void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
243    /// Add N to the address of this subobject.
244    void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
245      if (Invalid) return;
246      if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
247        Entries.back().ArrayIndex += N;
248        if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249          diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250          setInvalid();
251        }
252        return;
253      }
254      // [expr.add]p4: For the purposes of these operators, a pointer to a
255      // nonarray object behaves the same as a pointer to the first element of
256      // an array of length one with the type of the object as its element type.
257      if (IsOnePastTheEnd && N == (uint64_t)-1)
258        IsOnePastTheEnd = false;
259      else if (!IsOnePastTheEnd && N == 1)
260        IsOnePastTheEnd = true;
261      else if (N != 0) {
262        diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
263        setInvalid();
264      }
265    }
266  };
267
268  /// A stack frame in the constexpr call stack.
269  struct CallStackFrame {
270    EvalInfo &Info;
271
272    /// Parent - The caller of this stack frame.
273    CallStackFrame *Caller;
274
275    /// CallLoc - The location of the call expression for this call.
276    SourceLocation CallLoc;
277
278    /// Callee - The function which was called.
279    const FunctionDecl *Callee;
280
281    /// Index - The call index of this call.
282    unsigned Index;
283
284    /// This - The binding for the this pointer in this call, if any.
285    const LValue *This;
286
287    /// ParmBindings - Parameter bindings for this function call, indexed by
288    /// parameters' function scope indices.
289    const APValue *Arguments;
290
291    typedef llvm::DenseMap<const Expr*, APValue> MapTy;
292    typedef MapTy::const_iterator temp_iterator;
293    /// Temporaries - Temporary lvalues materialized within this stack frame.
294    MapTy Temporaries;
295
296    CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
297                   const FunctionDecl *Callee, const LValue *This,
298                   const APValue *Arguments);
299    ~CallStackFrame();
300  };
301
302  /// A partial diagnostic which we might know in advance that we are not going
303  /// to emit.
304  class OptionalDiagnostic {
305    PartialDiagnostic *Diag;
306
307  public:
308    explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
309
310    template<typename T>
311    OptionalDiagnostic &operator<<(const T &v) {
312      if (Diag)
313        *Diag << v;
314      return *this;
315    }
316
317    OptionalDiagnostic &operator<<(const APSInt &I) {
318      if (Diag) {
319        llvm::SmallVector<char, 32> Buffer;
320        I.toString(Buffer);
321        *Diag << StringRef(Buffer.data(), Buffer.size());
322      }
323      return *this;
324    }
325
326    OptionalDiagnostic &operator<<(const APFloat &F) {
327      if (Diag) {
328        llvm::SmallVector<char, 32> Buffer;
329        F.toString(Buffer);
330        *Diag << StringRef(Buffer.data(), Buffer.size());
331      }
332      return *this;
333    }
334  };
335
336  /// EvalInfo - This is a private struct used by the evaluator to capture
337  /// information about a subexpression as it is folded.  It retains information
338  /// about the AST context, but also maintains information about the folded
339  /// expression.
340  ///
341  /// If an expression could be evaluated, it is still possible it is not a C
342  /// "integer constant expression" or constant expression.  If not, this struct
343  /// captures information about how and why not.
344  ///
345  /// One bit of information passed *into* the request for constant folding
346  /// indicates whether the subexpression is "evaluated" or not according to C
347  /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
348  /// evaluate the expression regardless of what the RHS is, but C only allows
349  /// certain things in certain situations.
350  struct EvalInfo {
351    ASTContext &Ctx;
352
353    /// EvalStatus - Contains information about the evaluation.
354    Expr::EvalStatus &EvalStatus;
355
356    /// CurrentCall - The top of the constexpr call stack.
357    CallStackFrame *CurrentCall;
358
359    /// CallStackDepth - The number of calls in the call stack right now.
360    unsigned CallStackDepth;
361
362    /// NextCallIndex - The next call index to assign.
363    unsigned NextCallIndex;
364
365    typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
366    /// OpaqueValues - Values used as the common expression in a
367    /// BinaryConditionalOperator.
368    MapTy OpaqueValues;
369
370    /// BottomFrame - The frame in which evaluation started. This must be
371    /// initialized after CurrentCall and CallStackDepth.
372    CallStackFrame BottomFrame;
373
374    /// EvaluatingDecl - This is the declaration whose initializer is being
375    /// evaluated, if any.
376    const VarDecl *EvaluatingDecl;
377
378    /// EvaluatingDeclValue - This is the value being constructed for the
379    /// declaration whose initializer is being evaluated, if any.
380    APValue *EvaluatingDeclValue;
381
382    /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
383    /// notes attached to it will also be stored, otherwise they will not be.
384    bool HasActiveDiagnostic;
385
386    /// CheckingPotentialConstantExpression - Are we checking whether the
387    /// expression is a potential constant expression? If so, some diagnostics
388    /// are suppressed.
389    bool CheckingPotentialConstantExpression;
390
391    /// \brief Stack depth of IntExprEvaluator.
392    /// We check this against a maximum value to avoid stack overflow, see
393    /// test case in test/Sema/many-logical-ops.c.
394    // FIXME: This is a hack; handle properly unlimited logical ops.
395    unsigned IntExprEvaluatorDepth;
396
397    EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
398      : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
399        CallStackDepth(0), NextCallIndex(1),
400        BottomFrame(*this, SourceLocation(), 0, 0, 0),
401        EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
402        CheckingPotentialConstantExpression(false), IntExprEvaluatorDepth(0) {}
403
404    const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
405      MapTy::const_iterator i = OpaqueValues.find(e);
406      if (i == OpaqueValues.end()) return 0;
407      return &i->second;
408    }
409
410    void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
411      EvaluatingDecl = VD;
412      EvaluatingDeclValue = &Value;
413    }
414
415    const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
416
417    bool CheckCallLimit(SourceLocation Loc) {
418      // Don't perform any constexpr calls (other than the call we're checking)
419      // when checking a potential constant expression.
420      if (CheckingPotentialConstantExpression && CallStackDepth > 1)
421        return false;
422      if (NextCallIndex == 0) {
423        // NextCallIndex has wrapped around.
424        Diag(Loc, diag::note_constexpr_call_limit_exceeded);
425        return false;
426      }
427      if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
428        return true;
429      Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
430        << getLangOpts().ConstexprCallDepth;
431      return false;
432    }
433
434    CallStackFrame *getCallFrame(unsigned CallIndex) {
435      assert(CallIndex && "no call index in getCallFrame");
436      // We will eventually hit BottomFrame, which has Index 1, so Frame can't
437      // be null in this loop.
438      CallStackFrame *Frame = CurrentCall;
439      while (Frame->Index > CallIndex)
440        Frame = Frame->Caller;
441      return (Frame->Index == CallIndex) ? Frame : 0;
442    }
443
444  private:
445    /// Add a diagnostic to the diagnostics list.
446    PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
447      PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
448      EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
449      return EvalStatus.Diag->back().second;
450    }
451
452    /// Add notes containing a call stack to the current point of evaluation.
453    void addCallStack(unsigned Limit);
454
455  public:
456    /// Diagnose that the evaluation cannot be folded.
457    OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
458                              = diag::note_invalid_subexpr_in_const_expr,
459                            unsigned ExtraNotes = 0) {
460      // If we have a prior diagnostic, it will be noting that the expression
461      // isn't a constant expression. This diagnostic is more important.
462      // FIXME: We might want to show both diagnostics to the user.
463      if (EvalStatus.Diag) {
464        unsigned CallStackNotes = CallStackDepth - 1;
465        unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
466        if (Limit)
467          CallStackNotes = std::min(CallStackNotes, Limit + 1);
468        if (CheckingPotentialConstantExpression)
469          CallStackNotes = 0;
470
471        HasActiveDiagnostic = true;
472        EvalStatus.Diag->clear();
473        EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
474        addDiag(Loc, DiagId);
475        if (!CheckingPotentialConstantExpression)
476          addCallStack(Limit);
477        return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
478      }
479      HasActiveDiagnostic = false;
480      return OptionalDiagnostic();
481    }
482
483    OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
484                              = diag::note_invalid_subexpr_in_const_expr,
485                            unsigned ExtraNotes = 0) {
486      if (EvalStatus.Diag)
487        return Diag(E->getExprLoc(), DiagId, ExtraNotes);
488      HasActiveDiagnostic = false;
489      return OptionalDiagnostic();
490    }
491
492    /// Diagnose that the evaluation does not produce a C++11 core constant
493    /// expression.
494    template<typename LocArg>
495    OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
496                                 = diag::note_invalid_subexpr_in_const_expr,
497                               unsigned ExtraNotes = 0) {
498      // Don't override a previous diagnostic.
499      if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
500        HasActiveDiagnostic = false;
501        return OptionalDiagnostic();
502      }
503      return Diag(Loc, DiagId, ExtraNotes);
504    }
505
506    /// Add a note to a prior diagnostic.
507    OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
508      if (!HasActiveDiagnostic)
509        return OptionalDiagnostic();
510      return OptionalDiagnostic(&addDiag(Loc, DiagId));
511    }
512
513    /// Add a stack of notes to a prior diagnostic.
514    void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
515      if (HasActiveDiagnostic) {
516        EvalStatus.Diag->insert(EvalStatus.Diag->end(),
517                                Diags.begin(), Diags.end());
518      }
519    }
520
521    /// Should we continue evaluation as much as possible after encountering a
522    /// construct which can't be folded?
523    bool keepEvaluatingAfterFailure() {
524      return CheckingPotentialConstantExpression &&
525             EvalStatus.Diag && EvalStatus.Diag->empty();
526    }
527  };
528
529  /// Object used to treat all foldable expressions as constant expressions.
530  struct FoldConstant {
531    bool Enabled;
532
533    explicit FoldConstant(EvalInfo &Info)
534      : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
535                !Info.EvalStatus.HasSideEffects) {
536    }
537    // Treat the value we've computed since this object was created as constant.
538    void Fold(EvalInfo &Info) {
539      if (Enabled && !Info.EvalStatus.Diag->empty() &&
540          !Info.EvalStatus.HasSideEffects)
541        Info.EvalStatus.Diag->clear();
542    }
543  };
544
545  /// RAII object used to suppress diagnostics and side-effects from a
546  /// speculative evaluation.
547  class SpeculativeEvaluationRAII {
548    EvalInfo &Info;
549    Expr::EvalStatus Old;
550
551  public:
552    SpeculativeEvaluationRAII(EvalInfo &Info,
553                              llvm::SmallVectorImpl<PartialDiagnosticAt>
554                                *NewDiag = 0)
555      : Info(Info), Old(Info.EvalStatus) {
556      Info.EvalStatus.Diag = NewDiag;
557    }
558    ~SpeculativeEvaluationRAII() {
559      Info.EvalStatus = Old;
560    }
561  };
562}
563
564bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
565                                         CheckSubobjectKind CSK) {
566  if (Invalid)
567    return false;
568  if (isOnePastTheEnd()) {
569    Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
570      << CSK;
571    setInvalid();
572    return false;
573  }
574  return true;
575}
576
577void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
578                                                    const Expr *E, uint64_t N) {
579  if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
580    Info.CCEDiag(E, diag::note_constexpr_array_index)
581      << static_cast<int>(N) << /*array*/ 0
582      << static_cast<unsigned>(MostDerivedArraySize);
583  else
584    Info.CCEDiag(E, diag::note_constexpr_array_index)
585      << static_cast<int>(N) << /*non-array*/ 1;
586  setInvalid();
587}
588
589CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
590                               const FunctionDecl *Callee, const LValue *This,
591                               const APValue *Arguments)
592    : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
593      Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
594  Info.CurrentCall = this;
595  ++Info.CallStackDepth;
596}
597
598CallStackFrame::~CallStackFrame() {
599  assert(Info.CurrentCall == this && "calls retired out of order");
600  --Info.CallStackDepth;
601  Info.CurrentCall = Caller;
602}
603
604/// Produce a string describing the given constexpr call.
605static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
606  unsigned ArgIndex = 0;
607  bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
608                      !isa<CXXConstructorDecl>(Frame->Callee) &&
609                      cast<CXXMethodDecl>(Frame->Callee)->isInstance();
610
611  if (!IsMemberCall)
612    Out << *Frame->Callee << '(';
613
614  for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
615       E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
616    if (ArgIndex > (unsigned)IsMemberCall)
617      Out << ", ";
618
619    const ParmVarDecl *Param = *I;
620    const APValue &Arg = Frame->Arguments[ArgIndex];
621    Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
622
623    if (ArgIndex == 0 && IsMemberCall)
624      Out << "->" << *Frame->Callee << '(';
625  }
626
627  Out << ')';
628}
629
630void EvalInfo::addCallStack(unsigned Limit) {
631  // Determine which calls to skip, if any.
632  unsigned ActiveCalls = CallStackDepth - 1;
633  unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
634  if (Limit && Limit < ActiveCalls) {
635    SkipStart = Limit / 2 + Limit % 2;
636    SkipEnd = ActiveCalls - Limit / 2;
637  }
638
639  // Walk the call stack and add the diagnostics.
640  unsigned CallIdx = 0;
641  for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
642       Frame = Frame->Caller, ++CallIdx) {
643    // Skip this call?
644    if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
645      if (CallIdx == SkipStart) {
646        // Note that we're skipping calls.
647        addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
648          << unsigned(ActiveCalls - Limit);
649      }
650      continue;
651    }
652
653    llvm::SmallVector<char, 128> Buffer;
654    llvm::raw_svector_ostream Out(Buffer);
655    describeCall(Frame, Out);
656    addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
657  }
658}
659
660namespace {
661  struct ComplexValue {
662  private:
663    bool IsInt;
664
665  public:
666    APSInt IntReal, IntImag;
667    APFloat FloatReal, FloatImag;
668
669    ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
670
671    void makeComplexFloat() { IsInt = false; }
672    bool isComplexFloat() const { return !IsInt; }
673    APFloat &getComplexFloatReal() { return FloatReal; }
674    APFloat &getComplexFloatImag() { return FloatImag; }
675
676    void makeComplexInt() { IsInt = true; }
677    bool isComplexInt() const { return IsInt; }
678    APSInt &getComplexIntReal() { return IntReal; }
679    APSInt &getComplexIntImag() { return IntImag; }
680
681    void moveInto(APValue &v) const {
682      if (isComplexFloat())
683        v = APValue(FloatReal, FloatImag);
684      else
685        v = APValue(IntReal, IntImag);
686    }
687    void setFrom(const APValue &v) {
688      assert(v.isComplexFloat() || v.isComplexInt());
689      if (v.isComplexFloat()) {
690        makeComplexFloat();
691        FloatReal = v.getComplexFloatReal();
692        FloatImag = v.getComplexFloatImag();
693      } else {
694        makeComplexInt();
695        IntReal = v.getComplexIntReal();
696        IntImag = v.getComplexIntImag();
697      }
698    }
699  };
700
701  struct LValue {
702    APValue::LValueBase Base;
703    CharUnits Offset;
704    unsigned CallIndex;
705    SubobjectDesignator Designator;
706
707    const APValue::LValueBase getLValueBase() const { return Base; }
708    CharUnits &getLValueOffset() { return Offset; }
709    const CharUnits &getLValueOffset() const { return Offset; }
710    unsigned getLValueCallIndex() const { return CallIndex; }
711    SubobjectDesignator &getLValueDesignator() { return Designator; }
712    const SubobjectDesignator &getLValueDesignator() const { return Designator;}
713
714    void moveInto(APValue &V) const {
715      if (Designator.Invalid)
716        V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
717      else
718        V = APValue(Base, Offset, Designator.Entries,
719                    Designator.IsOnePastTheEnd, CallIndex);
720    }
721    void setFrom(ASTContext &Ctx, const APValue &V) {
722      assert(V.isLValue());
723      Base = V.getLValueBase();
724      Offset = V.getLValueOffset();
725      CallIndex = V.getLValueCallIndex();
726      Designator = SubobjectDesignator(Ctx, V);
727    }
728
729    void set(APValue::LValueBase B, unsigned I = 0) {
730      Base = B;
731      Offset = CharUnits::Zero();
732      CallIndex = I;
733      Designator = SubobjectDesignator(getType(B));
734    }
735
736    // Check that this LValue is not based on a null pointer. If it is, produce
737    // a diagnostic and mark the designator as invalid.
738    bool checkNullPointer(EvalInfo &Info, const Expr *E,
739                          CheckSubobjectKind CSK) {
740      if (Designator.Invalid)
741        return false;
742      if (!Base) {
743        Info.CCEDiag(E, diag::note_constexpr_null_subobject)
744          << CSK;
745        Designator.setInvalid();
746        return false;
747      }
748      return true;
749    }
750
751    // Check this LValue refers to an object. If not, set the designator to be
752    // invalid and emit a diagnostic.
753    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
754      // Outside C++11, do not build a designator referring to a subobject of
755      // any object: we won't use such a designator for anything.
756      if (!Info.getLangOpts().CPlusPlus0x)
757        Designator.setInvalid();
758      return checkNullPointer(Info, E, CSK) &&
759             Designator.checkSubobject(Info, E, CSK);
760    }
761
762    void addDecl(EvalInfo &Info, const Expr *E,
763                 const Decl *D, bool Virtual = false) {
764      if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
765        Designator.addDeclUnchecked(D, Virtual);
766    }
767    void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
768      if (checkSubobject(Info, E, CSK_ArrayToPointer))
769        Designator.addArrayUnchecked(CAT);
770    }
771    void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
772      if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
773        Designator.addComplexUnchecked(EltTy, Imag);
774    }
775    void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
776      if (checkNullPointer(Info, E, CSK_ArrayIndex))
777        Designator.adjustIndex(Info, E, N);
778    }
779  };
780
781  struct MemberPtr {
782    MemberPtr() {}
783    explicit MemberPtr(const ValueDecl *Decl) :
784      DeclAndIsDerivedMember(Decl, false), Path() {}
785
786    /// The member or (direct or indirect) field referred to by this member
787    /// pointer, or 0 if this is a null member pointer.
788    const ValueDecl *getDecl() const {
789      return DeclAndIsDerivedMember.getPointer();
790    }
791    /// Is this actually a member of some type derived from the relevant class?
792    bool isDerivedMember() const {
793      return DeclAndIsDerivedMember.getInt();
794    }
795    /// Get the class which the declaration actually lives in.
796    const CXXRecordDecl *getContainingRecord() const {
797      return cast<CXXRecordDecl>(
798          DeclAndIsDerivedMember.getPointer()->getDeclContext());
799    }
800
801    void moveInto(APValue &V) const {
802      V = APValue(getDecl(), isDerivedMember(), Path);
803    }
804    void setFrom(const APValue &V) {
805      assert(V.isMemberPointer());
806      DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
807      DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
808      Path.clear();
809      ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
810      Path.insert(Path.end(), P.begin(), P.end());
811    }
812
813    /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
814    /// whether the member is a member of some class derived from the class type
815    /// of the member pointer.
816    llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
817    /// Path - The path of base/derived classes from the member declaration's
818    /// class (exclusive) to the class type of the member pointer (inclusive).
819    SmallVector<const CXXRecordDecl*, 4> Path;
820
821    /// Perform a cast towards the class of the Decl (either up or down the
822    /// hierarchy).
823    bool castBack(const CXXRecordDecl *Class) {
824      assert(!Path.empty());
825      const CXXRecordDecl *Expected;
826      if (Path.size() >= 2)
827        Expected = Path[Path.size() - 2];
828      else
829        Expected = getContainingRecord();
830      if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
831        // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
832        // if B does not contain the original member and is not a base or
833        // derived class of the class containing the original member, the result
834        // of the cast is undefined.
835        // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
836        // (D::*). We consider that to be a language defect.
837        return false;
838      }
839      Path.pop_back();
840      return true;
841    }
842    /// Perform a base-to-derived member pointer cast.
843    bool castToDerived(const CXXRecordDecl *Derived) {
844      if (!getDecl())
845        return true;
846      if (!isDerivedMember()) {
847        Path.push_back(Derived);
848        return true;
849      }
850      if (!castBack(Derived))
851        return false;
852      if (Path.empty())
853        DeclAndIsDerivedMember.setInt(false);
854      return true;
855    }
856    /// Perform a derived-to-base member pointer cast.
857    bool castToBase(const CXXRecordDecl *Base) {
858      if (!getDecl())
859        return true;
860      if (Path.empty())
861        DeclAndIsDerivedMember.setInt(true);
862      if (isDerivedMember()) {
863        Path.push_back(Base);
864        return true;
865      }
866      return castBack(Base);
867    }
868  };
869
870  /// Compare two member pointers, which are assumed to be of the same type.
871  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
872    if (!LHS.getDecl() || !RHS.getDecl())
873      return !LHS.getDecl() && !RHS.getDecl();
874    if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
875      return false;
876    return LHS.Path == RHS.Path;
877  }
878
879  /// Kinds of constant expression checking, for diagnostics.
880  enum CheckConstantExpressionKind {
881    CCEK_Constant,    ///< A normal constant.
882    CCEK_ReturnValue, ///< A constexpr function return value.
883    CCEK_MemberInit   ///< A constexpr constructor mem-initializer.
884  };
885}
886
887static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
888static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
889                            const LValue &This, const Expr *E,
890                            CheckConstantExpressionKind CCEK = CCEK_Constant,
891                            bool AllowNonLiteralTypes = false);
892static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
893static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
894static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
895                                  EvalInfo &Info);
896static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
897static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
898static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
899                                    EvalInfo &Info);
900static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
901static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
902
903//===----------------------------------------------------------------------===//
904// Misc utilities
905//===----------------------------------------------------------------------===//
906
907/// Should this call expression be treated as a string literal?
908static bool IsStringLiteralCall(const CallExpr *E) {
909  unsigned Builtin = E->isBuiltinCall();
910  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
911          Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
912}
913
914static bool IsGlobalLValue(APValue::LValueBase B) {
915  // C++11 [expr.const]p3 An address constant expression is a prvalue core
916  // constant expression of pointer type that evaluates to...
917
918  // ... a null pointer value, or a prvalue core constant expression of type
919  // std::nullptr_t.
920  if (!B) return true;
921
922  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
923    // ... the address of an object with static storage duration,
924    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
925      return VD->hasGlobalStorage();
926    // ... the address of a function,
927    return isa<FunctionDecl>(D);
928  }
929
930  const Expr *E = B.get<const Expr*>();
931  switch (E->getStmtClass()) {
932  default:
933    return false;
934  case Expr::CompoundLiteralExprClass: {
935    const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
936    return CLE->isFileScope() && CLE->isLValue();
937  }
938  // A string literal has static storage duration.
939  case Expr::StringLiteralClass:
940  case Expr::PredefinedExprClass:
941  case Expr::ObjCStringLiteralClass:
942  case Expr::ObjCEncodeExprClass:
943  case Expr::CXXTypeidExprClass:
944    return true;
945  case Expr::CallExprClass:
946    return IsStringLiteralCall(cast<CallExpr>(E));
947  // For GCC compatibility, &&label has static storage duration.
948  case Expr::AddrLabelExprClass:
949    return true;
950  // A Block literal expression may be used as the initialization value for
951  // Block variables at global or local static scope.
952  case Expr::BlockExprClass:
953    return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
954  case Expr::ImplicitValueInitExprClass:
955    // FIXME:
956    // We can never form an lvalue with an implicit value initialization as its
957    // base through expression evaluation, so these only appear in one case: the
958    // implicit variable declaration we invent when checking whether a constexpr
959    // constructor can produce a constant expression. We must assume that such
960    // an expression might be a global lvalue.
961    return true;
962  }
963}
964
965static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
966  assert(Base && "no location for a null lvalue");
967  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
968  if (VD)
969    Info.Note(VD->getLocation(), diag::note_declared_at);
970  else
971    Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
972              diag::note_constexpr_temporary_here);
973}
974
975/// Check that this reference or pointer core constant expression is a valid
976/// value for an address or reference constant expression. Return true if we
977/// can fold this expression, whether or not it's a constant expression.
978static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
979                                          QualType Type, const LValue &LVal) {
980  bool IsReferenceType = Type->isReferenceType();
981
982  APValue::LValueBase Base = LVal.getLValueBase();
983  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
984
985  // Check that the object is a global. Note that the fake 'this' object we
986  // manufacture when checking potential constant expressions is conservatively
987  // assumed to be global here.
988  if (!IsGlobalLValue(Base)) {
989    if (Info.getLangOpts().CPlusPlus0x) {
990      const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
991      Info.Diag(Loc, diag::note_constexpr_non_global, 1)
992        << IsReferenceType << !Designator.Entries.empty()
993        << !!VD << VD;
994      NoteLValueLocation(Info, Base);
995    } else {
996      Info.Diag(Loc);
997    }
998    // Don't allow references to temporaries to escape.
999    return false;
1000  }
1001  assert((Info.CheckingPotentialConstantExpression ||
1002          LVal.getLValueCallIndex() == 0) &&
1003         "have call index for global lvalue");
1004
1005  // Allow address constant expressions to be past-the-end pointers. This is
1006  // an extension: the standard requires them to point to an object.
1007  if (!IsReferenceType)
1008    return true;
1009
1010  // A reference constant expression must refer to an object.
1011  if (!Base) {
1012    // FIXME: diagnostic
1013    Info.CCEDiag(Loc);
1014    return true;
1015  }
1016
1017  // Does this refer one past the end of some object?
1018  if (Designator.isOnePastTheEnd()) {
1019    const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1020    Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1021      << !Designator.Entries.empty() << !!VD << VD;
1022    NoteLValueLocation(Info, Base);
1023  }
1024
1025  return true;
1026}
1027
1028/// Check that this core constant expression is of literal type, and if not,
1029/// produce an appropriate diagnostic.
1030static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1031  if (!E->isRValue() || E->getType()->isLiteralType())
1032    return true;
1033
1034  // Prvalue constant expressions must be of literal types.
1035  if (Info.getLangOpts().CPlusPlus0x)
1036    Info.Diag(E, diag::note_constexpr_nonliteral)
1037      << E->getType();
1038  else
1039    Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1040  return false;
1041}
1042
1043/// Check that this core constant expression value is a valid value for a
1044/// constant expression. If not, report an appropriate diagnostic. Does not
1045/// check that the expression is of literal type.
1046static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1047                                    QualType Type, const APValue &Value) {
1048  // Core issue 1454: For a literal constant expression of array or class type,
1049  // each subobject of its value shall have been initialized by a constant
1050  // expression.
1051  if (Value.isArray()) {
1052    QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1053    for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1054      if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1055                                   Value.getArrayInitializedElt(I)))
1056        return false;
1057    }
1058    if (!Value.hasArrayFiller())
1059      return true;
1060    return CheckConstantExpression(Info, DiagLoc, EltTy,
1061                                   Value.getArrayFiller());
1062  }
1063  if (Value.isUnion() && Value.getUnionField()) {
1064    return CheckConstantExpression(Info, DiagLoc,
1065                                   Value.getUnionField()->getType(),
1066                                   Value.getUnionValue());
1067  }
1068  if (Value.isStruct()) {
1069    RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1070    if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1071      unsigned BaseIndex = 0;
1072      for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1073             End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1074        if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1075                                     Value.getStructBase(BaseIndex)))
1076          return false;
1077      }
1078    }
1079    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1080         I != E; ++I) {
1081      if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1082                                   Value.getStructField((*I)->getFieldIndex())))
1083        return false;
1084    }
1085  }
1086
1087  if (Value.isLValue()) {
1088    LValue LVal;
1089    LVal.setFrom(Info.Ctx, Value);
1090    return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1091  }
1092
1093  // Everything else is fine.
1094  return true;
1095}
1096
1097const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1098  return LVal.Base.dyn_cast<const ValueDecl*>();
1099}
1100
1101static bool IsLiteralLValue(const LValue &Value) {
1102  return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
1103}
1104
1105static bool IsWeakLValue(const LValue &Value) {
1106  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1107  return Decl && Decl->isWeak();
1108}
1109
1110static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1111  // A null base expression indicates a null pointer.  These are always
1112  // evaluatable, and they are false unless the offset is zero.
1113  if (!Value.getLValueBase()) {
1114    Result = !Value.getLValueOffset().isZero();
1115    return true;
1116  }
1117
1118  // We have a non-null base.  These are generally known to be true, but if it's
1119  // a weak declaration it can be null at runtime.
1120  Result = true;
1121  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1122  return !Decl || !Decl->isWeak();
1123}
1124
1125static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1126  switch (Val.getKind()) {
1127  case APValue::Uninitialized:
1128    return false;
1129  case APValue::Int:
1130    Result = Val.getInt().getBoolValue();
1131    return true;
1132  case APValue::Float:
1133    Result = !Val.getFloat().isZero();
1134    return true;
1135  case APValue::ComplexInt:
1136    Result = Val.getComplexIntReal().getBoolValue() ||
1137             Val.getComplexIntImag().getBoolValue();
1138    return true;
1139  case APValue::ComplexFloat:
1140    Result = !Val.getComplexFloatReal().isZero() ||
1141             !Val.getComplexFloatImag().isZero();
1142    return true;
1143  case APValue::LValue:
1144    return EvalPointerValueAsBool(Val, Result);
1145  case APValue::MemberPointer:
1146    Result = Val.getMemberPointerDecl();
1147    return true;
1148  case APValue::Vector:
1149  case APValue::Array:
1150  case APValue::Struct:
1151  case APValue::Union:
1152  case APValue::AddrLabelDiff:
1153    return false;
1154  }
1155
1156  llvm_unreachable("unknown APValue kind");
1157}
1158
1159static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1160                                       EvalInfo &Info) {
1161  assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1162  APValue Val;
1163  if (!Evaluate(Val, Info, E))
1164    return false;
1165  return HandleConversionToBool(Val, Result);
1166}
1167
1168template<typename T>
1169static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1170                           const T &SrcValue, QualType DestType) {
1171  Info.Diag(E, diag::note_constexpr_overflow)
1172    << SrcValue << DestType;
1173  return false;
1174}
1175
1176static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1177                                 QualType SrcType, const APFloat &Value,
1178                                 QualType DestType, APSInt &Result) {
1179  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1180  // Determine whether we are converting to unsigned or signed.
1181  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1182
1183  Result = APSInt(DestWidth, !DestSigned);
1184  bool ignored;
1185  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1186      & APFloat::opInvalidOp)
1187    return HandleOverflow(Info, E, Value, DestType);
1188  return true;
1189}
1190
1191static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1192                                   QualType SrcType, QualType DestType,
1193                                   APFloat &Result) {
1194  APFloat Value = Result;
1195  bool ignored;
1196  if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1197                     APFloat::rmNearestTiesToEven, &ignored)
1198      & APFloat::opOverflow)
1199    return HandleOverflow(Info, E, Value, DestType);
1200  return true;
1201}
1202
1203static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1204                                 QualType DestType, QualType SrcType,
1205                                 APSInt &Value) {
1206  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1207  APSInt Result = Value;
1208  // Figure out if this is a truncate, extend or noop cast.
1209  // If the input is signed, do a sign extend, noop, or truncate.
1210  Result = Result.extOrTrunc(DestWidth);
1211  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1212  return Result;
1213}
1214
1215static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1216                                 QualType SrcType, const APSInt &Value,
1217                                 QualType DestType, APFloat &Result) {
1218  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1219  if (Result.convertFromAPInt(Value, Value.isSigned(),
1220                              APFloat::rmNearestTiesToEven)
1221      & APFloat::opOverflow)
1222    return HandleOverflow(Info, E, Value, DestType);
1223  return true;
1224}
1225
1226static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1227                                  llvm::APInt &Res) {
1228  APValue SVal;
1229  if (!Evaluate(SVal, Info, E))
1230    return false;
1231  if (SVal.isInt()) {
1232    Res = SVal.getInt();
1233    return true;
1234  }
1235  if (SVal.isFloat()) {
1236    Res = SVal.getFloat().bitcastToAPInt();
1237    return true;
1238  }
1239  if (SVal.isVector()) {
1240    QualType VecTy = E->getType();
1241    unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1242    QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1243    unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1244    bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1245    Res = llvm::APInt::getNullValue(VecSize);
1246    for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1247      APValue &Elt = SVal.getVectorElt(i);
1248      llvm::APInt EltAsInt;
1249      if (Elt.isInt()) {
1250        EltAsInt = Elt.getInt();
1251      } else if (Elt.isFloat()) {
1252        EltAsInt = Elt.getFloat().bitcastToAPInt();
1253      } else {
1254        // Don't try to handle vectors of anything other than int or float
1255        // (not sure if it's possible to hit this case).
1256        Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1257        return false;
1258      }
1259      unsigned BaseEltSize = EltAsInt.getBitWidth();
1260      if (BigEndian)
1261        Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1262      else
1263        Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1264    }
1265    return true;
1266  }
1267  // Give up if the input isn't an int, float, or vector.  For example, we
1268  // reject "(v4i16)(intptr_t)&a".
1269  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1270  return false;
1271}
1272
1273/// Cast an lvalue referring to a base subobject to a derived class, by
1274/// truncating the lvalue's path to the given length.
1275static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1276                               const RecordDecl *TruncatedType,
1277                               unsigned TruncatedElements) {
1278  SubobjectDesignator &D = Result.Designator;
1279
1280  // Check we actually point to a derived class object.
1281  if (TruncatedElements == D.Entries.size())
1282    return true;
1283  assert(TruncatedElements >= D.MostDerivedPathLength &&
1284         "not casting to a derived class");
1285  if (!Result.checkSubobject(Info, E, CSK_Derived))
1286    return false;
1287
1288  // Truncate the path to the subobject, and remove any derived-to-base offsets.
1289  const RecordDecl *RD = TruncatedType;
1290  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1291    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1292    const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1293    if (isVirtualBaseClass(D.Entries[I]))
1294      Result.Offset -= Layout.getVBaseClassOffset(Base);
1295    else
1296      Result.Offset -= Layout.getBaseClassOffset(Base);
1297    RD = Base;
1298  }
1299  D.Entries.resize(TruncatedElements);
1300  return true;
1301}
1302
1303static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1304                                   const CXXRecordDecl *Derived,
1305                                   const CXXRecordDecl *Base,
1306                                   const ASTRecordLayout *RL = 0) {
1307  if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1308  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1309  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1310}
1311
1312static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1313                             const CXXRecordDecl *DerivedDecl,
1314                             const CXXBaseSpecifier *Base) {
1315  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1316
1317  if (!Base->isVirtual()) {
1318    HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1319    return true;
1320  }
1321
1322  SubobjectDesignator &D = Obj.Designator;
1323  if (D.Invalid)
1324    return false;
1325
1326  // Extract most-derived object and corresponding type.
1327  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1328  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1329    return false;
1330
1331  // Find the virtual base class.
1332  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1333  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1334  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1335  return true;
1336}
1337
1338/// Update LVal to refer to the given field, which must be a member of the type
1339/// currently described by LVal.
1340static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1341                               const FieldDecl *FD,
1342                               const ASTRecordLayout *RL = 0) {
1343  if (!RL)
1344    RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1345
1346  unsigned I = FD->getFieldIndex();
1347  LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1348  LVal.addDecl(Info, E, FD);
1349}
1350
1351/// Update LVal to refer to the given indirect field.
1352static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1353                                       LValue &LVal,
1354                                       const IndirectFieldDecl *IFD) {
1355  for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1356                                         CE = IFD->chain_end(); C != CE; ++C)
1357    HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1358}
1359
1360/// Get the size of the given type in char units.
1361static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1362                         QualType Type, CharUnits &Size) {
1363  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1364  // extension.
1365  if (Type->isVoidType() || Type->isFunctionType()) {
1366    Size = CharUnits::One();
1367    return true;
1368  }
1369
1370  if (!Type->isConstantSizeType()) {
1371    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1372    // FIXME: Better diagnostic.
1373    Info.Diag(Loc);
1374    return false;
1375  }
1376
1377  Size = Info.Ctx.getTypeSizeInChars(Type);
1378  return true;
1379}
1380
1381/// Update a pointer value to model pointer arithmetic.
1382/// \param Info - Information about the ongoing evaluation.
1383/// \param E - The expression being evaluated, for diagnostic purposes.
1384/// \param LVal - The pointer value to be updated.
1385/// \param EltTy - The pointee type represented by LVal.
1386/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1387static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1388                                        LValue &LVal, QualType EltTy,
1389                                        int64_t Adjustment) {
1390  CharUnits SizeOfPointee;
1391  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1392    return false;
1393
1394  // Compute the new offset in the appropriate width.
1395  LVal.Offset += Adjustment * SizeOfPointee;
1396  LVal.adjustIndex(Info, E, Adjustment);
1397  return true;
1398}
1399
1400/// Update an lvalue to refer to a component of a complex number.
1401/// \param Info - Information about the ongoing evaluation.
1402/// \param LVal - The lvalue to be updated.
1403/// \param EltTy - The complex number's component type.
1404/// \param Imag - False for the real component, true for the imaginary.
1405static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1406                                       LValue &LVal, QualType EltTy,
1407                                       bool Imag) {
1408  if (Imag) {
1409    CharUnits SizeOfComponent;
1410    if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1411      return false;
1412    LVal.Offset += SizeOfComponent;
1413  }
1414  LVal.addComplex(Info, E, EltTy, Imag);
1415  return true;
1416}
1417
1418/// Try to evaluate the initializer for a variable declaration.
1419static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1420                                const VarDecl *VD,
1421                                CallStackFrame *Frame, APValue &Result) {
1422  // If this is a parameter to an active constexpr function call, perform
1423  // argument substitution.
1424  if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1425    // Assume arguments of a potential constant expression are unknown
1426    // constant expressions.
1427    if (Info.CheckingPotentialConstantExpression)
1428      return false;
1429    if (!Frame || !Frame->Arguments) {
1430      Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1431      return false;
1432    }
1433    Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1434    return true;
1435  }
1436
1437  // Dig out the initializer, and use the declaration which it's attached to.
1438  const Expr *Init = VD->getAnyInitializer(VD);
1439  if (!Init || Init->isValueDependent()) {
1440    // If we're checking a potential constant expression, the variable could be
1441    // initialized later.
1442    if (!Info.CheckingPotentialConstantExpression)
1443      Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1444    return false;
1445  }
1446
1447  // If we're currently evaluating the initializer of this declaration, use that
1448  // in-flight value.
1449  if (Info.EvaluatingDecl == VD) {
1450    Result = *Info.EvaluatingDeclValue;
1451    return !Result.isUninit();
1452  }
1453
1454  // Never evaluate the initializer of a weak variable. We can't be sure that
1455  // this is the definition which will be used.
1456  if (VD->isWeak()) {
1457    Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1458    return false;
1459  }
1460
1461  // Check that we can fold the initializer. In C++, we will have already done
1462  // this in the cases where it matters for conformance.
1463  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1464  if (!VD->evaluateValue(Notes)) {
1465    Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1466              Notes.size() + 1) << VD;
1467    Info.Note(VD->getLocation(), diag::note_declared_at);
1468    Info.addNotes(Notes);
1469    return false;
1470  } else if (!VD->checkInitIsICE()) {
1471    Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
1472                 Notes.size() + 1) << VD;
1473    Info.Note(VD->getLocation(), diag::note_declared_at);
1474    Info.addNotes(Notes);
1475  }
1476
1477  Result = *VD->getEvaluatedValue();
1478  return true;
1479}
1480
1481static bool IsConstNonVolatile(QualType T) {
1482  Qualifiers Quals = T.getQualifiers();
1483  return Quals.hasConst() && !Quals.hasVolatile();
1484}
1485
1486/// Get the base index of the given base class within an APValue representing
1487/// the given derived class.
1488static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1489                             const CXXRecordDecl *Base) {
1490  Base = Base->getCanonicalDecl();
1491  unsigned Index = 0;
1492  for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1493         E = Derived->bases_end(); I != E; ++I, ++Index) {
1494    if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1495      return Index;
1496  }
1497
1498  llvm_unreachable("base class missing from derived class's bases list");
1499}
1500
1501/// Extract the value of a character from a string literal.
1502static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1503                                            uint64_t Index) {
1504  // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1505  const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1506  assert(S && "unexpected string literal expression kind");
1507
1508  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1509    Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1510  if (Index < S->getLength())
1511    Value = S->getCodeUnit(Index);
1512  return Value;
1513}
1514
1515/// Extract the designated sub-object of an rvalue.
1516static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1517                             APValue &Obj, QualType ObjType,
1518                             const SubobjectDesignator &Sub, QualType SubType) {
1519  if (Sub.Invalid)
1520    // A diagnostic will have already been produced.
1521    return false;
1522  if (Sub.isOnePastTheEnd()) {
1523    Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1524                (unsigned)diag::note_constexpr_read_past_end :
1525                (unsigned)diag::note_invalid_subexpr_in_const_expr);
1526    return false;
1527  }
1528  if (Sub.Entries.empty())
1529    return true;
1530  if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1531    // This object might be initialized later.
1532    return false;
1533
1534  APValue *O = &Obj;
1535  // Walk the designator's path to find the subobject.
1536  for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
1537    if (ObjType->isArrayType()) {
1538      // Next subobject is an array element.
1539      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
1540      assert(CAT && "vla in literal type?");
1541      uint64_t Index = Sub.Entries[I].ArrayIndex;
1542      if (CAT->getSize().ule(Index)) {
1543        // Note, it should not be possible to form a pointer with a valid
1544        // designator which points more than one past the end of the array.
1545        Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1546                    (unsigned)diag::note_constexpr_read_past_end :
1547                    (unsigned)diag::note_invalid_subexpr_in_const_expr);
1548        return false;
1549      }
1550      // An array object is represented as either an Array APValue or as an
1551      // LValue which refers to a string literal.
1552      if (O->isLValue()) {
1553        assert(I == N - 1 && "extracting subobject of character?");
1554        assert(!O->hasLValuePath() || O->getLValuePath().empty());
1555        Obj = APValue(ExtractStringLiteralCharacter(
1556          Info, O->getLValueBase().get<const Expr*>(), Index));
1557        return true;
1558      } else if (O->getArrayInitializedElts() > Index)
1559        O = &O->getArrayInitializedElt(Index);
1560      else
1561        O = &O->getArrayFiller();
1562      ObjType = CAT->getElementType();
1563    } else if (ObjType->isAnyComplexType()) {
1564      // Next subobject is a complex number.
1565      uint64_t Index = Sub.Entries[I].ArrayIndex;
1566      if (Index > 1) {
1567        Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1568                    (unsigned)diag::note_constexpr_read_past_end :
1569                    (unsigned)diag::note_invalid_subexpr_in_const_expr);
1570        return false;
1571      }
1572      assert(I == N - 1 && "extracting subobject of scalar?");
1573      if (O->isComplexInt()) {
1574        Obj = APValue(Index ? O->getComplexIntImag()
1575                            : O->getComplexIntReal());
1576      } else {
1577        assert(O->isComplexFloat());
1578        Obj = APValue(Index ? O->getComplexFloatImag()
1579                            : O->getComplexFloatReal());
1580      }
1581      return true;
1582    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1583      if (Field->isMutable()) {
1584        Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
1585          << Field;
1586        Info.Note(Field->getLocation(), diag::note_declared_at);
1587        return false;
1588      }
1589
1590      // Next subobject is a class, struct or union field.
1591      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1592      if (RD->isUnion()) {
1593        const FieldDecl *UnionField = O->getUnionField();
1594        if (!UnionField ||
1595            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
1596          Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
1597            << Field << !UnionField << UnionField;
1598          return false;
1599        }
1600        O = &O->getUnionValue();
1601      } else
1602        O = &O->getStructField(Field->getFieldIndex());
1603      ObjType = Field->getType();
1604
1605      if (ObjType.isVolatileQualified()) {
1606        if (Info.getLangOpts().CPlusPlus) {
1607          // FIXME: Include a description of the path to the volatile subobject.
1608          Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
1609            << 2 << Field;
1610          Info.Note(Field->getLocation(), diag::note_declared_at);
1611        } else {
1612          Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1613        }
1614        return false;
1615      }
1616    } else {
1617      // Next subobject is a base class.
1618      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1619      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1620      O = &O->getStructBase(getBaseIndex(Derived, Base));
1621      ObjType = Info.Ctx.getRecordType(Base);
1622    }
1623
1624    if (O->isUninit()) {
1625      if (!Info.CheckingPotentialConstantExpression)
1626        Info.Diag(E, diag::note_constexpr_read_uninit);
1627      return false;
1628    }
1629  }
1630
1631  // This may look super-stupid, but it serves an important purpose: if we just
1632  // swapped Obj and *O, we'd create an object which had itself as a subobject.
1633  // To avoid the leak, we ensure that Tmp ends up owning the original complete
1634  // object, which is destroyed by Tmp's destructor.
1635  APValue Tmp;
1636  O->swap(Tmp);
1637  Obj.swap(Tmp);
1638  return true;
1639}
1640
1641/// Find the position where two subobject designators diverge, or equivalently
1642/// the length of the common initial subsequence.
1643static unsigned FindDesignatorMismatch(QualType ObjType,
1644                                       const SubobjectDesignator &A,
1645                                       const SubobjectDesignator &B,
1646                                       bool &WasArrayIndex) {
1647  unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1648  for (/**/; I != N; ++I) {
1649    if (!ObjType.isNull() &&
1650        (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
1651      // Next subobject is an array element.
1652      if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1653        WasArrayIndex = true;
1654        return I;
1655      }
1656      if (ObjType->isAnyComplexType())
1657        ObjType = ObjType->castAs<ComplexType>()->getElementType();
1658      else
1659        ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1660    } else {
1661      if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1662        WasArrayIndex = false;
1663        return I;
1664      }
1665      if (const FieldDecl *FD = getAsField(A.Entries[I]))
1666        // Next subobject is a field.
1667        ObjType = FD->getType();
1668      else
1669        // Next subobject is a base class.
1670        ObjType = QualType();
1671    }
1672  }
1673  WasArrayIndex = false;
1674  return I;
1675}
1676
1677/// Determine whether the given subobject designators refer to elements of the
1678/// same array object.
1679static bool AreElementsOfSameArray(QualType ObjType,
1680                                   const SubobjectDesignator &A,
1681                                   const SubobjectDesignator &B) {
1682  if (A.Entries.size() != B.Entries.size())
1683    return false;
1684
1685  bool IsArray = A.MostDerivedArraySize != 0;
1686  if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1687    // A is a subobject of the array element.
1688    return false;
1689
1690  // If A (and B) designates an array element, the last entry will be the array
1691  // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1692  // of length 1' case, and the entire path must match.
1693  bool WasArrayIndex;
1694  unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1695  return CommonLength >= A.Entries.size() - IsArray;
1696}
1697
1698/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1699/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1700/// for looking up the glvalue referred to by an entity of reference type.
1701///
1702/// \param Info - Information about the ongoing evaluation.
1703/// \param Conv - The expression for which we are performing the conversion.
1704///               Used for diagnostics.
1705/// \param Type - The type we expect this conversion to produce, before
1706///               stripping cv-qualifiers in the case of a non-clas type.
1707/// \param LVal - The glvalue on which we are attempting to perform this action.
1708/// \param RVal - The produced value will be placed here.
1709static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1710                                           QualType Type,
1711                                           const LValue &LVal, APValue &RVal) {
1712  if (LVal.Designator.Invalid)
1713    // A diagnostic will have already been produced.
1714    return false;
1715
1716  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
1717
1718  if (!LVal.Base) {
1719    // FIXME: Indirection through a null pointer deserves a specific diagnostic.
1720    Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
1721    return false;
1722  }
1723
1724  CallStackFrame *Frame = 0;
1725  if (LVal.CallIndex) {
1726    Frame = Info.getCallFrame(LVal.CallIndex);
1727    if (!Frame) {
1728      Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
1729      NoteLValueLocation(Info, LVal.Base);
1730      return false;
1731    }
1732  }
1733
1734  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1735  // is not a constant expression (even if the object is non-volatile). We also
1736  // apply this rule to C++98, in order to conform to the expected 'volatile'
1737  // semantics.
1738  if (Type.isVolatileQualified()) {
1739    if (Info.getLangOpts().CPlusPlus)
1740      Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
1741    else
1742      Info.Diag(Conv);
1743    return false;
1744  }
1745
1746  if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1747    // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1748    // In C++11, constexpr, non-volatile variables initialized with constant
1749    // expressions are constant expressions too. Inside constexpr functions,
1750    // parameters are constant expressions even if they're non-const.
1751    // In C, such things can also be folded, although they are not ICEs.
1752    const VarDecl *VD = dyn_cast<VarDecl>(D);
1753    if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1754      VD = VDef;
1755    if (!VD || VD->isInvalidDecl()) {
1756      Info.Diag(Conv);
1757      return false;
1758    }
1759
1760    // DR1313: If the object is volatile-qualified but the glvalue was not,
1761    // behavior is undefined so the result is not a constant expression.
1762    QualType VT = VD->getType();
1763    if (VT.isVolatileQualified()) {
1764      if (Info.getLangOpts().CPlusPlus) {
1765        Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1766        Info.Note(VD->getLocation(), diag::note_declared_at);
1767      } else {
1768        Info.Diag(Conv);
1769      }
1770      return false;
1771    }
1772
1773    if (!isa<ParmVarDecl>(VD)) {
1774      if (VD->isConstexpr()) {
1775        // OK, we can read this variable.
1776      } else if (VT->isIntegralOrEnumerationType()) {
1777        if (!VT.isConstQualified()) {
1778          if (Info.getLangOpts().CPlusPlus) {
1779            Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1780            Info.Note(VD->getLocation(), diag::note_declared_at);
1781          } else {
1782            Info.Diag(Conv);
1783          }
1784          return false;
1785        }
1786      } else if (VT->isFloatingType() && VT.isConstQualified()) {
1787        // We support folding of const floating-point types, in order to make
1788        // static const data members of such types (supported as an extension)
1789        // more useful.
1790        if (Info.getLangOpts().CPlusPlus0x) {
1791          Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1792          Info.Note(VD->getLocation(), diag::note_declared_at);
1793        } else {
1794          Info.CCEDiag(Conv);
1795        }
1796      } else {
1797        // FIXME: Allow folding of values of any literal type in all languages.
1798        if (Info.getLangOpts().CPlusPlus0x) {
1799          Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1800          Info.Note(VD->getLocation(), diag::note_declared_at);
1801        } else {
1802          Info.Diag(Conv);
1803        }
1804        return false;
1805      }
1806    }
1807
1808    if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
1809      return false;
1810
1811    if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
1812      return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
1813
1814    // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1815    // conversion. This happens when the declaration and the lvalue should be
1816    // considered synonymous, for instance when initializing an array of char
1817    // from a string literal. Continue as if the initializer lvalue was the
1818    // value we were originally given.
1819    assert(RVal.getLValueOffset().isZero() &&
1820           "offset for lvalue init of non-reference");
1821    Base = RVal.getLValueBase().get<const Expr*>();
1822
1823    if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1824      Frame = Info.getCallFrame(CallIndex);
1825      if (!Frame) {
1826        Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
1827        NoteLValueLocation(Info, RVal.getLValueBase());
1828        return false;
1829      }
1830    } else {
1831      Frame = 0;
1832    }
1833  }
1834
1835  // Volatile temporary objects cannot be read in constant expressions.
1836  if (Base->getType().isVolatileQualified()) {
1837    if (Info.getLangOpts().CPlusPlus) {
1838      Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1839      Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1840    } else {
1841      Info.Diag(Conv);
1842    }
1843    return false;
1844  }
1845
1846  if (Frame) {
1847    // If this is a temporary expression with a nontrivial initializer, grab the
1848    // value from the relevant stack frame.
1849    RVal = Frame->Temporaries[Base];
1850  } else if (const CompoundLiteralExpr *CLE
1851             = dyn_cast<CompoundLiteralExpr>(Base)) {
1852    // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1853    // initializer until now for such expressions. Such an expression can't be
1854    // an ICE in C, so this only matters for fold.
1855    assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1856    if (!Evaluate(RVal, Info, CLE->getInitializer()))
1857      return false;
1858  } else if (isa<StringLiteral>(Base)) {
1859    // We represent a string literal array as an lvalue pointing at the
1860    // corresponding expression, rather than building an array of chars.
1861    // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1862    RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
1863  } else {
1864    Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
1865    return false;
1866  }
1867
1868  return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1869                          Type);
1870}
1871
1872/// Build an lvalue for the object argument of a member function call.
1873static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1874                                   LValue &This) {
1875  if (Object->getType()->isPointerType())
1876    return EvaluatePointer(Object, This, Info);
1877
1878  if (Object->isGLValue())
1879    return EvaluateLValue(Object, This, Info);
1880
1881  if (Object->getType()->isLiteralType())
1882    return EvaluateTemporary(Object, This, Info);
1883
1884  return false;
1885}
1886
1887/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1888/// lvalue referring to the result.
1889///
1890/// \param Info - Information about the ongoing evaluation.
1891/// \param BO - The member pointer access operation.
1892/// \param LV - Filled in with a reference to the resulting object.
1893/// \param IncludeMember - Specifies whether the member itself is included in
1894///        the resulting LValue subobject designator. This is not possible when
1895///        creating a bound member function.
1896/// \return The field or method declaration to which the member pointer refers,
1897///         or 0 if evaluation fails.
1898static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1899                                                  const BinaryOperator *BO,
1900                                                  LValue &LV,
1901                                                  bool IncludeMember = true) {
1902  assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1903
1904  bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1905  if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
1906    return 0;
1907
1908  MemberPtr MemPtr;
1909  if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1910    return 0;
1911
1912  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1913  // member value, the behavior is undefined.
1914  if (!MemPtr.getDecl())
1915    return 0;
1916
1917  if (!EvalObjOK)
1918    return 0;
1919
1920  if (MemPtr.isDerivedMember()) {
1921    // This is a member of some derived class. Truncate LV appropriately.
1922    // The end of the derived-to-base path for the base object must match the
1923    // derived-to-base path for the member pointer.
1924    if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
1925        LV.Designator.Entries.size())
1926      return 0;
1927    unsigned PathLengthToMember =
1928        LV.Designator.Entries.size() - MemPtr.Path.size();
1929    for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1930      const CXXRecordDecl *LVDecl = getAsBaseClass(
1931          LV.Designator.Entries[PathLengthToMember + I]);
1932      const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1933      if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1934        return 0;
1935    }
1936
1937    // Truncate the lvalue to the appropriate derived class.
1938    if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1939                            PathLengthToMember))
1940      return 0;
1941  } else if (!MemPtr.Path.empty()) {
1942    // Extend the LValue path with the member pointer's path.
1943    LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1944                                  MemPtr.Path.size() + IncludeMember);
1945
1946    // Walk down to the appropriate base class.
1947    QualType LVType = BO->getLHS()->getType();
1948    if (const PointerType *PT = LVType->getAs<PointerType>())
1949      LVType = PT->getPointeeType();
1950    const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1951    assert(RD && "member pointer access on non-class-type expression");
1952    // The first class in the path is that of the lvalue.
1953    for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1954      const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1955      HandleLValueDirectBase(Info, BO, LV, RD, Base);
1956      RD = Base;
1957    }
1958    // Finally cast to the class containing the member.
1959    HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
1960  }
1961
1962  // Add the member. Note that we cannot build bound member functions here.
1963  if (IncludeMember) {
1964    if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1965      HandleLValueMember(Info, BO, LV, FD);
1966    else if (const IndirectFieldDecl *IFD =
1967               dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1968      HandleLValueIndirectMember(Info, BO, LV, IFD);
1969    else
1970      llvm_unreachable("can't construct reference to bound member function");
1971  }
1972
1973  return MemPtr.getDecl();
1974}
1975
1976/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1977/// the provided lvalue, which currently refers to the base object.
1978static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1979                                    LValue &Result) {
1980  SubobjectDesignator &D = Result.Designator;
1981  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
1982    return false;
1983
1984  QualType TargetQT = E->getType();
1985  if (const PointerType *PT = TargetQT->getAs<PointerType>())
1986    TargetQT = PT->getPointeeType();
1987
1988  // Check this cast lands within the final derived-to-base subobject path.
1989  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1990    Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
1991      << D.MostDerivedType << TargetQT;
1992    return false;
1993  }
1994
1995  // Check the type of the final cast. We don't need to check the path,
1996  // since a cast can only be formed if the path is unique.
1997  unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1998  const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1999  const CXXRecordDecl *FinalType;
2000  if (NewEntriesSize == D.MostDerivedPathLength)
2001    FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2002  else
2003    FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
2004  if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
2005    Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
2006      << D.MostDerivedType << TargetQT;
2007    return false;
2008  }
2009
2010  // Truncate the lvalue to the appropriate derived class.
2011  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
2012}
2013
2014namespace {
2015enum EvalStmtResult {
2016  /// Evaluation failed.
2017  ESR_Failed,
2018  /// Hit a 'return' statement.
2019  ESR_Returned,
2020  /// Evaluation succeeded.
2021  ESR_Succeeded
2022};
2023}
2024
2025// Evaluate a statement.
2026static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2027                                   const Stmt *S) {
2028  switch (S->getStmtClass()) {
2029  default:
2030    return ESR_Failed;
2031
2032  case Stmt::NullStmtClass:
2033  case Stmt::DeclStmtClass:
2034    return ESR_Succeeded;
2035
2036  case Stmt::ReturnStmtClass: {
2037    const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
2038    if (!Evaluate(Result, Info, RetExpr))
2039      return ESR_Failed;
2040    return ESR_Returned;
2041  }
2042
2043  case Stmt::CompoundStmtClass: {
2044    const CompoundStmt *CS = cast<CompoundStmt>(S);
2045    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2046           BE = CS->body_end(); BI != BE; ++BI) {
2047      EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2048      if (ESR != ESR_Succeeded)
2049        return ESR;
2050    }
2051    return ESR_Succeeded;
2052  }
2053  }
2054}
2055
2056/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2057/// default constructor. If so, we'll fold it whether or not it's marked as
2058/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2059/// so we need special handling.
2060static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
2061                                           const CXXConstructorDecl *CD,
2062                                           bool IsValueInitialization) {
2063  if (!CD->isTrivial() || !CD->isDefaultConstructor())
2064    return false;
2065
2066  // Value-initialization does not call a trivial default constructor, so such a
2067  // call is a core constant expression whether or not the constructor is
2068  // constexpr.
2069  if (!CD->isConstexpr() && !IsValueInitialization) {
2070    if (Info.getLangOpts().CPlusPlus0x) {
2071      // FIXME: If DiagDecl is an implicitly-declared special member function,
2072      // we should be much more explicit about why it's not constexpr.
2073      Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2074        << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2075      Info.Note(CD->getLocation(), diag::note_declared_at);
2076    } else {
2077      Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2078    }
2079  }
2080  return true;
2081}
2082
2083/// CheckConstexprFunction - Check that a function can be called in a constant
2084/// expression.
2085static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2086                                   const FunctionDecl *Declaration,
2087                                   const FunctionDecl *Definition) {
2088  // Potential constant expressions can contain calls to declared, but not yet
2089  // defined, constexpr functions.
2090  if (Info.CheckingPotentialConstantExpression && !Definition &&
2091      Declaration->isConstexpr())
2092    return false;
2093
2094  // Can we evaluate this function call?
2095  if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2096    return true;
2097
2098  if (Info.getLangOpts().CPlusPlus0x) {
2099    const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
2100    // FIXME: If DiagDecl is an implicitly-declared special member function, we
2101    // should be much more explicit about why it's not constexpr.
2102    Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2103      << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2104      << DiagDecl;
2105    Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2106  } else {
2107    Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2108  }
2109  return false;
2110}
2111
2112namespace {
2113typedef SmallVector<APValue, 8> ArgVector;
2114}
2115
2116/// EvaluateArgs - Evaluate the arguments to a function call.
2117static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2118                         EvalInfo &Info) {
2119  bool Success = true;
2120  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
2121       I != E; ++I) {
2122    if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2123      // If we're checking for a potential constant expression, evaluate all
2124      // initializers even if some of them fail.
2125      if (!Info.keepEvaluatingAfterFailure())
2126        return false;
2127      Success = false;
2128    }
2129  }
2130  return Success;
2131}
2132
2133/// Evaluate a function call.
2134static bool HandleFunctionCall(SourceLocation CallLoc,
2135                               const FunctionDecl *Callee, const LValue *This,
2136                               ArrayRef<const Expr*> Args, const Stmt *Body,
2137                               EvalInfo &Info, APValue &Result) {
2138  ArgVector ArgValues(Args.size());
2139  if (!EvaluateArgs(Args, ArgValues, Info))
2140    return false;
2141
2142  if (!Info.CheckCallLimit(CallLoc))
2143    return false;
2144
2145  CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
2146  return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2147}
2148
2149/// Evaluate a constructor call.
2150static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
2151                                  ArrayRef<const Expr*> Args,
2152                                  const CXXConstructorDecl *Definition,
2153                                  EvalInfo &Info, APValue &Result) {
2154  ArgVector ArgValues(Args.size());
2155  if (!EvaluateArgs(Args, ArgValues, Info))
2156    return false;
2157
2158  if (!Info.CheckCallLimit(CallLoc))
2159    return false;
2160
2161  const CXXRecordDecl *RD = Definition->getParent();
2162  if (RD->getNumVBases()) {
2163    Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2164    return false;
2165  }
2166
2167  CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
2168
2169  // If it's a delegating constructor, just delegate.
2170  if (Definition->isDelegatingConstructor()) {
2171    CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2172    return EvaluateInPlace(Result, Info, This, (*I)->getInit());
2173  }
2174
2175  // For a trivial copy or move constructor, perform an APValue copy. This is
2176  // essential for unions, where the operations performed by the constructor
2177  // cannot be represented by ctor-initializers.
2178  if (Definition->isDefaulted() &&
2179      ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2180       (Definition->isMoveConstructor() && Definition->isTrivial()))) {
2181    LValue RHS;
2182    RHS.setFrom(Info.Ctx, ArgValues[0]);
2183    return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2184                                          RHS, Result);
2185  }
2186
2187  // Reserve space for the struct members.
2188  if (!RD->isUnion() && Result.isUninit())
2189    Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2190                     std::distance(RD->field_begin(), RD->field_end()));
2191
2192  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2193
2194  bool Success = true;
2195  unsigned BasesSeen = 0;
2196#ifndef NDEBUG
2197  CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2198#endif
2199  for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2200       E = Definition->init_end(); I != E; ++I) {
2201    LValue Subobject = This;
2202    APValue *Value = &Result;
2203
2204    // Determine the subobject to initialize.
2205    if ((*I)->isBaseInitializer()) {
2206      QualType BaseType((*I)->getBaseClass(), 0);
2207#ifndef NDEBUG
2208      // Non-virtual base classes are initialized in the order in the class
2209      // definition. We have already checked for virtual base classes.
2210      assert(!BaseIt->isVirtual() && "virtual base for literal type");
2211      assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2212             "base class initializers not in expected order");
2213      ++BaseIt;
2214#endif
2215      HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2216                             BaseType->getAsCXXRecordDecl(), &Layout);
2217      Value = &Result.getStructBase(BasesSeen++);
2218    } else if (FieldDecl *FD = (*I)->getMember()) {
2219      HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
2220      if (RD->isUnion()) {
2221        Result = APValue(FD);
2222        Value = &Result.getUnionValue();
2223      } else {
2224        Value = &Result.getStructField(FD->getFieldIndex());
2225      }
2226    } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
2227      // Walk the indirect field decl's chain to find the object to initialize,
2228      // and make sure we've initialized every step along it.
2229      for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2230                                             CE = IFD->chain_end();
2231           C != CE; ++C) {
2232        FieldDecl *FD = cast<FieldDecl>(*C);
2233        CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2234        // Switch the union field if it differs. This happens if we had
2235        // preceding zero-initialization, and we're now initializing a union
2236        // subobject other than the first.
2237        // FIXME: In this case, the values of the other subobjects are
2238        // specified, since zero-initialization sets all padding bits to zero.
2239        if (Value->isUninit() ||
2240            (Value->isUnion() && Value->getUnionField() != FD)) {
2241          if (CD->isUnion())
2242            *Value = APValue(FD);
2243          else
2244            *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2245                             std::distance(CD->field_begin(), CD->field_end()));
2246        }
2247        HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
2248        if (CD->isUnion())
2249          Value = &Value->getUnionValue();
2250        else
2251          Value = &Value->getStructField(FD->getFieldIndex());
2252      }
2253    } else {
2254      llvm_unreachable("unknown base initializer kind");
2255    }
2256
2257    if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2258                         (*I)->isBaseInitializer()
2259                                      ? CCEK_Constant : CCEK_MemberInit)) {
2260      // If we're checking for a potential constant expression, evaluate all
2261      // initializers even if some of them fail.
2262      if (!Info.keepEvaluatingAfterFailure())
2263        return false;
2264      Success = false;
2265    }
2266  }
2267
2268  return Success;
2269}
2270
2271namespace {
2272class HasSideEffect
2273  : public ConstStmtVisitor<HasSideEffect, bool> {
2274  const ASTContext &Ctx;
2275public:
2276
2277  HasSideEffect(const ASTContext &C) : Ctx(C) {}
2278
2279  // Unhandled nodes conservatively default to having side effects.
2280  bool VisitStmt(const Stmt *S) {
2281    return true;
2282  }
2283
2284  bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2285  bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
2286    return Visit(E->getResultExpr());
2287  }
2288  bool VisitDeclRefExpr(const DeclRefExpr *E) {
2289    if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2290      return true;
2291    return false;
2292  }
2293  bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
2294    if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2295      return true;
2296    return false;
2297  }
2298
2299  // We don't want to evaluate BlockExprs multiple times, as they generate
2300  // a ton of code.
2301  bool VisitBlockExpr(const BlockExpr *E) { return true; }
2302  bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2303  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
2304    { return Visit(E->getInitializer()); }
2305  bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2306  bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2307  bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2308  bool VisitStringLiteral(const StringLiteral *E) { return false; }
2309  bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2310  bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
2311    { return false; }
2312  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
2313    { return Visit(E->getLHS()) || Visit(E->getRHS()); }
2314  bool VisitChooseExpr(const ChooseExpr *E)
2315    { return Visit(E->getChosenSubExpr(Ctx)); }
2316  bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2317  bool VisitBinAssign(const BinaryOperator *E) { return true; }
2318  bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2319  bool VisitBinaryOperator(const BinaryOperator *E)
2320  { return Visit(E->getLHS()) || Visit(E->getRHS()); }
2321  bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2322  bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2323  bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2324  bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2325  bool VisitUnaryDeref(const UnaryOperator *E) {
2326    if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2327      return true;
2328    return Visit(E->getSubExpr());
2329  }
2330  bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
2331
2332  // Has side effects if any element does.
2333  bool VisitInitListExpr(const InitListExpr *E) {
2334    for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2335      if (Visit(E->getInit(i))) return true;
2336    if (const Expr *filler = E->getArrayFiller())
2337      return Visit(filler);
2338    return false;
2339  }
2340
2341  bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
2342};
2343
2344class OpaqueValueEvaluation {
2345  EvalInfo &info;
2346  OpaqueValueExpr *opaqueValue;
2347
2348public:
2349  OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2350                        Expr *value)
2351    : info(info), opaqueValue(opaqueValue) {
2352
2353    // If evaluation fails, fail immediately.
2354    if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
2355      this->opaqueValue = 0;
2356      return;
2357    }
2358  }
2359
2360  bool hasError() const { return opaqueValue == 0; }
2361
2362  ~OpaqueValueEvaluation() {
2363    // FIXME: For a recursive constexpr call, an outer stack frame might have
2364    // been using this opaque value too, and will now have to re-evaluate the
2365    // source expression.
2366    if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2367  }
2368};
2369
2370} // end anonymous namespace
2371
2372//===----------------------------------------------------------------------===//
2373// Generic Evaluation
2374//===----------------------------------------------------------------------===//
2375namespace {
2376
2377// FIXME: RetTy is always bool. Remove it.
2378template <class Derived, typename RetTy=bool>
2379class ExprEvaluatorBase
2380  : public ConstStmtVisitor<Derived, RetTy> {
2381private:
2382  RetTy DerivedSuccess(const APValue &V, const Expr *E) {
2383    return static_cast<Derived*>(this)->Success(V, E);
2384  }
2385  RetTy DerivedZeroInitialization(const Expr *E) {
2386    return static_cast<Derived*>(this)->ZeroInitialization(E);
2387  }
2388
2389  // Check whether a conditional operator with a non-constant condition is a
2390  // potential constant expression. If neither arm is a potential constant
2391  // expression, then the conditional operator is not either.
2392  template<typename ConditionalOperator>
2393  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2394    assert(Info.CheckingPotentialConstantExpression);
2395
2396    // Speculatively evaluate both arms.
2397    {
2398      llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2399      SpeculativeEvaluationRAII Speculate(Info, &Diag);
2400
2401      StmtVisitorTy::Visit(E->getFalseExpr());
2402      if (Diag.empty())
2403        return;
2404
2405      Diag.clear();
2406      StmtVisitorTy::Visit(E->getTrueExpr());
2407      if (Diag.empty())
2408        return;
2409    }
2410
2411    Error(E, diag::note_constexpr_conditional_never_const);
2412  }
2413
2414
2415  template<typename ConditionalOperator>
2416  bool HandleConditionalOperator(const ConditionalOperator *E) {
2417    bool BoolResult;
2418    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2419      if (Info.CheckingPotentialConstantExpression)
2420        CheckPotentialConstantConditional(E);
2421      return false;
2422    }
2423
2424    Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2425    return StmtVisitorTy::Visit(EvalExpr);
2426  }
2427
2428protected:
2429  EvalInfo &Info;
2430  typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2431  typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2432
2433  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
2434    return Info.CCEDiag(E, D);
2435  }
2436
2437  /// Report an evaluation error. This should only be called when an error is
2438  /// first discovered. When propagating an error, just return false.
2439  bool Error(const Expr *E, diag::kind D) {
2440    Info.Diag(E, D);
2441    return false;
2442  }
2443  bool Error(const Expr *E) {
2444    return Error(E, diag::note_invalid_subexpr_in_const_expr);
2445  }
2446
2447  RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2448
2449public:
2450  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2451
2452  RetTy VisitStmt(const Stmt *) {
2453    llvm_unreachable("Expression evaluator should not be called on stmts");
2454  }
2455  RetTy VisitExpr(const Expr *E) {
2456    return Error(E);
2457  }
2458
2459  RetTy VisitParenExpr(const ParenExpr *E)
2460    { return StmtVisitorTy::Visit(E->getSubExpr()); }
2461  RetTy VisitUnaryExtension(const UnaryOperator *E)
2462    { return StmtVisitorTy::Visit(E->getSubExpr()); }
2463  RetTy VisitUnaryPlus(const UnaryOperator *E)
2464    { return StmtVisitorTy::Visit(E->getSubExpr()); }
2465  RetTy VisitChooseExpr(const ChooseExpr *E)
2466    { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2467  RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2468    { return StmtVisitorTy::Visit(E->getResultExpr()); }
2469  RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2470    { return StmtVisitorTy::Visit(E->getReplacement()); }
2471  RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2472    { return StmtVisitorTy::Visit(E->getExpr()); }
2473  // We cannot create any objects for which cleanups are required, so there is
2474  // nothing to do here; all cleanups must come from unevaluated subexpressions.
2475  RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2476    { return StmtVisitorTy::Visit(E->getSubExpr()); }
2477
2478  RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2479    CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2480    return static_cast<Derived*>(this)->VisitCastExpr(E);
2481  }
2482  RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2483    CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2484    return static_cast<Derived*>(this)->VisitCastExpr(E);
2485  }
2486
2487  RetTy VisitBinaryOperator(const BinaryOperator *E) {
2488    switch (E->getOpcode()) {
2489    default:
2490      return Error(E);
2491
2492    case BO_Comma:
2493      VisitIgnoredValue(E->getLHS());
2494      return StmtVisitorTy::Visit(E->getRHS());
2495
2496    case BO_PtrMemD:
2497    case BO_PtrMemI: {
2498      LValue Obj;
2499      if (!HandleMemberPointerAccess(Info, E, Obj))
2500        return false;
2501      APValue Result;
2502      if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
2503        return false;
2504      return DerivedSuccess(Result, E);
2505    }
2506    }
2507  }
2508
2509  RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2510    // Cache the value of the common expression.
2511    OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2512    if (opaque.hasError())
2513      return false;
2514
2515    return HandleConditionalOperator(E);
2516  }
2517
2518  RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2519    bool IsBcpCall = false;
2520    // If the condition (ignoring parens) is a __builtin_constant_p call,
2521    // the result is a constant expression if it can be folded without
2522    // side-effects. This is an important GNU extension. See GCC PR38377
2523    // for discussion.
2524    if (const CallExpr *CallCE =
2525          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2526      if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2527        IsBcpCall = true;
2528
2529    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2530    // constant expression; we can't check whether it's potentially foldable.
2531    if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2532      return false;
2533
2534    FoldConstant Fold(Info);
2535
2536    if (!HandleConditionalOperator(E))
2537      return false;
2538
2539    if (IsBcpCall)
2540      Fold.Fold(Info);
2541
2542    return true;
2543  }
2544
2545  RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2546    const APValue *Value = Info.getOpaqueValue(E);
2547    if (!Value) {
2548      const Expr *Source = E->getSourceExpr();
2549      if (!Source)
2550        return Error(E);
2551      if (Source == E) { // sanity checking.
2552        assert(0 && "OpaqueValueExpr recursively refers to itself");
2553        return Error(E);
2554      }
2555      return StmtVisitorTy::Visit(Source);
2556    }
2557    return DerivedSuccess(*Value, E);
2558  }
2559
2560  RetTy VisitCallExpr(const CallExpr *E) {
2561    const Expr *Callee = E->getCallee()->IgnoreParens();
2562    QualType CalleeType = Callee->getType();
2563
2564    const FunctionDecl *FD = 0;
2565    LValue *This = 0, ThisVal;
2566    llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
2567    bool HasQualifier = false;
2568
2569    // Extract function decl and 'this' pointer from the callee.
2570    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
2571      const ValueDecl *Member = 0;
2572      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2573        // Explicit bound member calls, such as x.f() or p->g();
2574        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
2575          return false;
2576        Member = ME->getMemberDecl();
2577        This = &ThisVal;
2578        HasQualifier = ME->hasQualifier();
2579      } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2580        // Indirect bound member calls ('.*' or '->*').
2581        Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2582        if (!Member) return false;
2583        This = &ThisVal;
2584      } else
2585        return Error(Callee);
2586
2587      FD = dyn_cast<FunctionDecl>(Member);
2588      if (!FD)
2589        return Error(Callee);
2590    } else if (CalleeType->isFunctionPointerType()) {
2591      LValue Call;
2592      if (!EvaluatePointer(Callee, Call, Info))
2593        return false;
2594
2595      if (!Call.getLValueOffset().isZero())
2596        return Error(Callee);
2597      FD = dyn_cast_or_null<FunctionDecl>(
2598                             Call.getLValueBase().dyn_cast<const ValueDecl*>());
2599      if (!FD)
2600        return Error(Callee);
2601
2602      // Overloaded operator calls to member functions are represented as normal
2603      // calls with '*this' as the first argument.
2604      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2605      if (MD && !MD->isStatic()) {
2606        // FIXME: When selecting an implicit conversion for an overloaded
2607        // operator delete, we sometimes try to evaluate calls to conversion
2608        // operators without a 'this' parameter!
2609        if (Args.empty())
2610          return Error(E);
2611
2612        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2613          return false;
2614        This = &ThisVal;
2615        Args = Args.slice(1);
2616      }
2617
2618      // Don't call function pointers which have been cast to some other type.
2619      if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
2620        return Error(E);
2621    } else
2622      return Error(E);
2623
2624    if (This && !This->checkSubobject(Info, E, CSK_This))
2625      return false;
2626
2627    // DR1358 allows virtual constexpr functions in some cases. Don't allow
2628    // calls to such functions in constant expressions.
2629    if (This && !HasQualifier &&
2630        isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2631      return Error(E, diag::note_constexpr_virtual_call);
2632
2633    const FunctionDecl *Definition = 0;
2634    Stmt *Body = FD->getBody(Definition);
2635    APValue Result;
2636
2637    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
2638        !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2639                            Info, Result))
2640      return false;
2641
2642    return DerivedSuccess(Result, E);
2643  }
2644
2645  RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2646    return StmtVisitorTy::Visit(E->getInitializer());
2647  }
2648  RetTy VisitInitListExpr(const InitListExpr *E) {
2649    if (E->getNumInits() == 0)
2650      return DerivedZeroInitialization(E);
2651    if (E->getNumInits() == 1)
2652      return StmtVisitorTy::Visit(E->getInit(0));
2653    return Error(E);
2654  }
2655  RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
2656    return DerivedZeroInitialization(E);
2657  }
2658  RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
2659    return DerivedZeroInitialization(E);
2660  }
2661  RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2662    return DerivedZeroInitialization(E);
2663  }
2664
2665  /// A member expression where the object is a prvalue is itself a prvalue.
2666  RetTy VisitMemberExpr(const MemberExpr *E) {
2667    assert(!E->isArrow() && "missing call to bound member function?");
2668
2669    APValue Val;
2670    if (!Evaluate(Val, Info, E->getBase()))
2671      return false;
2672
2673    QualType BaseTy = E->getBase()->getType();
2674
2675    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2676    if (!FD) return Error(E);
2677    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2678    assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2679           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2680
2681    SubobjectDesignator Designator(BaseTy);
2682    Designator.addDeclUnchecked(FD);
2683
2684    return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
2685           DerivedSuccess(Val, E);
2686  }
2687
2688  RetTy VisitCastExpr(const CastExpr *E) {
2689    switch (E->getCastKind()) {
2690    default:
2691      break;
2692
2693    case CK_AtomicToNonAtomic:
2694    case CK_NonAtomicToAtomic:
2695    case CK_NoOp:
2696    case CK_UserDefinedConversion:
2697      return StmtVisitorTy::Visit(E->getSubExpr());
2698
2699    case CK_LValueToRValue: {
2700      LValue LVal;
2701      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2702        return false;
2703      APValue RVal;
2704      // Note, we use the subexpression's type in order to retain cv-qualifiers.
2705      if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2706                                          LVal, RVal))
2707        return false;
2708      return DerivedSuccess(RVal, E);
2709    }
2710    }
2711
2712    return Error(E);
2713  }
2714
2715  /// Visit a value which is evaluated, but whose value is ignored.
2716  void VisitIgnoredValue(const Expr *E) {
2717    APValue Scratch;
2718    if (!Evaluate(Scratch, Info, E))
2719      Info.EvalStatus.HasSideEffects = true;
2720  }
2721};
2722
2723}
2724
2725//===----------------------------------------------------------------------===//
2726// Common base class for lvalue and temporary evaluation.
2727//===----------------------------------------------------------------------===//
2728namespace {
2729template<class Derived>
2730class LValueExprEvaluatorBase
2731  : public ExprEvaluatorBase<Derived, bool> {
2732protected:
2733  LValue &Result;
2734  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2735  typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2736
2737  bool Success(APValue::LValueBase B) {
2738    Result.set(B);
2739    return true;
2740  }
2741
2742public:
2743  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2744    ExprEvaluatorBaseTy(Info), Result(Result) {}
2745
2746  bool Success(const APValue &V, const Expr *E) {
2747    Result.setFrom(this->Info.Ctx, V);
2748    return true;
2749  }
2750
2751  bool VisitMemberExpr(const MemberExpr *E) {
2752    // Handle non-static data members.
2753    QualType BaseTy;
2754    if (E->isArrow()) {
2755      if (!EvaluatePointer(E->getBase(), Result, this->Info))
2756        return false;
2757      BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
2758    } else if (E->getBase()->isRValue()) {
2759      assert(E->getBase()->getType()->isRecordType());
2760      if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2761        return false;
2762      BaseTy = E->getBase()->getType();
2763    } else {
2764      if (!this->Visit(E->getBase()))
2765        return false;
2766      BaseTy = E->getBase()->getType();
2767    }
2768
2769    const ValueDecl *MD = E->getMemberDecl();
2770    if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2771      assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2772             FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2773      (void)BaseTy;
2774      HandleLValueMember(this->Info, E, Result, FD);
2775    } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2776      HandleLValueIndirectMember(this->Info, E, Result, IFD);
2777    } else
2778      return this->Error(E);
2779
2780    if (MD->getType()->isReferenceType()) {
2781      APValue RefValue;
2782      if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
2783                                          RefValue))
2784        return false;
2785      return Success(RefValue, E);
2786    }
2787    return true;
2788  }
2789
2790  bool VisitBinaryOperator(const BinaryOperator *E) {
2791    switch (E->getOpcode()) {
2792    default:
2793      return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2794
2795    case BO_PtrMemD:
2796    case BO_PtrMemI:
2797      return HandleMemberPointerAccess(this->Info, E, Result);
2798    }
2799  }
2800
2801  bool VisitCastExpr(const CastExpr *E) {
2802    switch (E->getCastKind()) {
2803    default:
2804      return ExprEvaluatorBaseTy::VisitCastExpr(E);
2805
2806    case CK_DerivedToBase:
2807    case CK_UncheckedDerivedToBase: {
2808      if (!this->Visit(E->getSubExpr()))
2809        return false;
2810
2811      // Now figure out the necessary offset to add to the base LV to get from
2812      // the derived class to the base class.
2813      QualType Type = E->getSubExpr()->getType();
2814
2815      for (CastExpr::path_const_iterator PathI = E->path_begin(),
2816           PathE = E->path_end(); PathI != PathE; ++PathI) {
2817        if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
2818                              *PathI))
2819          return false;
2820        Type = (*PathI)->getType();
2821      }
2822
2823      return true;
2824    }
2825    }
2826  }
2827};
2828}
2829
2830//===----------------------------------------------------------------------===//
2831// LValue Evaluation
2832//
2833// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2834// function designators (in C), decl references to void objects (in C), and
2835// temporaries (if building with -Wno-address-of-temporary).
2836//
2837// LValue evaluation produces values comprising a base expression of one of the
2838// following types:
2839// - Declarations
2840//  * VarDecl
2841//  * FunctionDecl
2842// - Literals
2843//  * CompoundLiteralExpr in C
2844//  * StringLiteral
2845//  * CXXTypeidExpr
2846//  * PredefinedExpr
2847//  * ObjCStringLiteralExpr
2848//  * ObjCEncodeExpr
2849//  * AddrLabelExpr
2850//  * BlockExpr
2851//  * CallExpr for a MakeStringConstant builtin
2852// - Locals and temporaries
2853//  * Any Expr, with a CallIndex indicating the function in which the temporary
2854//    was evaluated.
2855// plus an offset in bytes.
2856//===----------------------------------------------------------------------===//
2857namespace {
2858class LValueExprEvaluator
2859  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
2860public:
2861  LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2862    LValueExprEvaluatorBaseTy(Info, Result) {}
2863
2864  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2865
2866  bool VisitDeclRefExpr(const DeclRefExpr *E);
2867  bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
2868  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2869  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2870  bool VisitMemberExpr(const MemberExpr *E);
2871  bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2872  bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2873  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2874  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2875  bool VisitUnaryDeref(const UnaryOperator *E);
2876  bool VisitUnaryReal(const UnaryOperator *E);
2877  bool VisitUnaryImag(const UnaryOperator *E);
2878
2879  bool VisitCastExpr(const CastExpr *E) {
2880    switch (E->getCastKind()) {
2881    default:
2882      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2883
2884    case CK_LValueBitCast:
2885      this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2886      if (!Visit(E->getSubExpr()))
2887        return false;
2888      Result.Designator.setInvalid();
2889      return true;
2890
2891    case CK_BaseToDerived:
2892      if (!Visit(E->getSubExpr()))
2893        return false;
2894      return HandleBaseToDerivedCast(Info, E, Result);
2895    }
2896  }
2897};
2898} // end anonymous namespace
2899
2900/// Evaluate an expression as an lvalue. This can be legitimately called on
2901/// expressions which are not glvalues, in a few cases:
2902///  * function designators in C,
2903///  * "extern void" objects,
2904///  * temporaries, if building with -Wno-address-of-temporary.
2905static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
2906  assert((E->isGLValue() || E->getType()->isFunctionType() ||
2907          E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2908         "can't evaluate expression as an lvalue");
2909  return LValueExprEvaluator(Info, Result).Visit(E);
2910}
2911
2912bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2913  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2914    return Success(FD);
2915  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
2916    return VisitVarDecl(E, VD);
2917  return Error(E);
2918}
2919
2920bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
2921  if (!VD->getType()->isReferenceType()) {
2922    if (isa<ParmVarDecl>(VD)) {
2923      Result.set(VD, Info.CurrentCall->Index);
2924      return true;
2925    }
2926    return Success(VD);
2927  }
2928
2929  APValue V;
2930  if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2931    return false;
2932  return Success(V, E);
2933}
2934
2935bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2936    const MaterializeTemporaryExpr *E) {
2937  if (E->GetTemporaryExpr()->isRValue()) {
2938    if (E->getType()->isRecordType())
2939      return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2940
2941    Result.set(E, Info.CurrentCall->Index);
2942    return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2943                           Result, E->GetTemporaryExpr());
2944  }
2945
2946  // Materialization of an lvalue temporary occurs when we need to force a copy
2947  // (for instance, if it's a bitfield).
2948  // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2949  if (!Visit(E->GetTemporaryExpr()))
2950    return false;
2951  if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
2952                                      Info.CurrentCall->Temporaries[E]))
2953    return false;
2954  Result.set(E, Info.CurrentCall->Index);
2955  return true;
2956}
2957
2958bool
2959LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2960  assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2961  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2962  // only see this when folding in C, so there's no standard to follow here.
2963  return Success(E);
2964}
2965
2966bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2967  if (E->isTypeOperand())
2968    return Success(E);
2969  CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2970  if (RD && RD->isPolymorphic()) {
2971    Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2972      << E->getExprOperand()->getType()
2973      << E->getExprOperand()->getSourceRange();
2974    return false;
2975  }
2976  return Success(E);
2977}
2978
2979bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
2980  // Handle static data members.
2981  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2982    VisitIgnoredValue(E->getBase());
2983    return VisitVarDecl(E, VD);
2984  }
2985
2986  // Handle static member functions.
2987  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2988    if (MD->isStatic()) {
2989      VisitIgnoredValue(E->getBase());
2990      return Success(MD);
2991    }
2992  }
2993
2994  // Handle non-static data members.
2995  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
2996}
2997
2998bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
2999  // FIXME: Deal with vectors as array subscript bases.
3000  if (E->getBase()->getType()->isVectorType())
3001    return Error(E);
3002
3003  if (!EvaluatePointer(E->getBase(), Result, Info))
3004    return false;
3005
3006  APSInt Index;
3007  if (!EvaluateInteger(E->getIdx(), Index, Info))
3008    return false;
3009  int64_t IndexValue
3010    = Index.isSigned() ? Index.getSExtValue()
3011                       : static_cast<int64_t>(Index.getZExtValue());
3012
3013  return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
3014}
3015
3016bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
3017  return EvaluatePointer(E->getSubExpr(), Result, Info);
3018}
3019
3020bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3021  if (!Visit(E->getSubExpr()))
3022    return false;
3023  // __real is a no-op on scalar lvalues.
3024  if (E->getSubExpr()->getType()->isAnyComplexType())
3025    HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3026  return true;
3027}
3028
3029bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3030  assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3031         "lvalue __imag__ on scalar?");
3032  if (!Visit(E->getSubExpr()))
3033    return false;
3034  HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3035  return true;
3036}
3037
3038//===----------------------------------------------------------------------===//
3039// Pointer Evaluation
3040//===----------------------------------------------------------------------===//
3041
3042namespace {
3043class PointerExprEvaluator
3044  : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
3045  LValue &Result;
3046
3047  bool Success(const Expr *E) {
3048    Result.set(E);
3049    return true;
3050  }
3051public:
3052
3053  PointerExprEvaluator(EvalInfo &info, LValue &Result)
3054    : ExprEvaluatorBaseTy(info), Result(Result) {}
3055
3056  bool Success(const APValue &V, const Expr *E) {
3057    Result.setFrom(Info.Ctx, V);
3058    return true;
3059  }
3060  bool ZeroInitialization(const Expr *E) {
3061    return Success((Expr*)0);
3062  }
3063
3064  bool VisitBinaryOperator(const BinaryOperator *E);
3065  bool VisitCastExpr(const CastExpr* E);
3066  bool VisitUnaryAddrOf(const UnaryOperator *E);
3067  bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
3068      { return Success(E); }
3069  bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3070      { return Success(E); }
3071  bool VisitAddrLabelExpr(const AddrLabelExpr *E)
3072      { return Success(E); }
3073  bool VisitCallExpr(const CallExpr *E);
3074  bool VisitBlockExpr(const BlockExpr *E) {
3075    if (!E->getBlockDecl()->hasCaptures())
3076      return Success(E);
3077    return Error(E);
3078  }
3079  bool VisitCXXThisExpr(const CXXThisExpr *E) {
3080    if (!Info.CurrentCall->This)
3081      return Error(E);
3082    Result = *Info.CurrentCall->This;
3083    return true;
3084  }
3085
3086  // FIXME: Missing: @protocol, @selector
3087};
3088} // end anonymous namespace
3089
3090static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
3091  assert(E->isRValue() && E->getType()->hasPointerRepresentation());
3092  return PointerExprEvaluator(Info, Result).Visit(E);
3093}
3094
3095bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
3096  if (E->getOpcode() != BO_Add &&
3097      E->getOpcode() != BO_Sub)
3098    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3099
3100  const Expr *PExp = E->getLHS();
3101  const Expr *IExp = E->getRHS();
3102  if (IExp->getType()->isPointerType())
3103    std::swap(PExp, IExp);
3104
3105  bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3106  if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
3107    return false;
3108
3109  llvm::APSInt Offset;
3110  if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
3111    return false;
3112  int64_t AdditionalOffset
3113    = Offset.isSigned() ? Offset.getSExtValue()
3114                        : static_cast<int64_t>(Offset.getZExtValue());
3115  if (E->getOpcode() == BO_Sub)
3116    AdditionalOffset = -AdditionalOffset;
3117
3118  QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
3119  return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3120                                     AdditionalOffset);
3121}
3122
3123bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3124  return EvaluateLValue(E->getSubExpr(), Result, Info);
3125}
3126
3127bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3128  const Expr* SubExpr = E->getSubExpr();
3129
3130  switch (E->getCastKind()) {
3131  default:
3132    break;
3133
3134  case CK_BitCast:
3135  case CK_CPointerToObjCPointerCast:
3136  case CK_BlockPointerToObjCPointerCast:
3137  case CK_AnyPointerToBlockPointerCast:
3138    if (!Visit(SubExpr))
3139      return false;
3140    // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3141    // permitted in constant expressions in C++11. Bitcasts from cv void* are
3142    // also static_casts, but we disallow them as a resolution to DR1312.
3143    if (!E->getType()->isVoidPointerType()) {
3144      Result.Designator.setInvalid();
3145      if (SubExpr->getType()->isVoidPointerType())
3146        CCEDiag(E, diag::note_constexpr_invalid_cast)
3147          << 3 << SubExpr->getType();
3148      else
3149        CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3150    }
3151    return true;
3152
3153  case CK_DerivedToBase:
3154  case CK_UncheckedDerivedToBase: {
3155    if (!EvaluatePointer(E->getSubExpr(), Result, Info))
3156      return false;
3157    if (!Result.Base && Result.Offset.isZero())
3158      return true;
3159
3160    // Now figure out the necessary offset to add to the base LV to get from
3161    // the derived class to the base class.
3162    QualType Type =
3163        E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3164
3165    for (CastExpr::path_const_iterator PathI = E->path_begin(),
3166         PathE = E->path_end(); PathI != PathE; ++PathI) {
3167      if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3168                            *PathI))
3169        return false;
3170      Type = (*PathI)->getType();
3171    }
3172
3173    return true;
3174  }
3175
3176  case CK_BaseToDerived:
3177    if (!Visit(E->getSubExpr()))
3178      return false;
3179    if (!Result.Base && Result.Offset.isZero())
3180      return true;
3181    return HandleBaseToDerivedCast(Info, E, Result);
3182
3183  case CK_NullToPointer:
3184    return ZeroInitialization(E);
3185
3186  case CK_IntegralToPointer: {
3187    CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3188
3189    APValue Value;
3190    if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
3191      break;
3192
3193    if (Value.isInt()) {
3194      unsigned Size = Info.Ctx.getTypeSize(E->getType());
3195      uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
3196      Result.Base = (Expr*)0;
3197      Result.Offset = CharUnits::fromQuantity(N);
3198      Result.CallIndex = 0;
3199      Result.Designator.setInvalid();
3200      return true;
3201    } else {
3202      // Cast is of an lvalue, no need to change value.
3203      Result.setFrom(Info.Ctx, Value);
3204      return true;
3205    }
3206  }
3207  case CK_ArrayToPointerDecay:
3208    if (SubExpr->isGLValue()) {
3209      if (!EvaluateLValue(SubExpr, Result, Info))
3210        return false;
3211    } else {
3212      Result.set(SubExpr, Info.CurrentCall->Index);
3213      if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3214                           Info, Result, SubExpr))
3215        return false;
3216    }
3217    // The result is a pointer to the first element of the array.
3218    if (const ConstantArrayType *CAT
3219          = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3220      Result.addArray(Info, E, CAT);
3221    else
3222      Result.Designator.setInvalid();
3223    return true;
3224
3225  case CK_FunctionToPointerDecay:
3226    return EvaluateLValue(SubExpr, Result, Info);
3227  }
3228
3229  return ExprEvaluatorBaseTy::VisitCastExpr(E);
3230}
3231
3232bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
3233  if (IsStringLiteralCall(E))
3234    return Success(E);
3235
3236  return ExprEvaluatorBaseTy::VisitCallExpr(E);
3237}
3238
3239//===----------------------------------------------------------------------===//
3240// Member Pointer Evaluation
3241//===----------------------------------------------------------------------===//
3242
3243namespace {
3244class MemberPointerExprEvaluator
3245  : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3246  MemberPtr &Result;
3247
3248  bool Success(const ValueDecl *D) {
3249    Result = MemberPtr(D);
3250    return true;
3251  }
3252public:
3253
3254  MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3255    : ExprEvaluatorBaseTy(Info), Result(Result) {}
3256
3257  bool Success(const APValue &V, const Expr *E) {
3258    Result.setFrom(V);
3259    return true;
3260  }
3261  bool ZeroInitialization(const Expr *E) {
3262    return Success((const ValueDecl*)0);
3263  }
3264
3265  bool VisitCastExpr(const CastExpr *E);
3266  bool VisitUnaryAddrOf(const UnaryOperator *E);
3267};
3268} // end anonymous namespace
3269
3270static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3271                                  EvalInfo &Info) {
3272  assert(E->isRValue() && E->getType()->isMemberPointerType());
3273  return MemberPointerExprEvaluator(Info, Result).Visit(E);
3274}
3275
3276bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3277  switch (E->getCastKind()) {
3278  default:
3279    return ExprEvaluatorBaseTy::VisitCastExpr(E);
3280
3281  case CK_NullToMemberPointer:
3282    return ZeroInitialization(E);
3283
3284  case CK_BaseToDerivedMemberPointer: {
3285    if (!Visit(E->getSubExpr()))
3286      return false;
3287    if (E->path_empty())
3288      return true;
3289    // Base-to-derived member pointer casts store the path in derived-to-base
3290    // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3291    // the wrong end of the derived->base arc, so stagger the path by one class.
3292    typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3293    for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3294         PathI != PathE; ++PathI) {
3295      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3296      const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3297      if (!Result.castToDerived(Derived))
3298        return Error(E);
3299    }
3300    const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3301    if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
3302      return Error(E);
3303    return true;
3304  }
3305
3306  case CK_DerivedToBaseMemberPointer:
3307    if (!Visit(E->getSubExpr()))
3308      return false;
3309    for (CastExpr::path_const_iterator PathI = E->path_begin(),
3310         PathE = E->path_end(); PathI != PathE; ++PathI) {
3311      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3312      const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3313      if (!Result.castToBase(Base))
3314        return Error(E);
3315    }
3316    return true;
3317  }
3318}
3319
3320bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3321  // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3322  // member can be formed.
3323  return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3324}
3325
3326//===----------------------------------------------------------------------===//
3327// Record Evaluation
3328//===----------------------------------------------------------------------===//
3329
3330namespace {
3331  class RecordExprEvaluator
3332  : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3333    const LValue &This;
3334    APValue &Result;
3335  public:
3336
3337    RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3338      : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3339
3340    bool Success(const APValue &V, const Expr *E) {
3341      Result = V;
3342      return true;
3343    }
3344    bool ZeroInitialization(const Expr *E);
3345
3346    bool VisitCastExpr(const CastExpr *E);
3347    bool VisitInitListExpr(const InitListExpr *E);
3348    bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3349  };
3350}
3351
3352/// Perform zero-initialization on an object of non-union class type.
3353/// C++11 [dcl.init]p5:
3354///  To zero-initialize an object or reference of type T means:
3355///    [...]
3356///    -- if T is a (possibly cv-qualified) non-union class type,
3357///       each non-static data member and each base-class subobject is
3358///       zero-initialized
3359static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3360                                          const RecordDecl *RD,
3361                                          const LValue &This, APValue &Result) {
3362  assert(!RD->isUnion() && "Expected non-union class type");
3363  const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3364  Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3365                   std::distance(RD->field_begin(), RD->field_end()));
3366
3367  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3368
3369  if (CD) {
3370    unsigned Index = 0;
3371    for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
3372           End = CD->bases_end(); I != End; ++I, ++Index) {
3373      const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3374      LValue Subobject = This;
3375      HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3376      if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
3377                                         Result.getStructBase(Index)))
3378        return false;
3379    }
3380  }
3381
3382  for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3383       I != End; ++I) {
3384    // -- if T is a reference type, no initialization is performed.
3385    if ((*I)->getType()->isReferenceType())
3386      continue;
3387
3388    LValue Subobject = This;
3389    HandleLValueMember(Info, E, Subobject, *I, &Layout);
3390
3391    ImplicitValueInitExpr VIE((*I)->getType());
3392    if (!EvaluateInPlace(
3393          Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3394      return false;
3395  }
3396
3397  return true;
3398}
3399
3400bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3401  const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3402  if (RD->isUnion()) {
3403    // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3404    // object's first non-static named data member is zero-initialized
3405    RecordDecl::field_iterator I = RD->field_begin();
3406    if (I == RD->field_end()) {
3407      Result = APValue((const FieldDecl*)0);
3408      return true;
3409    }
3410
3411    LValue Subobject = This;
3412    HandleLValueMember(Info, E, Subobject, *I);
3413    Result = APValue(*I);
3414    ImplicitValueInitExpr VIE((*I)->getType());
3415    return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
3416  }
3417
3418  if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3419    Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
3420    return false;
3421  }
3422
3423  return HandleClassZeroInitialization(Info, E, RD, This, Result);
3424}
3425
3426bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3427  switch (E->getCastKind()) {
3428  default:
3429    return ExprEvaluatorBaseTy::VisitCastExpr(E);
3430
3431  case CK_ConstructorConversion:
3432    return Visit(E->getSubExpr());
3433
3434  case CK_DerivedToBase:
3435  case CK_UncheckedDerivedToBase: {
3436    APValue DerivedObject;
3437    if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
3438      return false;
3439    if (!DerivedObject.isStruct())
3440      return Error(E->getSubExpr());
3441
3442    // Derived-to-base rvalue conversion: just slice off the derived part.
3443    APValue *Value = &DerivedObject;
3444    const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3445    for (CastExpr::path_const_iterator PathI = E->path_begin(),
3446         PathE = E->path_end(); PathI != PathE; ++PathI) {
3447      assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3448      const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3449      Value = &Value->getStructBase(getBaseIndex(RD, Base));
3450      RD = Base;
3451    }
3452    Result = *Value;
3453    return true;
3454  }
3455  }
3456}
3457
3458bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3459  // Cannot constant-evaluate std::initializer_list inits.
3460  if (E->initializesStdInitializerList())
3461    return false;
3462
3463  const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3464  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3465
3466  if (RD->isUnion()) {
3467    const FieldDecl *Field = E->getInitializedFieldInUnion();
3468    Result = APValue(Field);
3469    if (!Field)
3470      return true;
3471
3472    // If the initializer list for a union does not contain any elements, the
3473    // first element of the union is value-initialized.
3474    ImplicitValueInitExpr VIE(Field->getType());
3475    const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3476
3477    LValue Subobject = This;
3478    HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
3479    return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
3480  }
3481
3482  assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3483         "initializer list for class with base classes");
3484  Result = APValue(APValue::UninitStruct(), 0,
3485                   std::distance(RD->field_begin(), RD->field_end()));
3486  unsigned ElementNo = 0;
3487  bool Success = true;
3488  for (RecordDecl::field_iterator Field = RD->field_begin(),
3489       FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3490    // Anonymous bit-fields are not considered members of the class for
3491    // purposes of aggregate initialization.
3492    if (Field->isUnnamedBitfield())
3493      continue;
3494
3495    LValue Subobject = This;
3496
3497    bool HaveInit = ElementNo < E->getNumInits();
3498
3499    // FIXME: Diagnostics here should point to the end of the initializer
3500    // list, not the start.
3501    HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3502                       *Field, &Layout);
3503
3504    // Perform an implicit value-initialization for members beyond the end of
3505    // the initializer list.
3506    ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3507
3508    if (!EvaluateInPlace(
3509          Result.getStructField((*Field)->getFieldIndex()),
3510          Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3511      if (!Info.keepEvaluatingAfterFailure())
3512        return false;
3513      Success = false;
3514    }
3515  }
3516
3517  return Success;
3518}
3519
3520bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3521  const CXXConstructorDecl *FD = E->getConstructor();
3522  bool ZeroInit = E->requiresZeroInitialization();
3523  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3524    // If we've already performed zero-initialization, we're already done.
3525    if (!Result.isUninit())
3526      return true;
3527
3528    if (ZeroInit)
3529      return ZeroInitialization(E);
3530
3531    const CXXRecordDecl *RD = FD->getParent();
3532    if (RD->isUnion())
3533      Result = APValue((FieldDecl*)0);
3534    else
3535      Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3536                       std::distance(RD->field_begin(), RD->field_end()));
3537    return true;
3538  }
3539
3540  const FunctionDecl *Definition = 0;
3541  FD->getBody(Definition);
3542
3543  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3544    return false;
3545
3546  // Avoid materializing a temporary for an elidable copy/move constructor.
3547  if (E->isElidable() && !ZeroInit)
3548    if (const MaterializeTemporaryExpr *ME
3549          = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3550      return Visit(ME->GetTemporaryExpr());
3551
3552  if (ZeroInit && !ZeroInitialization(E))
3553    return false;
3554
3555  llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3556  return HandleConstructorCall(E->getExprLoc(), This, Args,
3557                               cast<CXXConstructorDecl>(Definition), Info,
3558                               Result);
3559}
3560
3561static bool EvaluateRecord(const Expr *E, const LValue &This,
3562                           APValue &Result, EvalInfo &Info) {
3563  assert(E->isRValue() && E->getType()->isRecordType() &&
3564         "can't evaluate expression as a record rvalue");
3565  return RecordExprEvaluator(Info, This, Result).Visit(E);
3566}
3567
3568//===----------------------------------------------------------------------===//
3569// Temporary Evaluation
3570//
3571// Temporaries are represented in the AST as rvalues, but generally behave like
3572// lvalues. The full-object of which the temporary is a subobject is implicitly
3573// materialized so that a reference can bind to it.
3574//===----------------------------------------------------------------------===//
3575namespace {
3576class TemporaryExprEvaluator
3577  : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3578public:
3579  TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3580    LValueExprEvaluatorBaseTy(Info, Result) {}
3581
3582  /// Visit an expression which constructs the value of this temporary.
3583  bool VisitConstructExpr(const Expr *E) {
3584    Result.set(E, Info.CurrentCall->Index);
3585    return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
3586  }
3587
3588  bool VisitCastExpr(const CastExpr *E) {
3589    switch (E->getCastKind()) {
3590    default:
3591      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3592
3593    case CK_ConstructorConversion:
3594      return VisitConstructExpr(E->getSubExpr());
3595    }
3596  }
3597  bool VisitInitListExpr(const InitListExpr *E) {
3598    return VisitConstructExpr(E);
3599  }
3600  bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3601    return VisitConstructExpr(E);
3602  }
3603  bool VisitCallExpr(const CallExpr *E) {
3604    return VisitConstructExpr(E);
3605  }
3606};
3607} // end anonymous namespace
3608
3609/// Evaluate an expression of record type as a temporary.
3610static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
3611  assert(E->isRValue() && E->getType()->isRecordType());
3612  return TemporaryExprEvaluator(Info, Result).Visit(E);
3613}
3614
3615//===----------------------------------------------------------------------===//
3616// Vector Evaluation
3617//===----------------------------------------------------------------------===//
3618
3619namespace {
3620  class VectorExprEvaluator
3621  : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3622    APValue &Result;
3623  public:
3624
3625    VectorExprEvaluator(EvalInfo &info, APValue &Result)
3626      : ExprEvaluatorBaseTy(info), Result(Result) {}
3627
3628    bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3629      assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3630      // FIXME: remove this APValue copy.
3631      Result = APValue(V.data(), V.size());
3632      return true;
3633    }
3634    bool Success(const APValue &V, const Expr *E) {
3635      assert(V.isVector());
3636      Result = V;
3637      return true;
3638    }
3639    bool ZeroInitialization(const Expr *E);
3640
3641    bool VisitUnaryReal(const UnaryOperator *E)
3642      { return Visit(E->getSubExpr()); }
3643    bool VisitCastExpr(const CastExpr* E);
3644    bool VisitInitListExpr(const InitListExpr *E);
3645    bool VisitUnaryImag(const UnaryOperator *E);
3646    // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
3647    //                 binary comparisons, binary and/or/xor,
3648    //                 shufflevector, ExtVectorElementExpr
3649  };
3650} // end anonymous namespace
3651
3652static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
3653  assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
3654  return VectorExprEvaluator(Info, Result).Visit(E);
3655}
3656
3657bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3658  const VectorType *VTy = E->getType()->castAs<VectorType>();
3659  unsigned NElts = VTy->getNumElements();
3660
3661  const Expr *SE = E->getSubExpr();
3662  QualType SETy = SE->getType();
3663
3664  switch (E->getCastKind()) {
3665  case CK_VectorSplat: {
3666    APValue Val = APValue();
3667    if (SETy->isIntegerType()) {
3668      APSInt IntResult;
3669      if (!EvaluateInteger(SE, IntResult, Info))
3670         return false;
3671      Val = APValue(IntResult);
3672    } else if (SETy->isRealFloatingType()) {
3673       APFloat F(0.0);
3674       if (!EvaluateFloat(SE, F, Info))
3675         return false;
3676       Val = APValue(F);
3677    } else {
3678      return Error(E);
3679    }
3680
3681    // Splat and create vector APValue.
3682    SmallVector<APValue, 4> Elts(NElts, Val);
3683    return Success(Elts, E);
3684  }
3685  case CK_BitCast: {
3686    // Evaluate the operand into an APInt we can extract from.
3687    llvm::APInt SValInt;
3688    if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3689      return false;
3690    // Extract the elements
3691    QualType EltTy = VTy->getElementType();
3692    unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3693    bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3694    SmallVector<APValue, 4> Elts;
3695    if (EltTy->isRealFloatingType()) {
3696      const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3697      bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3698      unsigned FloatEltSize = EltSize;
3699      if (&Sem == &APFloat::x87DoubleExtended)
3700        FloatEltSize = 80;
3701      for (unsigned i = 0; i < NElts; i++) {
3702        llvm::APInt Elt;
3703        if (BigEndian)
3704          Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3705        else
3706          Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3707        Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3708      }
3709    } else if (EltTy->isIntegerType()) {
3710      for (unsigned i = 0; i < NElts; i++) {
3711        llvm::APInt Elt;
3712        if (BigEndian)
3713          Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3714        else
3715          Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3716        Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3717      }
3718    } else {
3719      return Error(E);
3720    }
3721    return Success(Elts, E);
3722  }
3723  default:
3724    return ExprEvaluatorBaseTy::VisitCastExpr(E);
3725  }
3726}
3727
3728bool
3729VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3730  const VectorType *VT = E->getType()->castAs<VectorType>();
3731  unsigned NumInits = E->getNumInits();
3732  unsigned NumElements = VT->getNumElements();
3733
3734  QualType EltTy = VT->getElementType();
3735  SmallVector<APValue, 4> Elements;
3736
3737  // The number of initializers can be less than the number of
3738  // vector elements. For OpenCL, this can be due to nested vector
3739  // initialization. For GCC compatibility, missing trailing elements
3740  // should be initialized with zeroes.
3741  unsigned CountInits = 0, CountElts = 0;
3742  while (CountElts < NumElements) {
3743    // Handle nested vector initialization.
3744    if (CountInits < NumInits
3745        && E->getInit(CountInits)->getType()->isExtVectorType()) {
3746      APValue v;
3747      if (!EvaluateVector(E->getInit(CountInits), v, Info))
3748        return Error(E);
3749      unsigned vlen = v.getVectorLength();
3750      for (unsigned j = 0; j < vlen; j++)
3751        Elements.push_back(v.getVectorElt(j));
3752      CountElts += vlen;
3753    } else if (EltTy->isIntegerType()) {
3754      llvm::APSInt sInt(32);
3755      if (CountInits < NumInits) {
3756        if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3757          return false;
3758      } else // trailing integer zero.
3759        sInt = Info.Ctx.MakeIntValue(0, EltTy);
3760      Elements.push_back(APValue(sInt));
3761      CountElts++;
3762    } else {
3763      llvm::APFloat f(0.0);
3764      if (CountInits < NumInits) {
3765        if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3766          return false;
3767      } else // trailing float zero.
3768        f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3769      Elements.push_back(APValue(f));
3770      CountElts++;
3771    }
3772    CountInits++;
3773  }
3774  return Success(Elements, E);
3775}
3776
3777bool
3778VectorExprEvaluator::ZeroInitialization(const Expr *E) {
3779  const VectorType *VT = E->getType()->getAs<VectorType>();
3780  QualType EltTy = VT->getElementType();
3781  APValue ZeroElement;
3782  if (EltTy->isIntegerType())
3783    ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3784  else
3785    ZeroElement =
3786        APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3787
3788  SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
3789  return Success(Elements, E);
3790}
3791
3792bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3793  VisitIgnoredValue(E->getSubExpr());
3794  return ZeroInitialization(E);
3795}
3796
3797//===----------------------------------------------------------------------===//
3798// Array Evaluation
3799//===----------------------------------------------------------------------===//
3800
3801namespace {
3802  class ArrayExprEvaluator
3803  : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
3804    const LValue &This;
3805    APValue &Result;
3806  public:
3807
3808    ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3809      : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
3810
3811    bool Success(const APValue &V, const Expr *E) {
3812      assert((V.isArray() || V.isLValue()) &&
3813             "expected array or string literal");
3814      Result = V;
3815      return true;
3816    }
3817
3818    bool ZeroInitialization(const Expr *E) {
3819      const ConstantArrayType *CAT =
3820          Info.Ctx.getAsConstantArrayType(E->getType());
3821      if (!CAT)
3822        return Error(E);
3823
3824      Result = APValue(APValue::UninitArray(), 0,
3825                       CAT->getSize().getZExtValue());
3826      if (!Result.hasArrayFiller()) return true;
3827
3828      // Zero-initialize all elements.
3829      LValue Subobject = This;
3830      Subobject.addArray(Info, E, CAT);
3831      ImplicitValueInitExpr VIE(CAT->getElementType());
3832      return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
3833    }
3834
3835    bool VisitInitListExpr(const InitListExpr *E);
3836    bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3837  };
3838} // end anonymous namespace
3839
3840static bool EvaluateArray(const Expr *E, const LValue &This,
3841                          APValue &Result, EvalInfo &Info) {
3842  assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
3843  return ArrayExprEvaluator(Info, This, Result).Visit(E);
3844}
3845
3846bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3847  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3848  if (!CAT)
3849    return Error(E);
3850
3851  // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3852  // an appropriately-typed string literal enclosed in braces.
3853  if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
3854      Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3855    LValue LV;
3856    if (!EvaluateLValue(E->getInit(0), LV, Info))
3857      return false;
3858    APValue Val;
3859    LV.moveInto(Val);
3860    return Success(Val, E);
3861  }
3862
3863  bool Success = true;
3864
3865  Result = APValue(APValue::UninitArray(), E->getNumInits(),
3866                   CAT->getSize().getZExtValue());
3867  LValue Subobject = This;
3868  Subobject.addArray(Info, E, CAT);
3869  unsigned Index = 0;
3870  for (InitListExpr::const_iterator I = E->begin(), End = E->end();
3871       I != End; ++I, ++Index) {
3872    if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3873                         Info, Subobject, cast<Expr>(*I)) ||
3874        !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3875                                     CAT->getElementType(), 1)) {
3876      if (!Info.keepEvaluatingAfterFailure())
3877        return false;
3878      Success = false;
3879    }
3880  }
3881
3882  if (!Result.hasArrayFiller()) return Success;
3883  assert(E->hasArrayFiller() && "no array filler for incomplete init list");
3884  // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3885  // but sometimes does:
3886  //   struct S { constexpr S() : p(&p) {} void *p; };
3887  //   S s[10] = {};
3888  return EvaluateInPlace(Result.getArrayFiller(), Info,
3889                         Subobject, E->getArrayFiller()) && Success;
3890}
3891
3892bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3893  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3894  if (!CAT)
3895    return Error(E);
3896
3897  bool HadZeroInit = !Result.isUninit();
3898  if (!HadZeroInit)
3899    Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3900  if (!Result.hasArrayFiller())
3901    return true;
3902
3903  const CXXConstructorDecl *FD = E->getConstructor();
3904
3905  bool ZeroInit = E->requiresZeroInitialization();
3906  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3907    if (HadZeroInit)
3908      return true;
3909
3910    if (ZeroInit) {
3911      LValue Subobject = This;
3912      Subobject.addArray(Info, E, CAT);
3913      ImplicitValueInitExpr VIE(CAT->getElementType());
3914      return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
3915    }
3916
3917    const CXXRecordDecl *RD = FD->getParent();
3918    if (RD->isUnion())
3919      Result.getArrayFiller() = APValue((FieldDecl*)0);
3920    else
3921      Result.getArrayFiller() =
3922          APValue(APValue::UninitStruct(), RD->getNumBases(),
3923                  std::distance(RD->field_begin(), RD->field_end()));
3924    return true;
3925  }
3926
3927  const FunctionDecl *Definition = 0;
3928  FD->getBody(Definition);
3929
3930  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3931    return false;
3932
3933  // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3934  // but sometimes does:
3935  //   struct S { constexpr S() : p(&p) {} void *p; };
3936  //   S s[10];
3937  LValue Subobject = This;
3938  Subobject.addArray(Info, E, CAT);
3939
3940  if (ZeroInit && !HadZeroInit) {
3941    ImplicitValueInitExpr VIE(CAT->getElementType());
3942    if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
3943      return false;
3944  }
3945
3946  llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3947  return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
3948                               cast<CXXConstructorDecl>(Definition),
3949                               Info, Result.getArrayFiller());
3950}
3951
3952//===----------------------------------------------------------------------===//
3953// Integer Evaluation
3954//
3955// As a GNU extension, we support casting pointers to sufficiently-wide integer
3956// types and back in constant folding. Integer values are thus represented
3957// either as an integer-valued APValue, or as an lvalue-valued APValue.
3958//===----------------------------------------------------------------------===//
3959
3960namespace {
3961class IntExprEvaluator
3962  : public ExprEvaluatorBase<IntExprEvaluator, bool> {
3963  APValue &Result;
3964public:
3965  IntExprEvaluator(EvalInfo &info, APValue &result)
3966    : ExprEvaluatorBaseTy(info), Result(result) {}
3967
3968  bool Success(const llvm::APSInt &SI, const Expr *E) {
3969    assert(E->getType()->isIntegralOrEnumerationType() &&
3970           "Invalid evaluation result.");
3971    assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
3972           "Invalid evaluation result.");
3973    assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3974           "Invalid evaluation result.");
3975    Result = APValue(SI);
3976    return true;
3977  }
3978
3979  bool Success(const llvm::APInt &I, const Expr *E) {
3980    assert(E->getType()->isIntegralOrEnumerationType() &&
3981           "Invalid evaluation result.");
3982    assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3983           "Invalid evaluation result.");
3984    Result = APValue(APSInt(I));
3985    Result.getInt().setIsUnsigned(
3986                            E->getType()->isUnsignedIntegerOrEnumerationType());
3987    return true;
3988  }
3989
3990  bool Success(uint64_t Value, const Expr *E) {
3991    assert(E->getType()->isIntegralOrEnumerationType() &&
3992           "Invalid evaluation result.");
3993    Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
3994    return true;
3995  }
3996
3997  bool Success(CharUnits Size, const Expr *E) {
3998    return Success(Size.getQuantity(), E);
3999  }
4000
4001  bool Success(const APValue &V, const Expr *E) {
4002    if (V.isLValue() || V.isAddrLabelDiff()) {
4003      Result = V;
4004      return true;
4005    }
4006    return Success(V.getInt(), E);
4007  }
4008
4009  bool ZeroInitialization(const Expr *E) { return Success(0, E); }
4010
4011  // FIXME: See EvalInfo::IntExprEvaluatorDepth.
4012  bool Visit(const Expr *E) {
4013    SaveAndRestore<unsigned> Depth(Info.IntExprEvaluatorDepth,
4014                                   Info.IntExprEvaluatorDepth+1);
4015    const unsigned MaxDepth = 512;
4016    if (Depth.get() > MaxDepth) {
4017      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4018                                       diag::err_intexpr_depth_limit_exceeded);
4019      return false;
4020    }
4021
4022    return ExprEvaluatorBaseTy::Visit(E);
4023  }
4024
4025  //===--------------------------------------------------------------------===//
4026  //                            Visitor Methods
4027  //===--------------------------------------------------------------------===//
4028
4029  bool VisitIntegerLiteral(const IntegerLiteral *E) {
4030    return Success(E->getValue(), E);
4031  }
4032  bool VisitCharacterLiteral(const CharacterLiteral *E) {
4033    return Success(E->getValue(), E);
4034  }
4035
4036  bool CheckReferencedDecl(const Expr *E, const Decl *D);
4037  bool VisitDeclRefExpr(const DeclRefExpr *E) {
4038    if (CheckReferencedDecl(E, E->getDecl()))
4039      return true;
4040
4041    return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
4042  }
4043  bool VisitMemberExpr(const MemberExpr *E) {
4044    if (CheckReferencedDecl(E, E->getMemberDecl())) {
4045      VisitIgnoredValue(E->getBase());
4046      return true;
4047    }
4048
4049    return ExprEvaluatorBaseTy::VisitMemberExpr(E);
4050  }
4051
4052  bool VisitCallExpr(const CallExpr *E);
4053  bool VisitBinaryOperator(const BinaryOperator *E);
4054  bool VisitOffsetOfExpr(const OffsetOfExpr *E);
4055  bool VisitUnaryOperator(const UnaryOperator *E);
4056
4057  bool VisitCastExpr(const CastExpr* E);
4058  bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
4059
4060  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
4061    return Success(E->getValue(), E);
4062  }
4063
4064  bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4065    return Success(E->getValue(), E);
4066  }
4067
4068  // Note, GNU defines __null as an integer, not a pointer.
4069  bool VisitGNUNullExpr(const GNUNullExpr *E) {
4070    return ZeroInitialization(E);
4071  }
4072
4073  bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
4074    return Success(E->getValue(), E);
4075  }
4076
4077  bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4078    return Success(E->getValue(), E);
4079  }
4080
4081  bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4082    return Success(E->getValue(), E);
4083  }
4084
4085  bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4086    return Success(E->getValue(), E);
4087  }
4088
4089  bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4090    return Success(E->getValue(), E);
4091  }
4092
4093  bool VisitUnaryReal(const UnaryOperator *E);
4094  bool VisitUnaryImag(const UnaryOperator *E);
4095
4096  bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
4097  bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
4098
4099private:
4100  CharUnits GetAlignOfExpr(const Expr *E);
4101  CharUnits GetAlignOfType(QualType T);
4102  static QualType GetObjectType(APValue::LValueBase B);
4103  bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
4104  // FIXME: Missing: array subscript of vector, member of vector
4105};
4106} // end anonymous namespace
4107
4108/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4109/// produce either the integer value or a pointer.
4110///
4111/// GCC has a heinous extension which folds casts between pointer types and
4112/// pointer-sized integral types. We support this by allowing the evaluation of
4113/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4114/// Some simple arithmetic on such values is supported (they are treated much
4115/// like char*).
4116static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
4117                                    EvalInfo &Info) {
4118  assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
4119  return IntExprEvaluator(Info, Result).Visit(E);
4120}
4121
4122static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
4123  APValue Val;
4124  if (!EvaluateIntegerOrLValue(E, Val, Info))
4125    return false;
4126  if (!Val.isInt()) {
4127    // FIXME: It would be better to produce the diagnostic for casting
4128    //        a pointer to an integer.
4129    Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
4130    return false;
4131  }
4132  Result = Val.getInt();
4133  return true;
4134}
4135
4136/// Check whether the given declaration can be directly converted to an integral
4137/// rvalue. If not, no diagnostic is produced; there are other things we can
4138/// try.
4139bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
4140  // Enums are integer constant exprs.
4141  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
4142    // Check for signedness/width mismatches between E type and ECD value.
4143    bool SameSign = (ECD->getInitVal().isSigned()
4144                     == E->getType()->isSignedIntegerOrEnumerationType());
4145    bool SameWidth = (ECD->getInitVal().getBitWidth()
4146                      == Info.Ctx.getIntWidth(E->getType()));
4147    if (SameSign && SameWidth)
4148      return Success(ECD->getInitVal(), E);
4149    else {
4150      // Get rid of mismatch (otherwise Success assertions will fail)
4151      // by computing a new value matching the type of E.
4152      llvm::APSInt Val = ECD->getInitVal();
4153      if (!SameSign)
4154        Val.setIsSigned(!ECD->getInitVal().isSigned());
4155      if (!SameWidth)
4156        Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4157      return Success(Val, E);
4158    }
4159  }
4160  return false;
4161}
4162
4163/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4164/// as GCC.
4165static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4166  // The following enum mimics the values returned by GCC.
4167  // FIXME: Does GCC differ between lvalue and rvalue references here?
4168  enum gcc_type_class {
4169    no_type_class = -1,
4170    void_type_class, integer_type_class, char_type_class,
4171    enumeral_type_class, boolean_type_class,
4172    pointer_type_class, reference_type_class, offset_type_class,
4173    real_type_class, complex_type_class,
4174    function_type_class, method_type_class,
4175    record_type_class, union_type_class,
4176    array_type_class, string_type_class,
4177    lang_type_class
4178  };
4179
4180  // If no argument was supplied, default to "no_type_class". This isn't
4181  // ideal, however it is what gcc does.
4182  if (E->getNumArgs() == 0)
4183    return no_type_class;
4184
4185  QualType ArgTy = E->getArg(0)->getType();
4186  if (ArgTy->isVoidType())
4187    return void_type_class;
4188  else if (ArgTy->isEnumeralType())
4189    return enumeral_type_class;
4190  else if (ArgTy->isBooleanType())
4191    return boolean_type_class;
4192  else if (ArgTy->isCharType())
4193    return string_type_class; // gcc doesn't appear to use char_type_class
4194  else if (ArgTy->isIntegerType())
4195    return integer_type_class;
4196  else if (ArgTy->isPointerType())
4197    return pointer_type_class;
4198  else if (ArgTy->isReferenceType())
4199    return reference_type_class;
4200  else if (ArgTy->isRealType())
4201    return real_type_class;
4202  else if (ArgTy->isComplexType())
4203    return complex_type_class;
4204  else if (ArgTy->isFunctionType())
4205    return function_type_class;
4206  else if (ArgTy->isStructureOrClassType())
4207    return record_type_class;
4208  else if (ArgTy->isUnionType())
4209    return union_type_class;
4210  else if (ArgTy->isArrayType())
4211    return array_type_class;
4212  else if (ArgTy->isUnionType())
4213    return union_type_class;
4214  else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
4215    llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
4216}
4217
4218/// EvaluateBuiltinConstantPForLValue - Determine the result of
4219/// __builtin_constant_p when applied to the given lvalue.
4220///
4221/// An lvalue is only "constant" if it is a pointer or reference to the first
4222/// character of a string literal.
4223template<typename LValue>
4224static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4225  const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
4226  return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4227}
4228
4229/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4230/// GCC as we can manage.
4231static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4232  QualType ArgType = Arg->getType();
4233
4234  // __builtin_constant_p always has one operand. The rules which gcc follows
4235  // are not precisely documented, but are as follows:
4236  //
4237  //  - If the operand is of integral, floating, complex or enumeration type,
4238  //    and can be folded to a known value of that type, it returns 1.
4239  //  - If the operand and can be folded to a pointer to the first character
4240  //    of a string literal (or such a pointer cast to an integral type), it
4241  //    returns 1.
4242  //
4243  // Otherwise, it returns 0.
4244  //
4245  // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4246  // its support for this does not currently work.
4247  if (ArgType->isIntegralOrEnumerationType()) {
4248    Expr::EvalResult Result;
4249    if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4250      return false;
4251
4252    APValue &V = Result.Val;
4253    if (V.getKind() == APValue::Int)
4254      return true;
4255
4256    return EvaluateBuiltinConstantPForLValue(V);
4257  } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4258    return Arg->isEvaluatable(Ctx);
4259  } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4260    LValue LV;
4261    Expr::EvalStatus Status;
4262    EvalInfo Info(Ctx, Status);
4263    if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4264                          : EvaluatePointer(Arg, LV, Info)) &&
4265        !Status.HasSideEffects)
4266      return EvaluateBuiltinConstantPForLValue(LV);
4267  }
4268
4269  // Anything else isn't considered to be sufficiently constant.
4270  return false;
4271}
4272
4273/// Retrieves the "underlying object type" of the given expression,
4274/// as used by __builtin_object_size.
4275QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4276  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4277    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4278      return VD->getType();
4279  } else if (const Expr *E = B.get<const Expr*>()) {
4280    if (isa<CompoundLiteralExpr>(E))
4281      return E->getType();
4282  }
4283
4284  return QualType();
4285}
4286
4287bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
4288  // TODO: Perhaps we should let LLVM lower this?
4289  LValue Base;
4290  if (!EvaluatePointer(E->getArg(0), Base, Info))
4291    return false;
4292
4293  // If we can prove the base is null, lower to zero now.
4294  if (!Base.getLValueBase()) return Success(0, E);
4295
4296  QualType T = GetObjectType(Base.getLValueBase());
4297  if (T.isNull() ||
4298      T->isIncompleteType() ||
4299      T->isFunctionType() ||
4300      T->isVariablyModifiedType() ||
4301      T->isDependentType())
4302    return Error(E);
4303
4304  CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4305  CharUnits Offset = Base.getLValueOffset();
4306
4307  if (!Offset.isNegative() && Offset <= Size)
4308    Size -= Offset;
4309  else
4310    Size = CharUnits::Zero();
4311  return Success(Size, E);
4312}
4313
4314bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
4315  switch (E->isBuiltinCall()) {
4316  default:
4317    return ExprEvaluatorBaseTy::VisitCallExpr(E);
4318
4319  case Builtin::BI__builtin_object_size: {
4320    if (TryEvaluateBuiltinObjectSize(E))
4321      return true;
4322
4323    // If evaluating the argument has side-effects we can't determine
4324    // the size of the object and lower it to unknown now.
4325    if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
4326      if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
4327        return Success(-1ULL, E);
4328      return Success(0, E);
4329    }
4330
4331    return Error(E);
4332  }
4333
4334  case Builtin::BI__builtin_classify_type:
4335    return Success(EvaluateBuiltinClassifyType(E), E);
4336
4337  case Builtin::BI__builtin_constant_p:
4338    return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
4339
4340  case Builtin::BI__builtin_eh_return_data_regno: {
4341    int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
4342    Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
4343    return Success(Operand, E);
4344  }
4345
4346  case Builtin::BI__builtin_expect:
4347    return Visit(E->getArg(0));
4348
4349  case Builtin::BIstrlen:
4350    // A call to strlen is not a constant expression.
4351    if (Info.getLangOpts().CPlusPlus0x)
4352      Info.CCEDiag(E, diag::note_constexpr_invalid_function)
4353        << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4354    else
4355      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
4356    // Fall through.
4357  case Builtin::BI__builtin_strlen:
4358    // As an extension, we support strlen() and __builtin_strlen() as constant
4359    // expressions when the argument is a string literal.
4360    if (const StringLiteral *S
4361               = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4362      // The string literal may have embedded null characters. Find the first
4363      // one and truncate there.
4364      StringRef Str = S->getString();
4365      StringRef::size_type Pos = Str.find(0);
4366      if (Pos != StringRef::npos)
4367        Str = Str.substr(0, Pos);
4368
4369      return Success(Str.size(), E);
4370    }
4371
4372    return Error(E);
4373
4374  case Builtin::BI__atomic_is_lock_free: {
4375    APSInt SizeVal;
4376    if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4377      return false;
4378
4379    // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4380    // of two less than the maximum inline atomic width, we know it is
4381    // lock-free.  If the size isn't a power of two, or greater than the
4382    // maximum alignment where we promote atomics, we know it is not lock-free
4383    // (at least not in the sense of atomic_is_lock_free).  Otherwise,
4384    // the answer can only be determined at runtime; for example, 16-byte
4385    // atomics have lock-free implementations on some, but not all,
4386    // x86-64 processors.
4387
4388    // Check power-of-two.
4389    CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4390    if (!Size.isPowerOfTwo())
4391#if 0
4392      // FIXME: Suppress this folding until the ABI for the promotion width
4393      // settles.
4394      return Success(0, E);
4395#else
4396      return Error(E);
4397#endif
4398
4399#if 0
4400    // Check against promotion width.
4401    // FIXME: Suppress this folding until the ABI for the promotion width
4402    // settles.
4403    unsigned PromoteWidthBits =
4404        Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4405    if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4406      return Success(0, E);
4407#endif
4408
4409    // Check against inlining width.
4410    unsigned InlineWidthBits =
4411        Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4412    if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4413      return Success(1, E);
4414
4415    return Error(E);
4416  }
4417  }
4418}
4419
4420static bool HasSameBase(const LValue &A, const LValue &B) {
4421  if (!A.getLValueBase())
4422    return !B.getLValueBase();
4423  if (!B.getLValueBase())
4424    return false;
4425
4426  if (A.getLValueBase().getOpaqueValue() !=
4427      B.getLValueBase().getOpaqueValue()) {
4428    const Decl *ADecl = GetLValueBaseDecl(A);
4429    if (!ADecl)
4430      return false;
4431    const Decl *BDecl = GetLValueBaseDecl(B);
4432    if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
4433      return false;
4434  }
4435
4436  return IsGlobalLValue(A.getLValueBase()) ||
4437         A.getLValueCallIndex() == B.getLValueCallIndex();
4438}
4439
4440/// Perform the given integer operation, which is known to need at most BitWidth
4441/// bits, and check for overflow in the original type (if that type was not an
4442/// unsigned type).
4443template<typename Operation>
4444static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4445                                   const APSInt &LHS, const APSInt &RHS,
4446                                   unsigned BitWidth, Operation Op) {
4447  if (LHS.isUnsigned())
4448    return Op(LHS, RHS);
4449
4450  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4451  APSInt Result = Value.trunc(LHS.getBitWidth());
4452  if (Result.extend(BitWidth) != Value)
4453    HandleOverflow(Info, E, Value, E->getType());
4454  return Result;
4455}
4456
4457bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4458  if (E->isAssignmentOp())
4459    return Error(E);
4460
4461  if (E->getOpcode() == BO_Comma) {
4462    VisitIgnoredValue(E->getLHS());
4463    return Visit(E->getRHS());
4464  }
4465
4466  if (E->isLogicalOp()) {
4467    // These need to be handled specially because the operands aren't
4468    // necessarily integral nor evaluated.
4469    bool lhsResult, rhsResult;
4470
4471    if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
4472      // We were able to evaluate the LHS, see if we can get away with not
4473      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4474      if (lhsResult == (E->getOpcode() == BO_LOr))
4475        return Success(lhsResult, E);
4476
4477      if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4478        if (E->getOpcode() == BO_LOr)
4479          return Success(lhsResult || rhsResult, E);
4480        else
4481          return Success(lhsResult && rhsResult, E);
4482      }
4483    } else {
4484      // Since we weren't able to evaluate the left hand side, it
4485      // must have had side effects.
4486      Info.EvalStatus.HasSideEffects = true;
4487
4488      // Suppress diagnostics from this arm.
4489      SpeculativeEvaluationRAII Speculative(Info);
4490      if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4491        // We can't evaluate the LHS; however, sometimes the result
4492        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4493        if (rhsResult == (E->getOpcode() == BO_LOr))
4494          return Success(rhsResult, E);
4495      }
4496    }
4497
4498    return false;
4499  }
4500
4501  QualType LHSTy = E->getLHS()->getType();
4502  QualType RHSTy = E->getRHS()->getType();
4503
4504  if (LHSTy->isAnyComplexType()) {
4505    assert(RHSTy->isAnyComplexType() && "Invalid comparison");
4506    ComplexValue LHS, RHS;
4507
4508    bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4509    if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4510      return false;
4511
4512    if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
4513      return false;
4514
4515    if (LHS.isComplexFloat()) {
4516      APFloat::cmpResult CR_r =
4517        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
4518      APFloat::cmpResult CR_i =
4519        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4520
4521      if (E->getOpcode() == BO_EQ)
4522        return Success((CR_r == APFloat::cmpEqual &&
4523                        CR_i == APFloat::cmpEqual), E);
4524      else {
4525        assert(E->getOpcode() == BO_NE &&
4526               "Invalid complex comparison.");
4527        return Success(((CR_r == APFloat::cmpGreaterThan ||
4528                         CR_r == APFloat::cmpLessThan ||
4529                         CR_r == APFloat::cmpUnordered) ||
4530                        (CR_i == APFloat::cmpGreaterThan ||
4531                         CR_i == APFloat::cmpLessThan ||
4532                         CR_i == APFloat::cmpUnordered)), E);
4533      }
4534    } else {
4535      if (E->getOpcode() == BO_EQ)
4536        return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4537                        LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4538      else {
4539        assert(E->getOpcode() == BO_NE &&
4540               "Invalid compex comparison.");
4541        return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4542                        LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4543      }
4544    }
4545  }
4546
4547  if (LHSTy->isRealFloatingType() &&
4548      RHSTy->isRealFloatingType()) {
4549    APFloat RHS(0.0), LHS(0.0);
4550
4551    bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4552    if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4553      return false;
4554
4555    if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
4556      return false;
4557
4558    APFloat::cmpResult CR = LHS.compare(RHS);
4559
4560    switch (E->getOpcode()) {
4561    default:
4562      llvm_unreachable("Invalid binary operator!");
4563    case BO_LT:
4564      return Success(CR == APFloat::cmpLessThan, E);
4565    case BO_GT:
4566      return Success(CR == APFloat::cmpGreaterThan, E);
4567    case BO_LE:
4568      return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
4569    case BO_GE:
4570      return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
4571                     E);
4572    case BO_EQ:
4573      return Success(CR == APFloat::cmpEqual, E);
4574    case BO_NE:
4575      return Success(CR == APFloat::cmpGreaterThan
4576                     || CR == APFloat::cmpLessThan
4577                     || CR == APFloat::cmpUnordered, E);
4578    }
4579  }
4580
4581  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4582    if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
4583      LValue LHSValue, RHSValue;
4584
4585      bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4586      if (!LHSOK && Info.keepEvaluatingAfterFailure())
4587        return false;
4588
4589      if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4590        return false;
4591
4592      // Reject differing bases from the normal codepath; we special-case
4593      // comparisons to null.
4594      if (!HasSameBase(LHSValue, RHSValue)) {
4595        if (E->getOpcode() == BO_Sub) {
4596          // Handle &&A - &&B.
4597          if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4598            return false;
4599          const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4600          const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4601          if (!LHSExpr || !RHSExpr)
4602            return false;
4603          const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4604          const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4605          if (!LHSAddrExpr || !RHSAddrExpr)
4606            return false;
4607          // Make sure both labels come from the same function.
4608          if (LHSAddrExpr->getLabel()->getDeclContext() !=
4609              RHSAddrExpr->getLabel()->getDeclContext())
4610            return false;
4611          Result = APValue(LHSAddrExpr, RHSAddrExpr);
4612          return true;
4613        }
4614        // Inequalities and subtractions between unrelated pointers have
4615        // unspecified or undefined behavior.
4616        if (!E->isEqualityOp())
4617          return Error(E);
4618        // A constant address may compare equal to the address of a symbol.
4619        // The one exception is that address of an object cannot compare equal
4620        // to a null pointer constant.
4621        if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4622            (!RHSValue.Base && !RHSValue.Offset.isZero()))
4623          return Error(E);
4624        // It's implementation-defined whether distinct literals will have
4625        // distinct addresses. In clang, the result of such a comparison is
4626        // unspecified, so it is not a constant expression. However, we do know
4627        // that the address of a literal will be non-null.
4628        if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4629            LHSValue.Base && RHSValue.Base)
4630          return Error(E);
4631        // We can't tell whether weak symbols will end up pointing to the same
4632        // object.
4633        if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
4634          return Error(E);
4635        // Pointers with different bases cannot represent the same object.
4636        // (Note that clang defaults to -fmerge-all-constants, which can
4637        // lead to inconsistent results for comparisons involving the address
4638        // of a constant; this generally doesn't matter in practice.)
4639        return Success(E->getOpcode() == BO_NE, E);
4640      }
4641
4642      const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4643      const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4644
4645      SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4646      SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4647
4648      if (E->getOpcode() == BO_Sub) {
4649        // C++11 [expr.add]p6:
4650        //   Unless both pointers point to elements of the same array object, or
4651        //   one past the last element of the array object, the behavior is
4652        //   undefined.
4653        if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4654            !AreElementsOfSameArray(getType(LHSValue.Base),
4655                                    LHSDesignator, RHSDesignator))
4656          CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4657
4658        QualType Type = E->getLHS()->getType();
4659        QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
4660
4661        CharUnits ElementSize;
4662        if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
4663          return false;
4664
4665        // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4666        // and produce incorrect results when it overflows. Such behavior
4667        // appears to be non-conforming, but is common, so perhaps we should
4668        // assume the standard intended for such cases to be undefined behavior
4669        // and check for them.
4670
4671        // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4672        // overflow in the final conversion to ptrdiff_t.
4673        APSInt LHS(
4674          llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4675        APSInt RHS(
4676          llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4677        APSInt ElemSize(
4678          llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4679        APSInt TrueResult = (LHS - RHS) / ElemSize;
4680        APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4681
4682        if (Result.extend(65) != TrueResult)
4683          HandleOverflow(Info, E, TrueResult, E->getType());
4684        return Success(Result, E);
4685      }
4686
4687      // C++11 [expr.rel]p3:
4688      //   Pointers to void (after pointer conversions) can be compared, with a
4689      //   result defined as follows: If both pointers represent the same
4690      //   address or are both the null pointer value, the result is true if the
4691      //   operator is <= or >= and false otherwise; otherwise the result is
4692      //   unspecified.
4693      // We interpret this as applying to pointers to *cv* void.
4694      if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
4695          E->isRelationalOp())
4696        CCEDiag(E, diag::note_constexpr_void_comparison);
4697
4698      // C++11 [expr.rel]p2:
4699      // - If two pointers point to non-static data members of the same object,
4700      //   or to subobjects or array elements fo such members, recursively, the
4701      //   pointer to the later declared member compares greater provided the
4702      //   two members have the same access control and provided their class is
4703      //   not a union.
4704      //   [...]
4705      // - Otherwise pointer comparisons are unspecified.
4706      if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4707          E->isRelationalOp()) {
4708        bool WasArrayIndex;
4709        unsigned Mismatch =
4710          FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4711                                 RHSDesignator, WasArrayIndex);
4712        // At the point where the designators diverge, the comparison has a
4713        // specified value if:
4714        //  - we are comparing array indices
4715        //  - we are comparing fields of a union, or fields with the same access
4716        // Otherwise, the result is unspecified and thus the comparison is not a
4717        // constant expression.
4718        if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4719            Mismatch < RHSDesignator.Entries.size()) {
4720          const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4721          const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4722          if (!LF && !RF)
4723            CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4724          else if (!LF)
4725            CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4726              << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4727              << RF->getParent() << RF;
4728          else if (!RF)
4729            CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4730              << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4731              << LF->getParent() << LF;
4732          else if (!LF->getParent()->isUnion() &&
4733                   LF->getAccess() != RF->getAccess())
4734            CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4735              << LF << LF->getAccess() << RF << RF->getAccess()
4736              << LF->getParent();
4737        }
4738      }
4739
4740      switch (E->getOpcode()) {
4741      default: llvm_unreachable("missing comparison operator");
4742      case BO_LT: return Success(LHSOffset < RHSOffset, E);
4743      case BO_GT: return Success(LHSOffset > RHSOffset, E);
4744      case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4745      case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4746      case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4747      case BO_NE: return Success(LHSOffset != RHSOffset, E);
4748      }
4749    }
4750  }
4751
4752  if (LHSTy->isMemberPointerType()) {
4753    assert(E->isEqualityOp() && "unexpected member pointer operation");
4754    assert(RHSTy->isMemberPointerType() && "invalid comparison");
4755
4756    MemberPtr LHSValue, RHSValue;
4757
4758    bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4759    if (!LHSOK && Info.keepEvaluatingAfterFailure())
4760      return false;
4761
4762    if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4763      return false;
4764
4765    // C++11 [expr.eq]p2:
4766    //   If both operands are null, they compare equal. Otherwise if only one is
4767    //   null, they compare unequal.
4768    if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4769      bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4770      return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4771    }
4772
4773    //   Otherwise if either is a pointer to a virtual member function, the
4774    //   result is unspecified.
4775    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4776      if (MD->isVirtual())
4777        CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4778    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4779      if (MD->isVirtual())
4780        CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4781
4782    //   Otherwise they compare equal if and only if they would refer to the
4783    //   same member of the same most derived object or the same subobject if
4784    //   they were dereferenced with a hypothetical object of the associated
4785    //   class type.
4786    bool Equal = LHSValue == RHSValue;
4787    return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4788  }
4789
4790  if (LHSTy->isNullPtrType()) {
4791    assert(E->isComparisonOp() && "unexpected nullptr operation");
4792    assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4793    // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4794    // are compared, the result is true of the operator is <=, >= or ==, and
4795    // false otherwise.
4796    BinaryOperator::Opcode Opcode = E->getOpcode();
4797    return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4798  }
4799
4800  if (!LHSTy->isIntegralOrEnumerationType() ||
4801      !RHSTy->isIntegralOrEnumerationType()) {
4802    // We can't continue from here for non-integral types.
4803    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4804  }
4805
4806  // The LHS of a constant expr is always evaluated and needed.
4807  APValue LHSVal;
4808
4809  bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4810  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4811    return false;
4812
4813  if (!Visit(E->getRHS()) || !LHSOK)
4814    return false;
4815
4816  APValue &RHSVal = Result;
4817
4818  // Handle cases like (unsigned long)&a + 4.
4819  if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4820    CharUnits AdditionalOffset = CharUnits::fromQuantity(
4821                                     RHSVal.getInt().getZExtValue());
4822    if (E->getOpcode() == BO_Add)
4823      LHSVal.getLValueOffset() += AdditionalOffset;
4824    else
4825      LHSVal.getLValueOffset() -= AdditionalOffset;
4826    Result = LHSVal;
4827    return true;
4828  }
4829
4830  // Handle cases like 4 + (unsigned long)&a
4831  if (E->getOpcode() == BO_Add &&
4832        RHSVal.isLValue() && LHSVal.isInt()) {
4833    RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4834                                    LHSVal.getInt().getZExtValue());
4835    // Note that RHSVal is Result.
4836    return true;
4837  }
4838
4839  if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4840    // Handle (intptr_t)&&A - (intptr_t)&&B.
4841    if (!LHSVal.getLValueOffset().isZero() ||
4842        !RHSVal.getLValueOffset().isZero())
4843      return false;
4844    const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4845    const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4846    if (!LHSExpr || !RHSExpr)
4847      return false;
4848    const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4849    const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4850    if (!LHSAddrExpr || !RHSAddrExpr)
4851      return false;
4852    // Make sure both labels come from the same function.
4853    if (LHSAddrExpr->getLabel()->getDeclContext() !=
4854        RHSAddrExpr->getLabel()->getDeclContext())
4855      return false;
4856    Result = APValue(LHSAddrExpr, RHSAddrExpr);
4857    return true;
4858  }
4859
4860  // All the following cases expect both operands to be an integer
4861  if (!LHSVal.isInt() || !RHSVal.isInt())
4862    return Error(E);
4863
4864  APSInt &LHS = LHSVal.getInt();
4865  APSInt &RHS = RHSVal.getInt();
4866
4867  switch (E->getOpcode()) {
4868  default:
4869    return Error(E);
4870  case BO_Mul:
4871    return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4872                                        LHS.getBitWidth() * 2,
4873                                        std::multiplies<APSInt>()), E);
4874  case BO_Add:
4875    return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4876                                        LHS.getBitWidth() + 1,
4877                                        std::plus<APSInt>()), E);
4878  case BO_Sub:
4879    return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4880                                        LHS.getBitWidth() + 1,
4881                                        std::minus<APSInt>()), E);
4882  case BO_And: return Success(LHS & RHS, E);
4883  case BO_Xor: return Success(LHS ^ RHS, E);
4884  case BO_Or:  return Success(LHS | RHS, E);
4885  case BO_Div:
4886  case BO_Rem:
4887    if (RHS == 0)
4888      return Error(E, diag::note_expr_divide_by_zero);
4889    // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4890    // actually undefined behavior in C++11 due to a language defect.
4891    if (RHS.isNegative() && RHS.isAllOnesValue() &&
4892        LHS.isSigned() && LHS.isMinSignedValue())
4893      HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4894    return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
4895  case BO_Shl: {
4896    // During constant-folding, a negative shift is an opposite shift. Such a
4897    // shift is not a constant expression.
4898    if (RHS.isSigned() && RHS.isNegative()) {
4899      CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4900      RHS = -RHS;
4901      goto shift_right;
4902    }
4903
4904  shift_left:
4905    // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4906    // shifted type.
4907    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4908    if (SA != RHS) {
4909      CCEDiag(E, diag::note_constexpr_large_shift)
4910        << RHS << E->getType() << LHS.getBitWidth();
4911    } else if (LHS.isSigned()) {
4912      // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4913      // operand, and must not overflow the corresponding unsigned type.
4914      if (LHS.isNegative())
4915        CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4916      else if (LHS.countLeadingZeros() < SA)
4917        CCEDiag(E, diag::note_constexpr_lshift_discards);
4918    }
4919
4920    return Success(LHS << SA, E);
4921  }
4922  case BO_Shr: {
4923    // During constant-folding, a negative shift is an opposite shift. Such a
4924    // shift is not a constant expression.
4925    if (RHS.isSigned() && RHS.isNegative()) {
4926      CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4927      RHS = -RHS;
4928      goto shift_left;
4929    }
4930
4931  shift_right:
4932    // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4933    // shifted type.
4934    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4935    if (SA != RHS)
4936      CCEDiag(E, diag::note_constexpr_large_shift)
4937        << RHS << E->getType() << LHS.getBitWidth();
4938
4939    return Success(LHS >> SA, E);
4940  }
4941
4942  case BO_LT: return Success(LHS < RHS, E);
4943  case BO_GT: return Success(LHS > RHS, E);
4944  case BO_LE: return Success(LHS <= RHS, E);
4945  case BO_GE: return Success(LHS >= RHS, E);
4946  case BO_EQ: return Success(LHS == RHS, E);
4947  case BO_NE: return Success(LHS != RHS, E);
4948  }
4949}
4950
4951CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
4952  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4953  //   result shall be the alignment of the referenced type."
4954  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4955    T = Ref->getPointeeType();
4956
4957  // __alignof is defined to return the preferred alignment.
4958  return Info.Ctx.toCharUnitsFromBits(
4959    Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
4960}
4961
4962CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
4963  E = E->IgnoreParens();
4964
4965  // alignof decl is always accepted, even if it doesn't make sense: we default
4966  // to 1 in those cases.
4967  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4968    return Info.Ctx.getDeclAlign(DRE->getDecl(),
4969                                 /*RefAsPointee*/true);
4970
4971  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4972    return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4973                                 /*RefAsPointee*/true);
4974
4975  return GetAlignOfType(E->getType());
4976}
4977
4978
4979/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4980/// a result as the expression's type.
4981bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4982                                    const UnaryExprOrTypeTraitExpr *E) {
4983  switch(E->getKind()) {
4984  case UETT_AlignOf: {
4985    if (E->isArgumentType())
4986      return Success(GetAlignOfType(E->getArgumentType()), E);
4987    else
4988      return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
4989  }
4990
4991  case UETT_VecStep: {
4992    QualType Ty = E->getTypeOfArgument();
4993
4994    if (Ty->isVectorType()) {
4995      unsigned n = Ty->getAs<VectorType>()->getNumElements();
4996
4997      // The vec_step built-in functions that take a 3-component
4998      // vector return 4. (OpenCL 1.1 spec 6.11.12)
4999      if (n == 3)
5000        n = 4;
5001
5002      return Success(n, E);
5003    } else
5004      return Success(1, E);
5005  }
5006
5007  case UETT_SizeOf: {
5008    QualType SrcTy = E->getTypeOfArgument();
5009    // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5010    //   the result is the size of the referenced type."
5011    if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5012      SrcTy = Ref->getPointeeType();
5013
5014    CharUnits Sizeof;
5015    if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
5016      return false;
5017    return Success(Sizeof, E);
5018  }
5019  }
5020
5021  llvm_unreachable("unknown expr/type trait");
5022}
5023
5024bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
5025  CharUnits Result;
5026  unsigned n = OOE->getNumComponents();
5027  if (n == 0)
5028    return Error(OOE);
5029  QualType CurrentType = OOE->getTypeSourceInfo()->getType();
5030  for (unsigned i = 0; i != n; ++i) {
5031    OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5032    switch (ON.getKind()) {
5033    case OffsetOfExpr::OffsetOfNode::Array: {
5034      const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
5035      APSInt IdxResult;
5036      if (!EvaluateInteger(Idx, IdxResult, Info))
5037        return false;
5038      const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5039      if (!AT)
5040        return Error(OOE);
5041      CurrentType = AT->getElementType();
5042      CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5043      Result += IdxResult.getSExtValue() * ElementSize;
5044        break;
5045    }
5046
5047    case OffsetOfExpr::OffsetOfNode::Field: {
5048      FieldDecl *MemberDecl = ON.getField();
5049      const RecordType *RT = CurrentType->getAs<RecordType>();
5050      if (!RT)
5051        return Error(OOE);
5052      RecordDecl *RD = RT->getDecl();
5053      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5054      unsigned i = MemberDecl->getFieldIndex();
5055      assert(i < RL.getFieldCount() && "offsetof field in wrong type");
5056      Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
5057      CurrentType = MemberDecl->getType().getNonReferenceType();
5058      break;
5059    }
5060
5061    case OffsetOfExpr::OffsetOfNode::Identifier:
5062      llvm_unreachable("dependent __builtin_offsetof");
5063
5064    case OffsetOfExpr::OffsetOfNode::Base: {
5065      CXXBaseSpecifier *BaseSpec = ON.getBase();
5066      if (BaseSpec->isVirtual())
5067        return Error(OOE);
5068
5069      // Find the layout of the class whose base we are looking into.
5070      const RecordType *RT = CurrentType->getAs<RecordType>();
5071      if (!RT)
5072        return Error(OOE);
5073      RecordDecl *RD = RT->getDecl();
5074      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5075
5076      // Find the base class itself.
5077      CurrentType = BaseSpec->getType();
5078      const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5079      if (!BaseRT)
5080        return Error(OOE);
5081
5082      // Add the offset to the base.
5083      Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
5084      break;
5085    }
5086    }
5087  }
5088  return Success(Result, OOE);
5089}
5090
5091bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5092  switch (E->getOpcode()) {
5093  default:
5094    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5095    // See C99 6.6p3.
5096    return Error(E);
5097  case UO_Extension:
5098    // FIXME: Should extension allow i-c-e extension expressions in its scope?
5099    // If so, we could clear the diagnostic ID.
5100    return Visit(E->getSubExpr());
5101  case UO_Plus:
5102    // The result is just the value.
5103    return Visit(E->getSubExpr());
5104  case UO_Minus: {
5105    if (!Visit(E->getSubExpr()))
5106      return false;
5107    if (!Result.isInt()) return Error(E);
5108    const APSInt &Value = Result.getInt();
5109    if (Value.isSigned() && Value.isMinSignedValue())
5110      HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5111                     E->getType());
5112    return Success(-Value, E);
5113  }
5114  case UO_Not: {
5115    if (!Visit(E->getSubExpr()))
5116      return false;
5117    if (!Result.isInt()) return Error(E);
5118    return Success(~Result.getInt(), E);
5119  }
5120  case UO_LNot: {
5121    bool bres;
5122    if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
5123      return false;
5124    return Success(!bres, E);
5125  }
5126  }
5127}
5128
5129/// HandleCast - This is used to evaluate implicit or explicit casts where the
5130/// result type is integer.
5131bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5132  const Expr *SubExpr = E->getSubExpr();
5133  QualType DestType = E->getType();
5134  QualType SrcType = SubExpr->getType();
5135
5136  switch (E->getCastKind()) {
5137  case CK_BaseToDerived:
5138  case CK_DerivedToBase:
5139  case CK_UncheckedDerivedToBase:
5140  case CK_Dynamic:
5141  case CK_ToUnion:
5142  case CK_ArrayToPointerDecay:
5143  case CK_FunctionToPointerDecay:
5144  case CK_NullToPointer:
5145  case CK_NullToMemberPointer:
5146  case CK_BaseToDerivedMemberPointer:
5147  case CK_DerivedToBaseMemberPointer:
5148  case CK_ReinterpretMemberPointer:
5149  case CK_ConstructorConversion:
5150  case CK_IntegralToPointer:
5151  case CK_ToVoid:
5152  case CK_VectorSplat:
5153  case CK_IntegralToFloating:
5154  case CK_FloatingCast:
5155  case CK_CPointerToObjCPointerCast:
5156  case CK_BlockPointerToObjCPointerCast:
5157  case CK_AnyPointerToBlockPointerCast:
5158  case CK_ObjCObjectLValueCast:
5159  case CK_FloatingRealToComplex:
5160  case CK_FloatingComplexToReal:
5161  case CK_FloatingComplexCast:
5162  case CK_FloatingComplexToIntegralComplex:
5163  case CK_IntegralRealToComplex:
5164  case CK_IntegralComplexCast:
5165  case CK_IntegralComplexToFloatingComplex:
5166    llvm_unreachable("invalid cast kind for integral value");
5167
5168  case CK_BitCast:
5169  case CK_Dependent:
5170  case CK_LValueBitCast:
5171  case CK_ARCProduceObject:
5172  case CK_ARCConsumeObject:
5173  case CK_ARCReclaimReturnedObject:
5174  case CK_ARCExtendBlockObject:
5175  case CK_CopyAndAutoreleaseBlockObject:
5176    return Error(E);
5177
5178  case CK_UserDefinedConversion:
5179  case CK_LValueToRValue:
5180  case CK_AtomicToNonAtomic:
5181  case CK_NonAtomicToAtomic:
5182  case CK_NoOp:
5183    return ExprEvaluatorBaseTy::VisitCastExpr(E);
5184
5185  case CK_MemberPointerToBoolean:
5186  case CK_PointerToBoolean:
5187  case CK_IntegralToBoolean:
5188  case CK_FloatingToBoolean:
5189  case CK_FloatingComplexToBoolean:
5190  case CK_IntegralComplexToBoolean: {
5191    bool BoolResult;
5192    if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
5193      return false;
5194    return Success(BoolResult, E);
5195  }
5196
5197  case CK_IntegralCast: {
5198    if (!Visit(SubExpr))
5199      return false;
5200
5201    if (!Result.isInt()) {
5202      // Allow casts of address-of-label differences if they are no-ops
5203      // or narrowing.  (The narrowing case isn't actually guaranteed to
5204      // be constant-evaluatable except in some narrow cases which are hard
5205      // to detect here.  We let it through on the assumption the user knows
5206      // what they are doing.)
5207      if (Result.isAddrLabelDiff())
5208        return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
5209      // Only allow casts of lvalues if they are lossless.
5210      return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5211    }
5212
5213    return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5214                                      Result.getInt()), E);
5215  }
5216
5217  case CK_PointerToIntegral: {
5218    CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5219
5220    LValue LV;
5221    if (!EvaluatePointer(SubExpr, LV, Info))
5222      return false;
5223
5224    if (LV.getLValueBase()) {
5225      // Only allow based lvalue casts if they are lossless.
5226      // FIXME: Allow a larger integer size than the pointer size, and allow
5227      // narrowing back down to pointer width in subsequent integral casts.
5228      // FIXME: Check integer type's active bits, not its type size.
5229      if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
5230        return Error(E);
5231
5232      LV.Designator.setInvalid();
5233      LV.moveInto(Result);
5234      return true;
5235    }
5236
5237    APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5238                                         SrcType);
5239    return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
5240  }
5241
5242  case CK_IntegralComplexToReal: {
5243    ComplexValue C;
5244    if (!EvaluateComplex(SubExpr, C, Info))
5245      return false;
5246    return Success(C.getComplexIntReal(), E);
5247  }
5248
5249  case CK_FloatingToIntegral: {
5250    APFloat F(0.0);
5251    if (!EvaluateFloat(SubExpr, F, Info))
5252      return false;
5253
5254    APSInt Value;
5255    if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5256      return false;
5257    return Success(Value, E);
5258  }
5259  }
5260
5261  llvm_unreachable("unknown cast resulting in integral value");
5262}
5263
5264bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5265  if (E->getSubExpr()->getType()->isAnyComplexType()) {
5266    ComplexValue LV;
5267    if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5268      return false;
5269    if (!LV.isComplexInt())
5270      return Error(E);
5271    return Success(LV.getComplexIntReal(), E);
5272  }
5273
5274  return Visit(E->getSubExpr());
5275}
5276
5277bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5278  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
5279    ComplexValue LV;
5280    if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5281      return false;
5282    if (!LV.isComplexInt())
5283      return Error(E);
5284    return Success(LV.getComplexIntImag(), E);
5285  }
5286
5287  VisitIgnoredValue(E->getSubExpr());
5288  return Success(0, E);
5289}
5290
5291bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5292  return Success(E->getPackLength(), E);
5293}
5294
5295bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5296  return Success(E->getValue(), E);
5297}
5298
5299//===----------------------------------------------------------------------===//
5300// Float Evaluation
5301//===----------------------------------------------------------------------===//
5302
5303namespace {
5304class FloatExprEvaluator
5305  : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
5306  APFloat &Result;
5307public:
5308  FloatExprEvaluator(EvalInfo &info, APFloat &result)
5309    : ExprEvaluatorBaseTy(info), Result(result) {}
5310
5311  bool Success(const APValue &V, const Expr *e) {
5312    Result = V.getFloat();
5313    return true;
5314  }
5315
5316  bool ZeroInitialization(const Expr *E) {
5317    Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5318    return true;
5319  }
5320
5321  bool VisitCallExpr(const CallExpr *E);
5322
5323  bool VisitUnaryOperator(const UnaryOperator *E);
5324  bool VisitBinaryOperator(const BinaryOperator *E);
5325  bool VisitFloatingLiteral(const FloatingLiteral *E);
5326  bool VisitCastExpr(const CastExpr *E);
5327
5328  bool VisitUnaryReal(const UnaryOperator *E);
5329  bool VisitUnaryImag(const UnaryOperator *E);
5330
5331  // FIXME: Missing: array subscript of vector, member of vector
5332};
5333} // end anonymous namespace
5334
5335static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
5336  assert(E->isRValue() && E->getType()->isRealFloatingType());
5337  return FloatExprEvaluator(Info, Result).Visit(E);
5338}
5339
5340static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
5341                                  QualType ResultTy,
5342                                  const Expr *Arg,
5343                                  bool SNaN,
5344                                  llvm::APFloat &Result) {
5345  const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5346  if (!S) return false;
5347
5348  const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5349
5350  llvm::APInt fill;
5351
5352  // Treat empty strings as if they were zero.
5353  if (S->getString().empty())
5354    fill = llvm::APInt(32, 0);
5355  else if (S->getString().getAsInteger(0, fill))
5356    return false;
5357
5358  if (SNaN)
5359    Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5360  else
5361    Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5362  return true;
5363}
5364
5365bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
5366  switch (E->isBuiltinCall()) {
5367  default:
5368    return ExprEvaluatorBaseTy::VisitCallExpr(E);
5369
5370  case Builtin::BI__builtin_huge_val:
5371  case Builtin::BI__builtin_huge_valf:
5372  case Builtin::BI__builtin_huge_vall:
5373  case Builtin::BI__builtin_inf:
5374  case Builtin::BI__builtin_inff:
5375  case Builtin::BI__builtin_infl: {
5376    const llvm::fltSemantics &Sem =
5377      Info.Ctx.getFloatTypeSemantics(E->getType());
5378    Result = llvm::APFloat::getInf(Sem);
5379    return true;
5380  }
5381
5382  case Builtin::BI__builtin_nans:
5383  case Builtin::BI__builtin_nansf:
5384  case Builtin::BI__builtin_nansl:
5385    if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5386                               true, Result))
5387      return Error(E);
5388    return true;
5389
5390  case Builtin::BI__builtin_nan:
5391  case Builtin::BI__builtin_nanf:
5392  case Builtin::BI__builtin_nanl:
5393    // If this is __builtin_nan() turn this into a nan, otherwise we
5394    // can't constant fold it.
5395    if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5396                               false, Result))
5397      return Error(E);
5398    return true;
5399
5400  case Builtin::BI__builtin_fabs:
5401  case Builtin::BI__builtin_fabsf:
5402  case Builtin::BI__builtin_fabsl:
5403    if (!EvaluateFloat(E->getArg(0), Result, Info))
5404      return false;
5405
5406    if (Result.isNegative())
5407      Result.changeSign();
5408    return true;
5409
5410  case Builtin::BI__builtin_copysign:
5411  case Builtin::BI__builtin_copysignf:
5412  case Builtin::BI__builtin_copysignl: {
5413    APFloat RHS(0.);
5414    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5415        !EvaluateFloat(E->getArg(1), RHS, Info))
5416      return false;
5417    Result.copySign(RHS);
5418    return true;
5419  }
5420  }
5421}
5422
5423bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5424  if (E->getSubExpr()->getType()->isAnyComplexType()) {
5425    ComplexValue CV;
5426    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5427      return false;
5428    Result = CV.FloatReal;
5429    return true;
5430  }
5431
5432  return Visit(E->getSubExpr());
5433}
5434
5435bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5436  if (E->getSubExpr()->getType()->isAnyComplexType()) {
5437    ComplexValue CV;
5438    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5439      return false;
5440    Result = CV.FloatImag;
5441    return true;
5442  }
5443
5444  VisitIgnoredValue(E->getSubExpr());
5445  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5446  Result = llvm::APFloat::getZero(Sem);
5447  return true;
5448}
5449
5450bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5451  switch (E->getOpcode()) {
5452  default: return Error(E);
5453  case UO_Plus:
5454    return EvaluateFloat(E->getSubExpr(), Result, Info);
5455  case UO_Minus:
5456    if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5457      return false;
5458    Result.changeSign();
5459    return true;
5460  }
5461}
5462
5463bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5464  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5465    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5466
5467  APFloat RHS(0.0);
5468  bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5469  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5470    return false;
5471  if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
5472    return false;
5473
5474  switch (E->getOpcode()) {
5475  default: return Error(E);
5476  case BO_Mul:
5477    Result.multiply(RHS, APFloat::rmNearestTiesToEven);
5478    break;
5479  case BO_Add:
5480    Result.add(RHS, APFloat::rmNearestTiesToEven);
5481    break;
5482  case BO_Sub:
5483    Result.subtract(RHS, APFloat::rmNearestTiesToEven);
5484    break;
5485  case BO_Div:
5486    Result.divide(RHS, APFloat::rmNearestTiesToEven);
5487    break;
5488  }
5489
5490  if (Result.isInfinity() || Result.isNaN())
5491    CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5492  return true;
5493}
5494
5495bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5496  Result = E->getValue();
5497  return true;
5498}
5499
5500bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5501  const Expr* SubExpr = E->getSubExpr();
5502
5503  switch (E->getCastKind()) {
5504  default:
5505    return ExprEvaluatorBaseTy::VisitCastExpr(E);
5506
5507  case CK_IntegralToFloating: {
5508    APSInt IntResult;
5509    return EvaluateInteger(SubExpr, IntResult, Info) &&
5510           HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5511                                E->getType(), Result);
5512  }
5513
5514  case CK_FloatingCast: {
5515    if (!Visit(SubExpr))
5516      return false;
5517    return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5518                                  Result);
5519  }
5520
5521  case CK_FloatingComplexToReal: {
5522    ComplexValue V;
5523    if (!EvaluateComplex(SubExpr, V, Info))
5524      return false;
5525    Result = V.getComplexFloatReal();
5526    return true;
5527  }
5528  }
5529}
5530
5531//===----------------------------------------------------------------------===//
5532// Complex Evaluation (for float and integer)
5533//===----------------------------------------------------------------------===//
5534
5535namespace {
5536class ComplexExprEvaluator
5537  : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
5538  ComplexValue &Result;
5539
5540public:
5541  ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
5542    : ExprEvaluatorBaseTy(info), Result(Result) {}
5543
5544  bool Success(const APValue &V, const Expr *e) {
5545    Result.setFrom(V);
5546    return true;
5547  }
5548
5549  bool ZeroInitialization(const Expr *E);
5550
5551  //===--------------------------------------------------------------------===//
5552  //                            Visitor Methods
5553  //===--------------------------------------------------------------------===//
5554
5555  bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
5556  bool VisitCastExpr(const CastExpr *E);
5557  bool VisitBinaryOperator(const BinaryOperator *E);
5558  bool VisitUnaryOperator(const UnaryOperator *E);
5559  bool VisitInitListExpr(const InitListExpr *E);
5560};
5561} // end anonymous namespace
5562
5563static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5564                            EvalInfo &Info) {
5565  assert(E->isRValue() && E->getType()->isAnyComplexType());
5566  return ComplexExprEvaluator(Info, Result).Visit(E);
5567}
5568
5569bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
5570  QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
5571  if (ElemTy->isRealFloatingType()) {
5572    Result.makeComplexFloat();
5573    APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5574    Result.FloatReal = Zero;
5575    Result.FloatImag = Zero;
5576  } else {
5577    Result.makeComplexInt();
5578    APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5579    Result.IntReal = Zero;
5580    Result.IntImag = Zero;
5581  }
5582  return true;
5583}
5584
5585bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5586  const Expr* SubExpr = E->getSubExpr();
5587
5588  if (SubExpr->getType()->isRealFloatingType()) {
5589    Result.makeComplexFloat();
5590    APFloat &Imag = Result.FloatImag;
5591    if (!EvaluateFloat(SubExpr, Imag, Info))
5592      return false;
5593
5594    Result.FloatReal = APFloat(Imag.getSemantics());
5595    return true;
5596  } else {
5597    assert(SubExpr->getType()->isIntegerType() &&
5598           "Unexpected imaginary literal.");
5599
5600    Result.makeComplexInt();
5601    APSInt &Imag = Result.IntImag;
5602    if (!EvaluateInteger(SubExpr, Imag, Info))
5603      return false;
5604
5605    Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5606    return true;
5607  }
5608}
5609
5610bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
5611
5612  switch (E->getCastKind()) {
5613  case CK_BitCast:
5614  case CK_BaseToDerived:
5615  case CK_DerivedToBase:
5616  case CK_UncheckedDerivedToBase:
5617  case CK_Dynamic:
5618  case CK_ToUnion:
5619  case CK_ArrayToPointerDecay:
5620  case CK_FunctionToPointerDecay:
5621  case CK_NullToPointer:
5622  case CK_NullToMemberPointer:
5623  case CK_BaseToDerivedMemberPointer:
5624  case CK_DerivedToBaseMemberPointer:
5625  case CK_MemberPointerToBoolean:
5626  case CK_ReinterpretMemberPointer:
5627  case CK_ConstructorConversion:
5628  case CK_IntegralToPointer:
5629  case CK_PointerToIntegral:
5630  case CK_PointerToBoolean:
5631  case CK_ToVoid:
5632  case CK_VectorSplat:
5633  case CK_IntegralCast:
5634  case CK_IntegralToBoolean:
5635  case CK_IntegralToFloating:
5636  case CK_FloatingToIntegral:
5637  case CK_FloatingToBoolean:
5638  case CK_FloatingCast:
5639  case CK_CPointerToObjCPointerCast:
5640  case CK_BlockPointerToObjCPointerCast:
5641  case CK_AnyPointerToBlockPointerCast:
5642  case CK_ObjCObjectLValueCast:
5643  case CK_FloatingComplexToReal:
5644  case CK_FloatingComplexToBoolean:
5645  case CK_IntegralComplexToReal:
5646  case CK_IntegralComplexToBoolean:
5647  case CK_ARCProduceObject:
5648  case CK_ARCConsumeObject:
5649  case CK_ARCReclaimReturnedObject:
5650  case CK_ARCExtendBlockObject:
5651  case CK_CopyAndAutoreleaseBlockObject:
5652    llvm_unreachable("invalid cast kind for complex value");
5653
5654  case CK_LValueToRValue:
5655  case CK_AtomicToNonAtomic:
5656  case CK_NonAtomicToAtomic:
5657  case CK_NoOp:
5658    return ExprEvaluatorBaseTy::VisitCastExpr(E);
5659
5660  case CK_Dependent:
5661  case CK_LValueBitCast:
5662  case CK_UserDefinedConversion:
5663    return Error(E);
5664
5665  case CK_FloatingRealToComplex: {
5666    APFloat &Real = Result.FloatReal;
5667    if (!EvaluateFloat(E->getSubExpr(), Real, Info))
5668      return false;
5669
5670    Result.makeComplexFloat();
5671    Result.FloatImag = APFloat(Real.getSemantics());
5672    return true;
5673  }
5674
5675  case CK_FloatingComplexCast: {
5676    if (!Visit(E->getSubExpr()))
5677      return false;
5678
5679    QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5680    QualType From
5681      = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5682
5683    return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5684           HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
5685  }
5686
5687  case CK_FloatingComplexToIntegralComplex: {
5688    if (!Visit(E->getSubExpr()))
5689      return false;
5690
5691    QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5692    QualType From
5693      = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5694    Result.makeComplexInt();
5695    return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5696                                To, Result.IntReal) &&
5697           HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5698                                To, Result.IntImag);
5699  }
5700
5701  case CK_IntegralRealToComplex: {
5702    APSInt &Real = Result.IntReal;
5703    if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5704      return false;
5705
5706    Result.makeComplexInt();
5707    Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5708    return true;
5709  }
5710
5711  case CK_IntegralComplexCast: {
5712    if (!Visit(E->getSubExpr()))
5713      return false;
5714
5715    QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5716    QualType From
5717      = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5718
5719    Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5720    Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
5721    return true;
5722  }
5723
5724  case CK_IntegralComplexToFloatingComplex: {
5725    if (!Visit(E->getSubExpr()))
5726      return false;
5727
5728    QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5729    QualType From
5730      = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5731    Result.makeComplexFloat();
5732    return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5733                                To, Result.FloatReal) &&
5734           HandleIntToFloatCast(Info, E, From, Result.IntImag,
5735                                To, Result.FloatImag);
5736  }
5737  }
5738
5739  llvm_unreachable("unknown cast resulting in complex value");
5740}
5741
5742bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5743  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5744    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5745
5746  bool LHSOK = Visit(E->getLHS());
5747  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5748    return false;
5749
5750  ComplexValue RHS;
5751  if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
5752    return false;
5753
5754  assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5755         "Invalid operands to binary operator.");
5756  switch (E->getOpcode()) {
5757  default: return Error(E);
5758  case BO_Add:
5759    if (Result.isComplexFloat()) {
5760      Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5761                                       APFloat::rmNearestTiesToEven);
5762      Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5763                                       APFloat::rmNearestTiesToEven);
5764    } else {
5765      Result.getComplexIntReal() += RHS.getComplexIntReal();
5766      Result.getComplexIntImag() += RHS.getComplexIntImag();
5767    }
5768    break;
5769  case BO_Sub:
5770    if (Result.isComplexFloat()) {
5771      Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5772                                            APFloat::rmNearestTiesToEven);
5773      Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5774                                            APFloat::rmNearestTiesToEven);
5775    } else {
5776      Result.getComplexIntReal() -= RHS.getComplexIntReal();
5777      Result.getComplexIntImag() -= RHS.getComplexIntImag();
5778    }
5779    break;
5780  case BO_Mul:
5781    if (Result.isComplexFloat()) {
5782      ComplexValue LHS = Result;
5783      APFloat &LHS_r = LHS.getComplexFloatReal();
5784      APFloat &LHS_i = LHS.getComplexFloatImag();
5785      APFloat &RHS_r = RHS.getComplexFloatReal();
5786      APFloat &RHS_i = RHS.getComplexFloatImag();
5787
5788      APFloat Tmp = LHS_r;
5789      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5790      Result.getComplexFloatReal() = Tmp;
5791      Tmp = LHS_i;
5792      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5793      Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5794
5795      Tmp = LHS_r;
5796      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5797      Result.getComplexFloatImag() = Tmp;
5798      Tmp = LHS_i;
5799      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5800      Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5801    } else {
5802      ComplexValue LHS = Result;
5803      Result.getComplexIntReal() =
5804        (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5805         LHS.getComplexIntImag() * RHS.getComplexIntImag());
5806      Result.getComplexIntImag() =
5807        (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5808         LHS.getComplexIntImag() * RHS.getComplexIntReal());
5809    }
5810    break;
5811  case BO_Div:
5812    if (Result.isComplexFloat()) {
5813      ComplexValue LHS = Result;
5814      APFloat &LHS_r = LHS.getComplexFloatReal();
5815      APFloat &LHS_i = LHS.getComplexFloatImag();
5816      APFloat &RHS_r = RHS.getComplexFloatReal();
5817      APFloat &RHS_i = RHS.getComplexFloatImag();
5818      APFloat &Res_r = Result.getComplexFloatReal();
5819      APFloat &Res_i = Result.getComplexFloatImag();
5820
5821      APFloat Den = RHS_r;
5822      Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5823      APFloat Tmp = RHS_i;
5824      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5825      Den.add(Tmp, APFloat::rmNearestTiesToEven);
5826
5827      Res_r = LHS_r;
5828      Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5829      Tmp = LHS_i;
5830      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5831      Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5832      Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5833
5834      Res_i = LHS_i;
5835      Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5836      Tmp = LHS_r;
5837      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5838      Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5839      Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5840    } else {
5841      if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5842        return Error(E, diag::note_expr_divide_by_zero);
5843
5844      ComplexValue LHS = Result;
5845      APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5846        RHS.getComplexIntImag() * RHS.getComplexIntImag();
5847      Result.getComplexIntReal() =
5848        (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5849         LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5850      Result.getComplexIntImag() =
5851        (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5852         LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5853    }
5854    break;
5855  }
5856
5857  return true;
5858}
5859
5860bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5861  // Get the operand value into 'Result'.
5862  if (!Visit(E->getSubExpr()))
5863    return false;
5864
5865  switch (E->getOpcode()) {
5866  default:
5867    return Error(E);
5868  case UO_Extension:
5869    return true;
5870  case UO_Plus:
5871    // The result is always just the subexpr.
5872    return true;
5873  case UO_Minus:
5874    if (Result.isComplexFloat()) {
5875      Result.getComplexFloatReal().changeSign();
5876      Result.getComplexFloatImag().changeSign();
5877    }
5878    else {
5879      Result.getComplexIntReal() = -Result.getComplexIntReal();
5880      Result.getComplexIntImag() = -Result.getComplexIntImag();
5881    }
5882    return true;
5883  case UO_Not:
5884    if (Result.isComplexFloat())
5885      Result.getComplexFloatImag().changeSign();
5886    else
5887      Result.getComplexIntImag() = -Result.getComplexIntImag();
5888    return true;
5889  }
5890}
5891
5892bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5893  if (E->getNumInits() == 2) {
5894    if (E->getType()->isComplexType()) {
5895      Result.makeComplexFloat();
5896      if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5897        return false;
5898      if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5899        return false;
5900    } else {
5901      Result.makeComplexInt();
5902      if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5903        return false;
5904      if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5905        return false;
5906    }
5907    return true;
5908  }
5909  return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5910}
5911
5912//===----------------------------------------------------------------------===//
5913// Void expression evaluation, primarily for a cast to void on the LHS of a
5914// comma operator
5915//===----------------------------------------------------------------------===//
5916
5917namespace {
5918class VoidExprEvaluator
5919  : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5920public:
5921  VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5922
5923  bool Success(const APValue &V, const Expr *e) { return true; }
5924
5925  bool VisitCastExpr(const CastExpr *E) {
5926    switch (E->getCastKind()) {
5927    default:
5928      return ExprEvaluatorBaseTy::VisitCastExpr(E);
5929    case CK_ToVoid:
5930      VisitIgnoredValue(E->getSubExpr());
5931      return true;
5932    }
5933  }
5934};
5935} // end anonymous namespace
5936
5937static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5938  assert(E->isRValue() && E->getType()->isVoidType());
5939  return VoidExprEvaluator(Info).Visit(E);
5940}
5941
5942//===----------------------------------------------------------------------===//
5943// Top level Expr::EvaluateAsRValue method.
5944//===----------------------------------------------------------------------===//
5945
5946static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
5947  // In C, function designators are not lvalues, but we evaluate them as if they
5948  // are.
5949  if (E->isGLValue() || E->getType()->isFunctionType()) {
5950    LValue LV;
5951    if (!EvaluateLValue(E, LV, Info))
5952      return false;
5953    LV.moveInto(Result);
5954  } else if (E->getType()->isVectorType()) {
5955    if (!EvaluateVector(E, Result, Info))
5956      return false;
5957  } else if (E->getType()->isIntegralOrEnumerationType()) {
5958    if (!IntExprEvaluator(Info, Result).Visit(E))
5959      return false;
5960  } else if (E->getType()->hasPointerRepresentation()) {
5961    LValue LV;
5962    if (!EvaluatePointer(E, LV, Info))
5963      return false;
5964    LV.moveInto(Result);
5965  } else if (E->getType()->isRealFloatingType()) {
5966    llvm::APFloat F(0.0);
5967    if (!EvaluateFloat(E, F, Info))
5968      return false;
5969    Result = APValue(F);
5970  } else if (E->getType()->isAnyComplexType()) {
5971    ComplexValue C;
5972    if (!EvaluateComplex(E, C, Info))
5973      return false;
5974    C.moveInto(Result);
5975  } else if (E->getType()->isMemberPointerType()) {
5976    MemberPtr P;
5977    if (!EvaluateMemberPointer(E, P, Info))
5978      return false;
5979    P.moveInto(Result);
5980    return true;
5981  } else if (E->getType()->isArrayType()) {
5982    LValue LV;
5983    LV.set(E, Info.CurrentCall->Index);
5984    if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
5985      return false;
5986    Result = Info.CurrentCall->Temporaries[E];
5987  } else if (E->getType()->isRecordType()) {
5988    LValue LV;
5989    LV.set(E, Info.CurrentCall->Index);
5990    if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5991      return false;
5992    Result = Info.CurrentCall->Temporaries[E];
5993  } else if (E->getType()->isVoidType()) {
5994    if (Info.getLangOpts().CPlusPlus0x)
5995      Info.CCEDiag(E, diag::note_constexpr_nonliteral)
5996        << E->getType();
5997    else
5998      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5999    if (!EvaluateVoid(E, Info))
6000      return false;
6001  } else if (Info.getLangOpts().CPlusPlus0x) {
6002    Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
6003    return false;
6004  } else {
6005    Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
6006    return false;
6007  }
6008
6009  return true;
6010}
6011
6012/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6013/// cases, the in-place evaluation is essential, since later initializers for
6014/// an object can indirectly refer to subobjects which were initialized earlier.
6015static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6016                            const Expr *E, CheckConstantExpressionKind CCEK,
6017                            bool AllowNonLiteralTypes) {
6018  if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
6019    return false;
6020
6021  if (E->isRValue()) {
6022    // Evaluate arrays and record types in-place, so that later initializers can
6023    // refer to earlier-initialized members of the object.
6024    if (E->getType()->isArrayType())
6025      return EvaluateArray(E, This, Result, Info);
6026    else if (E->getType()->isRecordType())
6027      return EvaluateRecord(E, This, Result, Info);
6028  }
6029
6030  // For any other type, in-place evaluation is unimportant.
6031  return Evaluate(Result, Info, E);
6032}
6033
6034/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6035/// lvalue-to-rvalue cast if it is an lvalue.
6036static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
6037  if (!CheckLiteralType(Info, E))
6038    return false;
6039
6040  if (!::Evaluate(Result, Info, E))
6041    return false;
6042
6043  if (E->isGLValue()) {
6044    LValue LV;
6045    LV.setFrom(Info.Ctx, Result);
6046    if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
6047      return false;
6048  }
6049
6050  // Check this core constant expression is a constant expression.
6051  return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
6052}
6053
6054/// EvaluateAsRValue - Return true if this is a constant which we can fold using
6055/// any crazy technique (that has nothing to do with language standards) that
6056/// we want to.  If this function returns true, it returns the folded constant
6057/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6058/// will be applied to the result.
6059bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
6060  // Fast-path evaluations of integer literals, since we sometimes see files
6061  // containing vast quantities of these.
6062  if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6063    Result.Val = APValue(APSInt(L->getValue(),
6064                                L->getType()->isUnsignedIntegerType()));
6065    return true;
6066  }
6067
6068  // FIXME: Evaluating values of large array and record types can cause
6069  // performance problems. Only do so in C++11 for now.
6070  if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6071      !Ctx.getLangOpts().CPlusPlus0x)
6072    return false;
6073
6074  EvalInfo Info(Ctx, Result);
6075  return ::EvaluateAsRValue(Info, this, Result.Val);
6076}
6077
6078bool Expr::EvaluateAsBooleanCondition(bool &Result,
6079                                      const ASTContext &Ctx) const {
6080  EvalResult Scratch;
6081  return EvaluateAsRValue(Scratch, Ctx) &&
6082         HandleConversionToBool(Scratch.Val, Result);
6083}
6084
6085bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6086                         SideEffectsKind AllowSideEffects) const {
6087  if (!getType()->isIntegralOrEnumerationType())
6088    return false;
6089
6090  EvalResult ExprResult;
6091  if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6092      (!AllowSideEffects && ExprResult.HasSideEffects))
6093    return false;
6094
6095  Result = ExprResult.Val.getInt();
6096  return true;
6097}
6098
6099bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
6100  EvalInfo Info(Ctx, Result);
6101
6102  LValue LV;
6103  if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6104      !CheckLValueConstantExpression(Info, getExprLoc(),
6105                                     Ctx.getLValueReferenceType(getType()), LV))
6106    return false;
6107
6108  LV.moveInto(Result.Val);
6109  return true;
6110}
6111
6112bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6113                                 const VarDecl *VD,
6114                      llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
6115  // FIXME: Evaluating initializers for large array and record types can cause
6116  // performance problems. Only do so in C++11 for now.
6117  if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6118      !Ctx.getLangOpts().CPlusPlus0x)
6119    return false;
6120
6121  Expr::EvalStatus EStatus;
6122  EStatus.Diag = &Notes;
6123
6124  EvalInfo InitInfo(Ctx, EStatus);
6125  InitInfo.setEvaluatingDecl(VD, Value);
6126
6127  LValue LVal;
6128  LVal.set(VD);
6129
6130  // C++11 [basic.start.init]p2:
6131  //  Variables with static storage duration or thread storage duration shall be
6132  //  zero-initialized before any other initialization takes place.
6133  // This behavior is not present in C.
6134  if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
6135      !VD->getType()->isReferenceType()) {
6136    ImplicitValueInitExpr VIE(VD->getType());
6137    if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6138                         /*AllowNonLiteralTypes=*/true))
6139      return false;
6140  }
6141
6142  if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6143                         /*AllowNonLiteralTypes=*/true) ||
6144      EStatus.HasSideEffects)
6145    return false;
6146
6147  return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6148                                 Value);
6149}
6150
6151/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6152/// constant folded, but discard the result.
6153bool Expr::isEvaluatable(const ASTContext &Ctx) const {
6154  EvalResult Result;
6155  return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
6156}
6157
6158bool Expr::HasSideEffects(const ASTContext &Ctx) const {
6159  return HasSideEffect(Ctx).Visit(this);
6160}
6161
6162APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
6163  EvalResult EvalResult;
6164  bool Result = EvaluateAsRValue(EvalResult, Ctx);
6165  (void)Result;
6166  assert(Result && "Could not evaluate expression");
6167  assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
6168
6169  return EvalResult.Val.getInt();
6170}
6171
6172 bool Expr::EvalResult::isGlobalLValue() const {
6173   assert(Val.isLValue());
6174   return IsGlobalLValue(Val.getLValueBase());
6175 }
6176
6177
6178/// isIntegerConstantExpr - this recursive routine will test if an expression is
6179/// an integer constant expression.
6180
6181/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6182/// comma, etc
6183///
6184/// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
6185/// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
6186/// cast+dereference.
6187
6188// CheckICE - This function does the fundamental ICE checking: the returned
6189// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6190// Note that to reduce code duplication, this helper does no evaluation
6191// itself; the caller checks whether the expression is evaluatable, and
6192// in the rare cases where CheckICE actually cares about the evaluated
6193// value, it calls into Evalute.
6194//
6195// Meanings of Val:
6196// 0: This expression is an ICE.
6197// 1: This expression is not an ICE, but if it isn't evaluated, it's
6198//    a legal subexpression for an ICE. This return value is used to handle
6199//    the comma operator in C99 mode.
6200// 2: This expression is not an ICE, and is not a legal subexpression for one.
6201
6202namespace {
6203
6204struct ICEDiag {
6205  unsigned Val;
6206  SourceLocation Loc;
6207
6208  public:
6209  ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6210  ICEDiag() : Val(0) {}
6211};
6212
6213}
6214
6215static ICEDiag NoDiag() { return ICEDiag(); }
6216
6217static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6218  Expr::EvalResult EVResult;
6219  if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
6220      !EVResult.Val.isInt()) {
6221    return ICEDiag(2, E->getLocStart());
6222  }
6223  return NoDiag();
6224}
6225
6226static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6227  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
6228  if (!E->getType()->isIntegralOrEnumerationType()) {
6229    return ICEDiag(2, E->getLocStart());
6230  }
6231
6232  switch (E->getStmtClass()) {
6233#define ABSTRACT_STMT(Node)
6234#define STMT(Node, Base) case Expr::Node##Class:
6235#define EXPR(Node, Base)
6236#include "clang/AST/StmtNodes.inc"
6237  case Expr::PredefinedExprClass:
6238  case Expr::FloatingLiteralClass:
6239  case Expr::ImaginaryLiteralClass:
6240  case Expr::StringLiteralClass:
6241  case Expr::ArraySubscriptExprClass:
6242  case Expr::MemberExprClass:
6243  case Expr::CompoundAssignOperatorClass:
6244  case Expr::CompoundLiteralExprClass:
6245  case Expr::ExtVectorElementExprClass:
6246  case Expr::DesignatedInitExprClass:
6247  case Expr::ImplicitValueInitExprClass:
6248  case Expr::ParenListExprClass:
6249  case Expr::VAArgExprClass:
6250  case Expr::AddrLabelExprClass:
6251  case Expr::StmtExprClass:
6252  case Expr::CXXMemberCallExprClass:
6253  case Expr::CUDAKernelCallExprClass:
6254  case Expr::CXXDynamicCastExprClass:
6255  case Expr::CXXTypeidExprClass:
6256  case Expr::CXXUuidofExprClass:
6257  case Expr::CXXNullPtrLiteralExprClass:
6258  case Expr::UserDefinedLiteralClass:
6259  case Expr::CXXThisExprClass:
6260  case Expr::CXXThrowExprClass:
6261  case Expr::CXXNewExprClass:
6262  case Expr::CXXDeleteExprClass:
6263  case Expr::CXXPseudoDestructorExprClass:
6264  case Expr::UnresolvedLookupExprClass:
6265  case Expr::DependentScopeDeclRefExprClass:
6266  case Expr::CXXConstructExprClass:
6267  case Expr::CXXBindTemporaryExprClass:
6268  case Expr::ExprWithCleanupsClass:
6269  case Expr::CXXTemporaryObjectExprClass:
6270  case Expr::CXXUnresolvedConstructExprClass:
6271  case Expr::CXXDependentScopeMemberExprClass:
6272  case Expr::UnresolvedMemberExprClass:
6273  case Expr::ObjCStringLiteralClass:
6274  case Expr::ObjCNumericLiteralClass:
6275  case Expr::ObjCArrayLiteralClass:
6276  case Expr::ObjCDictionaryLiteralClass:
6277  case Expr::ObjCEncodeExprClass:
6278  case Expr::ObjCMessageExprClass:
6279  case Expr::ObjCSelectorExprClass:
6280  case Expr::ObjCProtocolExprClass:
6281  case Expr::ObjCIvarRefExprClass:
6282  case Expr::ObjCPropertyRefExprClass:
6283  case Expr::ObjCSubscriptRefExprClass:
6284  case Expr::ObjCIsaExprClass:
6285  case Expr::ShuffleVectorExprClass:
6286  case Expr::BlockExprClass:
6287  case Expr::NoStmtClass:
6288  case Expr::OpaqueValueExprClass:
6289  case Expr::PackExpansionExprClass:
6290  case Expr::SubstNonTypeTemplateParmPackExprClass:
6291  case Expr::AsTypeExprClass:
6292  case Expr::ObjCIndirectCopyRestoreExprClass:
6293  case Expr::MaterializeTemporaryExprClass:
6294  case Expr::PseudoObjectExprClass:
6295  case Expr::AtomicExprClass:
6296  case Expr::InitListExprClass:
6297  case Expr::LambdaExprClass:
6298    return ICEDiag(2, E->getLocStart());
6299
6300  case Expr::SizeOfPackExprClass:
6301  case Expr::GNUNullExprClass:
6302    // GCC considers the GNU __null value to be an integral constant expression.
6303    return NoDiag();
6304
6305  case Expr::SubstNonTypeTemplateParmExprClass:
6306    return
6307      CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6308
6309  case Expr::ParenExprClass:
6310    return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
6311  case Expr::GenericSelectionExprClass:
6312    return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
6313  case Expr::IntegerLiteralClass:
6314  case Expr::CharacterLiteralClass:
6315  case Expr::ObjCBoolLiteralExprClass:
6316  case Expr::CXXBoolLiteralExprClass:
6317  case Expr::CXXScalarValueInitExprClass:
6318  case Expr::UnaryTypeTraitExprClass:
6319  case Expr::BinaryTypeTraitExprClass:
6320  case Expr::TypeTraitExprClass:
6321  case Expr::ArrayTypeTraitExprClass:
6322  case Expr::ExpressionTraitExprClass:
6323  case Expr::CXXNoexceptExprClass:
6324    return NoDiag();
6325  case Expr::CallExprClass:
6326  case Expr::CXXOperatorCallExprClass: {
6327    // C99 6.6/3 allows function calls within unevaluated subexpressions of
6328    // constant expressions, but they can never be ICEs because an ICE cannot
6329    // contain an operand of (pointer to) function type.
6330    const CallExpr *CE = cast<CallExpr>(E);
6331    if (CE->isBuiltinCall())
6332      return CheckEvalInICE(E, Ctx);
6333    return ICEDiag(2, E->getLocStart());
6334  }
6335  case Expr::DeclRefExprClass: {
6336    if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6337      return NoDiag();
6338    const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
6339    if (Ctx.getLangOpts().CPlusPlus &&
6340        D && IsConstNonVolatile(D->getType())) {
6341      // Parameter variables are never constants.  Without this check,
6342      // getAnyInitializer() can find a default argument, which leads
6343      // to chaos.
6344      if (isa<ParmVarDecl>(D))
6345        return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6346
6347      // C++ 7.1.5.1p2
6348      //   A variable of non-volatile const-qualified integral or enumeration
6349      //   type initialized by an ICE can be used in ICEs.
6350      if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
6351        if (!Dcl->getType()->isIntegralOrEnumerationType())
6352          return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6353
6354        const VarDecl *VD;
6355        // Look for a declaration of this variable that has an initializer, and
6356        // check whether it is an ICE.
6357        if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6358          return NoDiag();
6359        else
6360          return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6361      }
6362    }
6363    return ICEDiag(2, E->getLocStart());
6364  }
6365  case Expr::UnaryOperatorClass: {
6366    const UnaryOperator *Exp = cast<UnaryOperator>(E);
6367    switch (Exp->getOpcode()) {
6368    case UO_PostInc:
6369    case UO_PostDec:
6370    case UO_PreInc:
6371    case UO_PreDec:
6372    case UO_AddrOf:
6373    case UO_Deref:
6374      // C99 6.6/3 allows increment and decrement within unevaluated
6375      // subexpressions of constant expressions, but they can never be ICEs
6376      // because an ICE cannot contain an lvalue operand.
6377      return ICEDiag(2, E->getLocStart());
6378    case UO_Extension:
6379    case UO_LNot:
6380    case UO_Plus:
6381    case UO_Minus:
6382    case UO_Not:
6383    case UO_Real:
6384    case UO_Imag:
6385      return CheckICE(Exp->getSubExpr(), Ctx);
6386    }
6387
6388    // OffsetOf falls through here.
6389  }
6390  case Expr::OffsetOfExprClass: {
6391      // Note that per C99, offsetof must be an ICE. And AFAIK, using
6392      // EvaluateAsRValue matches the proposed gcc behavior for cases like
6393      // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
6394      // compliance: we should warn earlier for offsetof expressions with
6395      // array subscripts that aren't ICEs, and if the array subscripts
6396      // are ICEs, the value of the offsetof must be an integer constant.
6397      return CheckEvalInICE(E, Ctx);
6398  }
6399  case Expr::UnaryExprOrTypeTraitExprClass: {
6400    const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6401    if ((Exp->getKind() ==  UETT_SizeOf) &&
6402        Exp->getTypeOfArgument()->isVariableArrayType())
6403      return ICEDiag(2, E->getLocStart());
6404    return NoDiag();
6405  }
6406  case Expr::BinaryOperatorClass: {
6407    const BinaryOperator *Exp = cast<BinaryOperator>(E);
6408    switch (Exp->getOpcode()) {
6409    case BO_PtrMemD:
6410    case BO_PtrMemI:
6411    case BO_Assign:
6412    case BO_MulAssign:
6413    case BO_DivAssign:
6414    case BO_RemAssign:
6415    case BO_AddAssign:
6416    case BO_SubAssign:
6417    case BO_ShlAssign:
6418    case BO_ShrAssign:
6419    case BO_AndAssign:
6420    case BO_XorAssign:
6421    case BO_OrAssign:
6422      // C99 6.6/3 allows assignments within unevaluated subexpressions of
6423      // constant expressions, but they can never be ICEs because an ICE cannot
6424      // contain an lvalue operand.
6425      return ICEDiag(2, E->getLocStart());
6426
6427    case BO_Mul:
6428    case BO_Div:
6429    case BO_Rem:
6430    case BO_Add:
6431    case BO_Sub:
6432    case BO_Shl:
6433    case BO_Shr:
6434    case BO_LT:
6435    case BO_GT:
6436    case BO_LE:
6437    case BO_GE:
6438    case BO_EQ:
6439    case BO_NE:
6440    case BO_And:
6441    case BO_Xor:
6442    case BO_Or:
6443    case BO_Comma: {
6444      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6445      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6446      if (Exp->getOpcode() == BO_Div ||
6447          Exp->getOpcode() == BO_Rem) {
6448        // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
6449        // we don't evaluate one.
6450        if (LHSResult.Val == 0 && RHSResult.Val == 0) {
6451          llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
6452          if (REval == 0)
6453            return ICEDiag(1, E->getLocStart());
6454          if (REval.isSigned() && REval.isAllOnesValue()) {
6455            llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
6456            if (LEval.isMinSignedValue())
6457              return ICEDiag(1, E->getLocStart());
6458          }
6459        }
6460      }
6461      if (Exp->getOpcode() == BO_Comma) {
6462        if (Ctx.getLangOpts().C99) {
6463          // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6464          // if it isn't evaluated.
6465          if (LHSResult.Val == 0 && RHSResult.Val == 0)
6466            return ICEDiag(1, E->getLocStart());
6467        } else {
6468          // In both C89 and C++, commas in ICEs are illegal.
6469          return ICEDiag(2, E->getLocStart());
6470        }
6471      }
6472      if (LHSResult.Val >= RHSResult.Val)
6473        return LHSResult;
6474      return RHSResult;
6475    }
6476    case BO_LAnd:
6477    case BO_LOr: {
6478      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6479      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6480      if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6481        // Rare case where the RHS has a comma "side-effect"; we need
6482        // to actually check the condition to see whether the side
6483        // with the comma is evaluated.
6484        if ((Exp->getOpcode() == BO_LAnd) !=
6485            (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
6486          return RHSResult;
6487        return NoDiag();
6488      }
6489
6490      if (LHSResult.Val >= RHSResult.Val)
6491        return LHSResult;
6492      return RHSResult;
6493    }
6494    }
6495  }
6496  case Expr::ImplicitCastExprClass:
6497  case Expr::CStyleCastExprClass:
6498  case Expr::CXXFunctionalCastExprClass:
6499  case Expr::CXXStaticCastExprClass:
6500  case Expr::CXXReinterpretCastExprClass:
6501  case Expr::CXXConstCastExprClass:
6502  case Expr::ObjCBridgedCastExprClass: {
6503    const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
6504    if (isa<ExplicitCastExpr>(E)) {
6505      if (const FloatingLiteral *FL
6506            = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6507        unsigned DestWidth = Ctx.getIntWidth(E->getType());
6508        bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6509        APSInt IgnoredVal(DestWidth, !DestSigned);
6510        bool Ignored;
6511        // If the value does not fit in the destination type, the behavior is
6512        // undefined, so we are not required to treat it as a constant
6513        // expression.
6514        if (FL->getValue().convertToInteger(IgnoredVal,
6515                                            llvm::APFloat::rmTowardZero,
6516                                            &Ignored) & APFloat::opInvalidOp)
6517          return ICEDiag(2, E->getLocStart());
6518        return NoDiag();
6519      }
6520    }
6521    switch (cast<CastExpr>(E)->getCastKind()) {
6522    case CK_LValueToRValue:
6523    case CK_AtomicToNonAtomic:
6524    case CK_NonAtomicToAtomic:
6525    case CK_NoOp:
6526    case CK_IntegralToBoolean:
6527    case CK_IntegralCast:
6528      return CheckICE(SubExpr, Ctx);
6529    default:
6530      return ICEDiag(2, E->getLocStart());
6531    }
6532  }
6533  case Expr::BinaryConditionalOperatorClass: {
6534    const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6535    ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6536    if (CommonResult.Val == 2) return CommonResult;
6537    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6538    if (FalseResult.Val == 2) return FalseResult;
6539    if (CommonResult.Val == 1) return CommonResult;
6540    if (FalseResult.Val == 1 &&
6541        Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
6542    return FalseResult;
6543  }
6544  case Expr::ConditionalOperatorClass: {
6545    const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6546    // If the condition (ignoring parens) is a __builtin_constant_p call,
6547    // then only the true side is actually considered in an integer constant
6548    // expression, and it is fully evaluated.  This is an important GNU
6549    // extension.  See GCC PR38377 for discussion.
6550    if (const CallExpr *CallCE
6551        = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
6552      if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6553        return CheckEvalInICE(E, Ctx);
6554    ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
6555    if (CondResult.Val == 2)
6556      return CondResult;
6557
6558    ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6559    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6560
6561    if (TrueResult.Val == 2)
6562      return TrueResult;
6563    if (FalseResult.Val == 2)
6564      return FalseResult;
6565    if (CondResult.Val == 1)
6566      return CondResult;
6567    if (TrueResult.Val == 0 && FalseResult.Val == 0)
6568      return NoDiag();
6569    // Rare case where the diagnostics depend on which side is evaluated
6570    // Note that if we get here, CondResult is 0, and at least one of
6571    // TrueResult and FalseResult is non-zero.
6572    if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
6573      return FalseResult;
6574    }
6575    return TrueResult;
6576  }
6577  case Expr::CXXDefaultArgExprClass:
6578    return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6579  case Expr::ChooseExprClass: {
6580    return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6581  }
6582  }
6583
6584  llvm_unreachable("Invalid StmtClass!");
6585}
6586
6587/// Evaluate an expression as a C++11 integral constant expression.
6588static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6589                                                    const Expr *E,
6590                                                    llvm::APSInt *Value,
6591                                                    SourceLocation *Loc) {
6592  if (!E->getType()->isIntegralOrEnumerationType()) {
6593    if (Loc) *Loc = E->getExprLoc();
6594    return false;
6595  }
6596
6597  APValue Result;
6598  if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
6599    return false;
6600
6601  assert(Result.isInt() && "pointer cast to int is not an ICE");
6602  if (Value) *Value = Result.getInt();
6603  return true;
6604}
6605
6606bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
6607  if (Ctx.getLangOpts().CPlusPlus0x)
6608    return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6609
6610  ICEDiag d = CheckICE(this, Ctx);
6611  if (d.Val != 0) {
6612    if (Loc) *Loc = d.Loc;
6613    return false;
6614  }
6615  return true;
6616}
6617
6618bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6619                                 SourceLocation *Loc, bool isEvaluated) const {
6620  if (Ctx.getLangOpts().CPlusPlus0x)
6621    return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6622
6623  if (!isIntegerConstantExpr(Ctx, Loc))
6624    return false;
6625  if (!EvaluateAsInt(Value, Ctx))
6626    llvm_unreachable("ICE cannot be evaluated!");
6627  return true;
6628}
6629
6630bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6631  return CheckICE(this, Ctx).Val == 0;
6632}
6633
6634bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6635                               SourceLocation *Loc) const {
6636  // We support this checking in C++98 mode in order to diagnose compatibility
6637  // issues.
6638  assert(Ctx.getLangOpts().CPlusPlus);
6639
6640  // Build evaluation settings.
6641  Expr::EvalStatus Status;
6642  llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6643  Status.Diag = &Diags;
6644  EvalInfo Info(Ctx, Status);
6645
6646  APValue Scratch;
6647  bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6648
6649  if (!Diags.empty()) {
6650    IsConstExpr = false;
6651    if (Loc) *Loc = Diags[0].first;
6652  } else if (!IsConstExpr) {
6653    // FIXME: This shouldn't happen.
6654    if (Loc) *Loc = getExprLoc();
6655  }
6656
6657  return IsConstExpr;
6658}
6659
6660bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6661                                   llvm::SmallVectorImpl<
6662                                     PartialDiagnosticAt> &Diags) {
6663  // FIXME: It would be useful to check constexpr function templates, but at the
6664  // moment the constant expression evaluator cannot cope with the non-rigorous
6665  // ASTs which we build for dependent expressions.
6666  if (FD->isDependentContext())
6667    return true;
6668
6669  Expr::EvalStatus Status;
6670  Status.Diag = &Diags;
6671
6672  EvalInfo Info(FD->getASTContext(), Status);
6673  Info.CheckingPotentialConstantExpression = true;
6674
6675  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6676  const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6677
6678  // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6679  // is a temporary being used as the 'this' pointer.
6680  LValue This;
6681  ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6682  This.set(&VIE, Info.CurrentCall->Index);
6683
6684  ArrayRef<const Expr*> Args;
6685
6686  SourceLocation Loc = FD->getLocation();
6687
6688  APValue Scratch;
6689  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
6690    HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6691  else
6692    HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6693                       Args, FD->getBody(), Info, Scratch);
6694
6695  return Diags.empty();
6696}
6697