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