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