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