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