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