1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "clang/AST/APValue.h"
36 #include "clang/AST/ASTContext.h"
37 #include "clang/AST/ASTDiagnostic.h"
38 #include "clang/AST/ASTLambda.h"
39 #include "clang/AST/CharUnits.h"
40 #include "clang/AST/CurrentSourceLocExprScope.h"
41 #include "clang/AST/CXXInheritance.h"
42 #include "clang/AST/Expr.h"
43 #include "clang/AST/OSLog.h"
44 #include "clang/AST/RecordLayout.h"
45 #include "clang/AST/StmtVisitor.h"
46 #include "clang/AST/TypeLoc.h"
47 #include "clang/Basic/Builtins.h"
48 #include "clang/Basic/FixedPoint.h"
49 #include "clang/Basic/TargetInfo.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include <cstring>
53 #include <functional>
54 
55 #define DEBUG_TYPE "exprconstant"
56 
57 using namespace clang;
58 using llvm::APSInt;
59 using llvm::APFloat;
60 
61 static bool IsGlobalLValue(APValue::LValueBase B);
62 
63 namespace {
64   struct LValue;
65   struct CallStackFrame;
66   struct EvalInfo;
67 
68   using SourceLocExprScopeGuard =
69       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
70 
71   static QualType getType(APValue::LValueBase B) {
72     if (!B) return QualType();
73     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
74       // FIXME: It's unclear where we're supposed to take the type from, and
75       // this actually matters for arrays of unknown bound. Eg:
76       //
77       // extern int arr[]; void f() { extern int arr[3]; };
78       // constexpr int *p = &arr[1]; // valid?
79       //
80       // For now, we take the array bound from the most recent declaration.
81       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
82            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
83         QualType T = Redecl->getType();
84         if (!T->isIncompleteArrayType())
85           return T;
86       }
87       return D->getType();
88     }
89 
90     if (B.is<TypeInfoLValue>())
91       return B.getTypeInfoType();
92 
93     const Expr *Base = B.get<const Expr*>();
94 
95     // For a materialized temporary, the type of the temporary we materialized
96     // may not be the type of the expression.
97     if (const MaterializeTemporaryExpr *MTE =
98             dyn_cast<MaterializeTemporaryExpr>(Base)) {
99       SmallVector<const Expr *, 2> CommaLHSs;
100       SmallVector<SubobjectAdjustment, 2> Adjustments;
101       const Expr *Temp = MTE->GetTemporaryExpr();
102       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
103                                                                Adjustments);
104       // Keep any cv-qualifiers from the reference if we generated a temporary
105       // for it directly. Otherwise use the type after adjustment.
106       if (!Adjustments.empty())
107         return Inner->getType();
108     }
109 
110     return Base->getType();
111   }
112 
113   /// Get an LValue path entry, which is known to not be an array index, as a
114   /// field declaration.
115   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
116     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
117   }
118   /// Get an LValue path entry, which is known to not be an array index, as a
119   /// base class declaration.
120   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
121     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
122   }
123   /// Determine whether this LValue path entry for a base class names a virtual
124   /// base class.
125   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
126     return E.getAsBaseOrMember().getInt();
127   }
128 
129   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
130   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
131     const FunctionDecl *Callee = CE->getDirectCallee();
132     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
133   }
134 
135   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
136   /// This will look through a single cast.
137   ///
138   /// Returns null if we couldn't unwrap a function with alloc_size.
139   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
140     if (!E->getType()->isPointerType())
141       return nullptr;
142 
143     E = E->IgnoreParens();
144     // If we're doing a variable assignment from e.g. malloc(N), there will
145     // probably be a cast of some kind. In exotic cases, we might also see a
146     // top-level ExprWithCleanups. Ignore them either way.
147     if (const auto *FE = dyn_cast<FullExpr>(E))
148       E = FE->getSubExpr()->IgnoreParens();
149 
150     if (const auto *Cast = dyn_cast<CastExpr>(E))
151       E = Cast->getSubExpr()->IgnoreParens();
152 
153     if (const auto *CE = dyn_cast<CallExpr>(E))
154       return getAllocSizeAttr(CE) ? CE : nullptr;
155     return nullptr;
156   }
157 
158   /// Determines whether or not the given Base contains a call to a function
159   /// with the alloc_size attribute.
160   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
161     const auto *E = Base.dyn_cast<const Expr *>();
162     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
163   }
164 
165   /// The bound to claim that an array of unknown bound has.
166   /// The value in MostDerivedArraySize is undefined in this case. So, set it
167   /// to an arbitrary value that's likely to loudly break things if it's used.
168   static const uint64_t AssumedSizeForUnsizedArray =
169       std::numeric_limits<uint64_t>::max() / 2;
170 
171   /// Determines if an LValue with the given LValueBase will have an unsized
172   /// array in its designator.
173   /// Find the path length and type of the most-derived subobject in the given
174   /// path, and find the size of the containing array, if any.
175   static unsigned
176   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
177                            ArrayRef<APValue::LValuePathEntry> Path,
178                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
179                            bool &FirstEntryIsUnsizedArray) {
180     // This only accepts LValueBases from APValues, and APValues don't support
181     // arrays that lack size info.
182     assert(!isBaseAnAllocSizeCall(Base) &&
183            "Unsized arrays shouldn't appear here");
184     unsigned MostDerivedLength = 0;
185     Type = getType(Base);
186 
187     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
188       if (Type->isArrayType()) {
189         const ArrayType *AT = Ctx.getAsArrayType(Type);
190         Type = AT->getElementType();
191         MostDerivedLength = I + 1;
192         IsArray = true;
193 
194         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
195           ArraySize = CAT->getSize().getZExtValue();
196         } else {
197           assert(I == 0 && "unexpected unsized array designator");
198           FirstEntryIsUnsizedArray = true;
199           ArraySize = AssumedSizeForUnsizedArray;
200         }
201       } else if (Type->isAnyComplexType()) {
202         const ComplexType *CT = Type->castAs<ComplexType>();
203         Type = CT->getElementType();
204         ArraySize = 2;
205         MostDerivedLength = I + 1;
206         IsArray = true;
207       } else if (const FieldDecl *FD = getAsField(Path[I])) {
208         Type = FD->getType();
209         ArraySize = 0;
210         MostDerivedLength = I + 1;
211         IsArray = false;
212       } else {
213         // Path[I] describes a base class.
214         ArraySize = 0;
215         IsArray = false;
216       }
217     }
218     return MostDerivedLength;
219   }
220 
221   // The order of this enum is important for diagnostics.
222   enum CheckSubobjectKind {
223     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
224     CSK_Real, CSK_Imag
225   };
226 
227   /// A path from a glvalue to a subobject of that glvalue.
228   struct SubobjectDesignator {
229     /// True if the subobject was named in a manner not supported by C++11. Such
230     /// lvalues can still be folded, but they are not core constant expressions
231     /// and we cannot perform lvalue-to-rvalue conversions on them.
232     unsigned Invalid : 1;
233 
234     /// Is this a pointer one past the end of an object?
235     unsigned IsOnePastTheEnd : 1;
236 
237     /// Indicator of whether the first entry is an unsized array.
238     unsigned FirstEntryIsAnUnsizedArray : 1;
239 
240     /// Indicator of whether the most-derived object is an array element.
241     unsigned MostDerivedIsArrayElement : 1;
242 
243     /// The length of the path to the most-derived object of which this is a
244     /// subobject.
245     unsigned MostDerivedPathLength : 28;
246 
247     /// The size of the array of which the most-derived object is an element.
248     /// This will always be 0 if the most-derived object is not an array
249     /// element. 0 is not an indicator of whether or not the most-derived object
250     /// is an array, however, because 0-length arrays are allowed.
251     ///
252     /// If the current array is an unsized array, the value of this is
253     /// undefined.
254     uint64_t MostDerivedArraySize;
255 
256     /// The type of the most derived object referred to by this address.
257     QualType MostDerivedType;
258 
259     typedef APValue::LValuePathEntry PathEntry;
260 
261     /// The entries on the path from the glvalue to the designated subobject.
262     SmallVector<PathEntry, 8> Entries;
263 
264     SubobjectDesignator() : Invalid(true) {}
265 
266     explicit SubobjectDesignator(QualType T)
267         : Invalid(false), IsOnePastTheEnd(false),
268           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
269           MostDerivedPathLength(0), MostDerivedArraySize(0),
270           MostDerivedType(T) {}
271 
272     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
273         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
274           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
275           MostDerivedPathLength(0), MostDerivedArraySize(0) {
276       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
277       if (!Invalid) {
278         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
279         ArrayRef<PathEntry> VEntries = V.getLValuePath();
280         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
281         if (V.getLValueBase()) {
282           bool IsArray = false;
283           bool FirstIsUnsizedArray = false;
284           MostDerivedPathLength = findMostDerivedSubobject(
285               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
286               MostDerivedType, IsArray, FirstIsUnsizedArray);
287           MostDerivedIsArrayElement = IsArray;
288           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
289         }
290       }
291     }
292 
293     void setInvalid() {
294       Invalid = true;
295       Entries.clear();
296     }
297 
298     /// Determine whether the most derived subobject is an array without a
299     /// known bound.
300     bool isMostDerivedAnUnsizedArray() const {
301       assert(!Invalid && "Calling this makes no sense on invalid designators");
302       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
303     }
304 
305     /// Determine what the most derived array's size is. Results in an assertion
306     /// failure if the most derived array lacks a size.
307     uint64_t getMostDerivedArraySize() const {
308       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
309       return MostDerivedArraySize;
310     }
311 
312     /// Determine whether this is a one-past-the-end pointer.
313     bool isOnePastTheEnd() const {
314       assert(!Invalid);
315       if (IsOnePastTheEnd)
316         return true;
317       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
318           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
319               MostDerivedArraySize)
320         return true;
321       return false;
322     }
323 
324     /// Get the range of valid index adjustments in the form
325     ///   {maximum value that can be subtracted from this pointer,
326     ///    maximum value that can be added to this pointer}
327     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
328       if (Invalid || isMostDerivedAnUnsizedArray())
329         return {0, 0};
330 
331       // [expr.add]p4: For the purposes of these operators, a pointer to a
332       // nonarray object behaves the same as a pointer to the first element of
333       // an array of length one with the type of the object as its element type.
334       bool IsArray = MostDerivedPathLength == Entries.size() &&
335                      MostDerivedIsArrayElement;
336       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
337                                     : (uint64_t)IsOnePastTheEnd;
338       uint64_t ArraySize =
339           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
340       return {ArrayIndex, ArraySize - ArrayIndex};
341     }
342 
343     /// Check that this refers to a valid subobject.
344     bool isValidSubobject() const {
345       if (Invalid)
346         return false;
347       return !isOnePastTheEnd();
348     }
349     /// Check that this refers to a valid subobject, and if not, produce a
350     /// relevant diagnostic and set the designator as invalid.
351     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
352 
353     /// Get the type of the designated object.
354     QualType getType(ASTContext &Ctx) const {
355       assert(!Invalid && "invalid designator has no subobject type");
356       return MostDerivedPathLength == Entries.size()
357                  ? MostDerivedType
358                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
359     }
360 
361     /// Update this designator to refer to the first element within this array.
362     void addArrayUnchecked(const ConstantArrayType *CAT) {
363       Entries.push_back(PathEntry::ArrayIndex(0));
364 
365       // This is a most-derived object.
366       MostDerivedType = CAT->getElementType();
367       MostDerivedIsArrayElement = true;
368       MostDerivedArraySize = CAT->getSize().getZExtValue();
369       MostDerivedPathLength = Entries.size();
370     }
371     /// Update this designator to refer to the first element within the array of
372     /// elements of type T. This is an array of unknown size.
373     void addUnsizedArrayUnchecked(QualType ElemTy) {
374       Entries.push_back(PathEntry::ArrayIndex(0));
375 
376       MostDerivedType = ElemTy;
377       MostDerivedIsArrayElement = true;
378       // The value in MostDerivedArraySize is undefined in this case. So, set it
379       // to an arbitrary value that's likely to loudly break things if it's
380       // used.
381       MostDerivedArraySize = AssumedSizeForUnsizedArray;
382       MostDerivedPathLength = Entries.size();
383     }
384     /// Update this designator to refer to the given base or member of this
385     /// object.
386     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
387       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
388 
389       // If this isn't a base class, it's a new most-derived object.
390       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
391         MostDerivedType = FD->getType();
392         MostDerivedIsArrayElement = false;
393         MostDerivedArraySize = 0;
394         MostDerivedPathLength = Entries.size();
395       }
396     }
397     /// Update this designator to refer to the given complex component.
398     void addComplexUnchecked(QualType EltTy, bool Imag) {
399       Entries.push_back(PathEntry::ArrayIndex(Imag));
400 
401       // This is technically a most-derived object, though in practice this
402       // is unlikely to matter.
403       MostDerivedType = EltTy;
404       MostDerivedIsArrayElement = true;
405       MostDerivedArraySize = 2;
406       MostDerivedPathLength = Entries.size();
407     }
408     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
409     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
410                                    const APSInt &N);
411     /// Add N to the address of this subobject.
412     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
413       if (Invalid || !N) return;
414       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
415       if (isMostDerivedAnUnsizedArray()) {
416         diagnoseUnsizedArrayPointerArithmetic(Info, E);
417         // Can't verify -- trust that the user is doing the right thing (or if
418         // not, trust that the caller will catch the bad behavior).
419         // FIXME: Should we reject if this overflows, at least?
420         Entries.back() = PathEntry::ArrayIndex(
421             Entries.back().getAsArrayIndex() + TruncatedN);
422         return;
423       }
424 
425       // [expr.add]p4: For the purposes of these operators, a pointer to a
426       // nonarray object behaves the same as a pointer to the first element of
427       // an array of length one with the type of the object as its element type.
428       bool IsArray = MostDerivedPathLength == Entries.size() &&
429                      MostDerivedIsArrayElement;
430       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
431                                     : (uint64_t)IsOnePastTheEnd;
432       uint64_t ArraySize =
433           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
434 
435       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
436         // Calculate the actual index in a wide enough type, so we can include
437         // it in the note.
438         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
439         (llvm::APInt&)N += ArrayIndex;
440         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
441         diagnosePointerArithmetic(Info, E, N);
442         setInvalid();
443         return;
444       }
445 
446       ArrayIndex += TruncatedN;
447       assert(ArrayIndex <= ArraySize &&
448              "bounds check succeeded for out-of-bounds index");
449 
450       if (IsArray)
451         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
452       else
453         IsOnePastTheEnd = (ArrayIndex != 0);
454     }
455   };
456 
457   /// A stack frame in the constexpr call stack.
458   struct CallStackFrame {
459     EvalInfo &Info;
460 
461     /// Parent - The caller of this stack frame.
462     CallStackFrame *Caller;
463 
464     /// Callee - The function which was called.
465     const FunctionDecl *Callee;
466 
467     /// This - The binding for the this pointer in this call, if any.
468     const LValue *This;
469 
470     /// Arguments - Parameter bindings for this function call, indexed by
471     /// parameters' function scope indices.
472     APValue *Arguments;
473 
474     /// Source location information about the default argument or default
475     /// initializer expression we're evaluating, if any.
476     CurrentSourceLocExprScope CurSourceLocExprScope;
477 
478     // Note that we intentionally use std::map here so that references to
479     // values are stable.
480     typedef std::pair<const void *, unsigned> MapKeyTy;
481     typedef std::map<MapKeyTy, APValue> MapTy;
482     /// Temporaries - Temporary lvalues materialized within this stack frame.
483     MapTy Temporaries;
484 
485     /// CallLoc - The location of the call expression for this call.
486     SourceLocation CallLoc;
487 
488     /// Index - The call index of this call.
489     unsigned Index;
490 
491     /// The stack of integers for tracking version numbers for temporaries.
492     SmallVector<unsigned, 2> TempVersionStack = {1};
493     unsigned CurTempVersion = TempVersionStack.back();
494 
495     unsigned getTempVersion() const { return TempVersionStack.back(); }
496 
497     void pushTempVersion() {
498       TempVersionStack.push_back(++CurTempVersion);
499     }
500 
501     void popTempVersion() {
502       TempVersionStack.pop_back();
503     }
504 
505     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
506     // on the overall stack usage of deeply-recursing constexpr evaluations.
507     // (We should cache this map rather than recomputing it repeatedly.)
508     // But let's try this and see how it goes; we can look into caching the map
509     // as a later change.
510 
511     /// LambdaCaptureFields - Mapping from captured variables/this to
512     /// corresponding data members in the closure class.
513     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
514     FieldDecl *LambdaThisCaptureField;
515 
516     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
517                    const FunctionDecl *Callee, const LValue *This,
518                    APValue *Arguments);
519     ~CallStackFrame();
520 
521     // Return the temporary for Key whose version number is Version.
522     APValue *getTemporary(const void *Key, unsigned Version) {
523       MapKeyTy KV(Key, Version);
524       auto LB = Temporaries.lower_bound(KV);
525       if (LB != Temporaries.end() && LB->first == KV)
526         return &LB->second;
527       // Pair (Key,Version) wasn't found in the map. Check that no elements
528       // in the map have 'Key' as their key.
529       assert((LB == Temporaries.end() || LB->first.first != Key) &&
530              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
531              "Element with key 'Key' found in map");
532       return nullptr;
533     }
534 
535     // Return the current temporary for Key in the map.
536     APValue *getCurrentTemporary(const void *Key) {
537       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
538       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
539         return &std::prev(UB)->second;
540       return nullptr;
541     }
542 
543     // Return the version number of the current temporary for Key.
544     unsigned getCurrentTemporaryVersion(const void *Key) const {
545       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
546       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
547         return std::prev(UB)->first.second;
548       return 0;
549     }
550 
551     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
552   };
553 
554   /// Temporarily override 'this'.
555   class ThisOverrideRAII {
556   public:
557     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
558         : Frame(Frame), OldThis(Frame.This) {
559       if (Enable)
560         Frame.This = NewThis;
561     }
562     ~ThisOverrideRAII() {
563       Frame.This = OldThis;
564     }
565   private:
566     CallStackFrame &Frame;
567     const LValue *OldThis;
568   };
569 
570   /// A partial diagnostic which we might know in advance that we are not going
571   /// to emit.
572   class OptionalDiagnostic {
573     PartialDiagnostic *Diag;
574 
575   public:
576     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
577       : Diag(Diag) {}
578 
579     template<typename T>
580     OptionalDiagnostic &operator<<(const T &v) {
581       if (Diag)
582         *Diag << v;
583       return *this;
584     }
585 
586     OptionalDiagnostic &operator<<(const APSInt &I) {
587       if (Diag) {
588         SmallVector<char, 32> Buffer;
589         I.toString(Buffer);
590         *Diag << StringRef(Buffer.data(), Buffer.size());
591       }
592       return *this;
593     }
594 
595     OptionalDiagnostic &operator<<(const APFloat &F) {
596       if (Diag) {
597         // FIXME: Force the precision of the source value down so we don't
598         // print digits which are usually useless (we don't really care here if
599         // we truncate a digit by accident in edge cases).  Ideally,
600         // APFloat::toString would automatically print the shortest
601         // representation which rounds to the correct value, but it's a bit
602         // tricky to implement.
603         unsigned precision =
604             llvm::APFloat::semanticsPrecision(F.getSemantics());
605         precision = (precision * 59 + 195) / 196;
606         SmallVector<char, 32> Buffer;
607         F.toString(Buffer, precision);
608         *Diag << StringRef(Buffer.data(), Buffer.size());
609       }
610       return *this;
611     }
612 
613     OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
614       if (Diag) {
615         SmallVector<char, 32> Buffer;
616         FX.toString(Buffer);
617         *Diag << StringRef(Buffer.data(), Buffer.size());
618       }
619       return *this;
620     }
621   };
622 
623   /// A cleanup, and a flag indicating whether it is lifetime-extended.
624   class Cleanup {
625     llvm::PointerIntPair<APValue*, 1, bool> Value;
626 
627   public:
628     Cleanup(APValue *Val, bool IsLifetimeExtended)
629         : Value(Val, IsLifetimeExtended) {}
630 
631     bool isLifetimeExtended() const { return Value.getInt(); }
632     void endLifetime() {
633       *Value.getPointer() = APValue();
634     }
635   };
636 
637   /// A reference to an object whose construction we are currently evaluating.
638   struct ObjectUnderConstruction {
639     APValue::LValueBase Base;
640     ArrayRef<APValue::LValuePathEntry> Path;
641     friend bool operator==(const ObjectUnderConstruction &LHS,
642                            const ObjectUnderConstruction &RHS) {
643       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
644     }
645     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
646       return llvm::hash_combine(Obj.Base, Obj.Path);
647     }
648   };
649   enum class ConstructionPhase { None, Bases, AfterBases };
650 }
651 
652 namespace llvm {
653 template<> struct DenseMapInfo<ObjectUnderConstruction> {
654   using Base = DenseMapInfo<APValue::LValueBase>;
655   static ObjectUnderConstruction getEmptyKey() {
656     return {Base::getEmptyKey(), {}}; }
657   static ObjectUnderConstruction getTombstoneKey() {
658     return {Base::getTombstoneKey(), {}};
659   }
660   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
661     return hash_value(Object);
662   }
663   static bool isEqual(const ObjectUnderConstruction &LHS,
664                       const ObjectUnderConstruction &RHS) {
665     return LHS == RHS;
666   }
667 };
668 }
669 
670 namespace {
671   /// EvalInfo - This is a private struct used by the evaluator to capture
672   /// information about a subexpression as it is folded.  It retains information
673   /// about the AST context, but also maintains information about the folded
674   /// expression.
675   ///
676   /// If an expression could be evaluated, it is still possible it is not a C
677   /// "integer constant expression" or constant expression.  If not, this struct
678   /// captures information about how and why not.
679   ///
680   /// One bit of information passed *into* the request for constant folding
681   /// indicates whether the subexpression is "evaluated" or not according to C
682   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
683   /// evaluate the expression regardless of what the RHS is, but C only allows
684   /// certain things in certain situations.
685   struct EvalInfo {
686     ASTContext &Ctx;
687 
688     /// EvalStatus - Contains information about the evaluation.
689     Expr::EvalStatus &EvalStatus;
690 
691     /// CurrentCall - The top of the constexpr call stack.
692     CallStackFrame *CurrentCall;
693 
694     /// CallStackDepth - The number of calls in the call stack right now.
695     unsigned CallStackDepth;
696 
697     /// NextCallIndex - The next call index to assign.
698     unsigned NextCallIndex;
699 
700     /// StepsLeft - The remaining number of evaluation steps we're permitted
701     /// to perform. This is essentially a limit for the number of statements
702     /// we will evaluate.
703     unsigned StepsLeft;
704 
705     /// BottomFrame - The frame in which evaluation started. This must be
706     /// initialized after CurrentCall and CallStackDepth.
707     CallStackFrame BottomFrame;
708 
709     /// A stack of values whose lifetimes end at the end of some surrounding
710     /// evaluation frame.
711     llvm::SmallVector<Cleanup, 16> CleanupStack;
712 
713     /// EvaluatingDecl - This is the declaration whose initializer is being
714     /// evaluated, if any.
715     APValue::LValueBase EvaluatingDecl;
716 
717     /// EvaluatingDeclValue - This is the value being constructed for the
718     /// declaration whose initializer is being evaluated, if any.
719     APValue *EvaluatingDeclValue;
720 
721     /// Set of objects that are currently being constructed.
722     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
723         ObjectsUnderConstruction;
724 
725     struct EvaluatingConstructorRAII {
726       EvalInfo &EI;
727       ObjectUnderConstruction Object;
728       bool DidInsert;
729       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
730                                 bool HasBases)
731           : EI(EI), Object(Object) {
732         DidInsert =
733             EI.ObjectsUnderConstruction
734                 .insert({Object, HasBases ? ConstructionPhase::Bases
735                                           : ConstructionPhase::AfterBases})
736                 .second;
737       }
738       void finishedConstructingBases() {
739         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
740       }
741       ~EvaluatingConstructorRAII() {
742         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
743       }
744     };
745 
746     ConstructionPhase
747     isEvaluatingConstructor(APValue::LValueBase Base,
748                             ArrayRef<APValue::LValuePathEntry> Path) {
749       return ObjectsUnderConstruction.lookup({Base, Path});
750     }
751 
752     /// If we're currently speculatively evaluating, the outermost call stack
753     /// depth at which we can mutate state, otherwise 0.
754     unsigned SpeculativeEvaluationDepth = 0;
755 
756     /// The current array initialization index, if we're performing array
757     /// initialization.
758     uint64_t ArrayInitIndex = -1;
759 
760     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
761     /// notes attached to it will also be stored, otherwise they will not be.
762     bool HasActiveDiagnostic;
763 
764     /// Have we emitted a diagnostic explaining why we couldn't constant
765     /// fold (not just why it's not strictly a constant expression)?
766     bool HasFoldFailureDiagnostic;
767 
768     /// Whether or not we're in a context where the front end requires a
769     /// constant value.
770     bool InConstantContext;
771 
772     enum EvaluationMode {
773       /// Evaluate as a constant expression. Stop if we find that the expression
774       /// is not a constant expression.
775       EM_ConstantExpression,
776 
777       /// Evaluate as a potential constant expression. Keep going if we hit a
778       /// construct that we can't evaluate yet (because we don't yet know the
779       /// value of something) but stop if we hit something that could never be
780       /// a constant expression.
781       EM_PotentialConstantExpression,
782 
783       /// Fold the expression to a constant. Stop if we hit a side-effect that
784       /// we can't model.
785       EM_ConstantFold,
786 
787       /// Evaluate the expression looking for integer overflow and similar
788       /// issues. Don't worry about side-effects, and try to visit all
789       /// subexpressions.
790       EM_EvaluateForOverflow,
791 
792       /// Evaluate in any way we know how. Don't worry about side-effects that
793       /// can't be modeled.
794       EM_IgnoreSideEffects,
795 
796       /// Evaluate as a constant expression. Stop if we find that the expression
797       /// is not a constant expression. Some expressions can be retried in the
798       /// optimizer if we don't constant fold them here, but in an unevaluated
799       /// context we try to fold them immediately since the optimizer never
800       /// gets a chance to look at it.
801       EM_ConstantExpressionUnevaluated,
802 
803       /// Evaluate as a potential constant expression. Keep going if we hit a
804       /// construct that we can't evaluate yet (because we don't yet know the
805       /// value of something) but stop if we hit something that could never be
806       /// a constant expression. Some expressions can be retried in the
807       /// optimizer if we don't constant fold them here, but in an unevaluated
808       /// context we try to fold them immediately since the optimizer never
809       /// gets a chance to look at it.
810       EM_PotentialConstantExpressionUnevaluated,
811     } EvalMode;
812 
813     /// Are we checking whether the expression is a potential constant
814     /// expression?
815     bool checkingPotentialConstantExpression() const {
816       return EvalMode == EM_PotentialConstantExpression ||
817              EvalMode == EM_PotentialConstantExpressionUnevaluated;
818     }
819 
820     /// Are we checking an expression for overflow?
821     // FIXME: We should check for any kind of undefined or suspicious behavior
822     // in such constructs, not just overflow.
823     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
824 
825     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
826       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
827         CallStackDepth(0), NextCallIndex(1),
828         StepsLeft(getLangOpts().ConstexprStepLimit),
829         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
830         EvaluatingDecl((const ValueDecl *)nullptr),
831         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
832         HasFoldFailureDiagnostic(false),
833         InConstantContext(false), EvalMode(Mode) {}
834 
835     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
836       EvaluatingDecl = Base;
837       EvaluatingDeclValue = &Value;
838     }
839 
840     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
841 
842     bool CheckCallLimit(SourceLocation Loc) {
843       // Don't perform any constexpr calls (other than the call we're checking)
844       // when checking a potential constant expression.
845       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
846         return false;
847       if (NextCallIndex == 0) {
848         // NextCallIndex has wrapped around.
849         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
850         return false;
851       }
852       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
853         return true;
854       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
855         << getLangOpts().ConstexprCallDepth;
856       return false;
857     }
858 
859     std::pair<CallStackFrame *, unsigned>
860     getCallFrameAndDepth(unsigned CallIndex) {
861       assert(CallIndex && "no call index in getCallFrameAndDepth");
862       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
863       // be null in this loop.
864       unsigned Depth = CallStackDepth;
865       CallStackFrame *Frame = CurrentCall;
866       while (Frame->Index > CallIndex) {
867         Frame = Frame->Caller;
868         --Depth;
869       }
870       if (Frame->Index == CallIndex)
871         return {Frame, Depth};
872       return {nullptr, 0};
873     }
874 
875     bool nextStep(const Stmt *S) {
876       if (!StepsLeft) {
877         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
878         return false;
879       }
880       --StepsLeft;
881       return true;
882     }
883 
884   private:
885     /// Add a diagnostic to the diagnostics list.
886     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
887       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
888       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
889       return EvalStatus.Diag->back().second;
890     }
891 
892     /// Add notes containing a call stack to the current point of evaluation.
893     void addCallStack(unsigned Limit);
894 
895   private:
896     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
897                             unsigned ExtraNotes, bool IsCCEDiag) {
898 
899       if (EvalStatus.Diag) {
900         // If we have a prior diagnostic, it will be noting that the expression
901         // isn't a constant expression. This diagnostic is more important,
902         // unless we require this evaluation to produce a constant expression.
903         //
904         // FIXME: We might want to show both diagnostics to the user in
905         // EM_ConstantFold mode.
906         if (!EvalStatus.Diag->empty()) {
907           switch (EvalMode) {
908           case EM_ConstantFold:
909           case EM_IgnoreSideEffects:
910           case EM_EvaluateForOverflow:
911             if (!HasFoldFailureDiagnostic)
912               break;
913             // We've already failed to fold something. Keep that diagnostic.
914             LLVM_FALLTHROUGH;
915           case EM_ConstantExpression:
916           case EM_PotentialConstantExpression:
917           case EM_ConstantExpressionUnevaluated:
918           case EM_PotentialConstantExpressionUnevaluated:
919             HasActiveDiagnostic = false;
920             return OptionalDiagnostic();
921           }
922         }
923 
924         unsigned CallStackNotes = CallStackDepth - 1;
925         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
926         if (Limit)
927           CallStackNotes = std::min(CallStackNotes, Limit + 1);
928         if (checkingPotentialConstantExpression())
929           CallStackNotes = 0;
930 
931         HasActiveDiagnostic = true;
932         HasFoldFailureDiagnostic = !IsCCEDiag;
933         EvalStatus.Diag->clear();
934         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
935         addDiag(Loc, DiagId);
936         if (!checkingPotentialConstantExpression())
937           addCallStack(Limit);
938         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
939       }
940       HasActiveDiagnostic = false;
941       return OptionalDiagnostic();
942     }
943   public:
944     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
945     OptionalDiagnostic
946     FFDiag(SourceLocation Loc,
947           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
948           unsigned ExtraNotes = 0) {
949       return Diag(Loc, DiagId, ExtraNotes, false);
950     }
951 
952     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
953                               = diag::note_invalid_subexpr_in_const_expr,
954                             unsigned ExtraNotes = 0) {
955       if (EvalStatus.Diag)
956         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
957       HasActiveDiagnostic = false;
958       return OptionalDiagnostic();
959     }
960 
961     /// Diagnose that the evaluation does not produce a C++11 core constant
962     /// expression.
963     ///
964     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
965     /// EM_PotentialConstantExpression mode and we produce one of these.
966     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
967                                  = diag::note_invalid_subexpr_in_const_expr,
968                                unsigned ExtraNotes = 0) {
969       // Don't override a previous diagnostic. Don't bother collecting
970       // diagnostics if we're evaluating for overflow.
971       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
972         HasActiveDiagnostic = false;
973         return OptionalDiagnostic();
974       }
975       return Diag(Loc, DiagId, ExtraNotes, true);
976     }
977     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
978                                  = diag::note_invalid_subexpr_in_const_expr,
979                                unsigned ExtraNotes = 0) {
980       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
981     }
982     /// Add a note to a prior diagnostic.
983     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
984       if (!HasActiveDiagnostic)
985         return OptionalDiagnostic();
986       return OptionalDiagnostic(&addDiag(Loc, DiagId));
987     }
988 
989     /// Add a stack of notes to a prior diagnostic.
990     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
991       if (HasActiveDiagnostic) {
992         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
993                                 Diags.begin(), Diags.end());
994       }
995     }
996 
997     /// Should we continue evaluation after encountering a side-effect that we
998     /// couldn't model?
999     bool keepEvaluatingAfterSideEffect() {
1000       switch (EvalMode) {
1001       case EM_PotentialConstantExpression:
1002       case EM_PotentialConstantExpressionUnevaluated:
1003       case EM_EvaluateForOverflow:
1004       case EM_IgnoreSideEffects:
1005         return true;
1006 
1007       case EM_ConstantExpression:
1008       case EM_ConstantExpressionUnevaluated:
1009       case EM_ConstantFold:
1010         return false;
1011       }
1012       llvm_unreachable("Missed EvalMode case");
1013     }
1014 
1015     /// Note that we have had a side-effect, and determine whether we should
1016     /// keep evaluating.
1017     bool noteSideEffect() {
1018       EvalStatus.HasSideEffects = true;
1019       return keepEvaluatingAfterSideEffect();
1020     }
1021 
1022     /// Should we continue evaluation after encountering undefined behavior?
1023     bool keepEvaluatingAfterUndefinedBehavior() {
1024       switch (EvalMode) {
1025       case EM_EvaluateForOverflow:
1026       case EM_IgnoreSideEffects:
1027       case EM_ConstantFold:
1028         return true;
1029 
1030       case EM_PotentialConstantExpression:
1031       case EM_PotentialConstantExpressionUnevaluated:
1032       case EM_ConstantExpression:
1033       case EM_ConstantExpressionUnevaluated:
1034         return false;
1035       }
1036       llvm_unreachable("Missed EvalMode case");
1037     }
1038 
1039     /// Note that we hit something that was technically undefined behavior, but
1040     /// that we can evaluate past it (such as signed overflow or floating-point
1041     /// division by zero.)
1042     bool noteUndefinedBehavior() {
1043       EvalStatus.HasUndefinedBehavior = true;
1044       return keepEvaluatingAfterUndefinedBehavior();
1045     }
1046 
1047     /// Should we continue evaluation as much as possible after encountering a
1048     /// construct which can't be reduced to a value?
1049     bool keepEvaluatingAfterFailure() {
1050       if (!StepsLeft)
1051         return false;
1052 
1053       switch (EvalMode) {
1054       case EM_PotentialConstantExpression:
1055       case EM_PotentialConstantExpressionUnevaluated:
1056       case EM_EvaluateForOverflow:
1057         return true;
1058 
1059       case EM_ConstantExpression:
1060       case EM_ConstantExpressionUnevaluated:
1061       case EM_ConstantFold:
1062       case EM_IgnoreSideEffects:
1063         return false;
1064       }
1065       llvm_unreachable("Missed EvalMode case");
1066     }
1067 
1068     /// Notes that we failed to evaluate an expression that other expressions
1069     /// directly depend on, and determine if we should keep evaluating. This
1070     /// should only be called if we actually intend to keep evaluating.
1071     ///
1072     /// Call noteSideEffect() instead if we may be able to ignore the value that
1073     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1074     ///
1075     /// (Foo(), 1)      // use noteSideEffect
1076     /// (Foo() || true) // use noteSideEffect
1077     /// Foo() + 1       // use noteFailure
1078     LLVM_NODISCARD bool noteFailure() {
1079       // Failure when evaluating some expression often means there is some
1080       // subexpression whose evaluation was skipped. Therefore, (because we
1081       // don't track whether we skipped an expression when unwinding after an
1082       // evaluation failure) every evaluation failure that bubbles up from a
1083       // subexpression implies that a side-effect has potentially happened. We
1084       // skip setting the HasSideEffects flag to true until we decide to
1085       // continue evaluating after that point, which happens here.
1086       bool KeepGoing = keepEvaluatingAfterFailure();
1087       EvalStatus.HasSideEffects |= KeepGoing;
1088       return KeepGoing;
1089     }
1090 
1091     class ArrayInitLoopIndex {
1092       EvalInfo &Info;
1093       uint64_t OuterIndex;
1094 
1095     public:
1096       ArrayInitLoopIndex(EvalInfo &Info)
1097           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1098         Info.ArrayInitIndex = 0;
1099       }
1100       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1101 
1102       operator uint64_t&() { return Info.ArrayInitIndex; }
1103     };
1104   };
1105 
1106   /// Object used to treat all foldable expressions as constant expressions.
1107   struct FoldConstant {
1108     EvalInfo &Info;
1109     bool Enabled;
1110     bool HadNoPriorDiags;
1111     EvalInfo::EvaluationMode OldMode;
1112 
1113     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1114       : Info(Info),
1115         Enabled(Enabled),
1116         HadNoPriorDiags(Info.EvalStatus.Diag &&
1117                         Info.EvalStatus.Diag->empty() &&
1118                         !Info.EvalStatus.HasSideEffects),
1119         OldMode(Info.EvalMode) {
1120       if (Enabled &&
1121           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1122            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1123         Info.EvalMode = EvalInfo::EM_ConstantFold;
1124     }
1125     void keepDiagnostics() { Enabled = false; }
1126     ~FoldConstant() {
1127       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1128           !Info.EvalStatus.HasSideEffects)
1129         Info.EvalStatus.Diag->clear();
1130       Info.EvalMode = OldMode;
1131     }
1132   };
1133 
1134   /// RAII object used to set the current evaluation mode to ignore
1135   /// side-effects.
1136   struct IgnoreSideEffectsRAII {
1137     EvalInfo &Info;
1138     EvalInfo::EvaluationMode OldMode;
1139     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1140         : Info(Info), OldMode(Info.EvalMode) {
1141       if (!Info.checkingPotentialConstantExpression())
1142         Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1143     }
1144 
1145     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1146   };
1147 
1148   /// RAII object used to optionally suppress diagnostics and side-effects from
1149   /// a speculative evaluation.
1150   class SpeculativeEvaluationRAII {
1151     EvalInfo *Info = nullptr;
1152     Expr::EvalStatus OldStatus;
1153     unsigned OldSpeculativeEvaluationDepth;
1154 
1155     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1156       Info = Other.Info;
1157       OldStatus = Other.OldStatus;
1158       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1159       Other.Info = nullptr;
1160     }
1161 
1162     void maybeRestoreState() {
1163       if (!Info)
1164         return;
1165 
1166       Info->EvalStatus = OldStatus;
1167       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1168     }
1169 
1170   public:
1171     SpeculativeEvaluationRAII() = default;
1172 
1173     SpeculativeEvaluationRAII(
1174         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1175         : Info(&Info), OldStatus(Info.EvalStatus),
1176           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1177       Info.EvalStatus.Diag = NewDiag;
1178       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1179     }
1180 
1181     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1182     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1183       moveFromAndCancel(std::move(Other));
1184     }
1185 
1186     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1187       maybeRestoreState();
1188       moveFromAndCancel(std::move(Other));
1189       return *this;
1190     }
1191 
1192     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1193   };
1194 
1195   /// RAII object wrapping a full-expression or block scope, and handling
1196   /// the ending of the lifetime of temporaries created within it.
1197   template<bool IsFullExpression>
1198   class ScopeRAII {
1199     EvalInfo &Info;
1200     unsigned OldStackSize;
1201   public:
1202     ScopeRAII(EvalInfo &Info)
1203         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1204       // Push a new temporary version. This is needed to distinguish between
1205       // temporaries created in different iterations of a loop.
1206       Info.CurrentCall->pushTempVersion();
1207     }
1208     ~ScopeRAII() {
1209       // Body moved to a static method to encourage the compiler to inline away
1210       // instances of this class.
1211       cleanup(Info, OldStackSize);
1212       Info.CurrentCall->popTempVersion();
1213     }
1214   private:
1215     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1216       unsigned NewEnd = OldStackSize;
1217       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1218            I != N; ++I) {
1219         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1220           // Full-expression cleanup of a lifetime-extended temporary: nothing
1221           // to do, just move this cleanup to the right place in the stack.
1222           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1223           ++NewEnd;
1224         } else {
1225           // End the lifetime of the object.
1226           Info.CleanupStack[I].endLifetime();
1227         }
1228       }
1229       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1230                               Info.CleanupStack.end());
1231     }
1232   };
1233   typedef ScopeRAII<false> BlockScopeRAII;
1234   typedef ScopeRAII<true> FullExpressionRAII;
1235 }
1236 
1237 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1238                                          CheckSubobjectKind CSK) {
1239   if (Invalid)
1240     return false;
1241   if (isOnePastTheEnd()) {
1242     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1243       << CSK;
1244     setInvalid();
1245     return false;
1246   }
1247   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1248   // must actually be at least one array element; even a VLA cannot have a
1249   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1250   return true;
1251 }
1252 
1253 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1254                                                                 const Expr *E) {
1255   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1256   // Do not set the designator as invalid: we can represent this situation,
1257   // and correct handling of __builtin_object_size requires us to do so.
1258 }
1259 
1260 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1261                                                     const Expr *E,
1262                                                     const APSInt &N) {
1263   // If we're complaining, we must be able to statically determine the size of
1264   // the most derived array.
1265   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1266     Info.CCEDiag(E, diag::note_constexpr_array_index)
1267       << N << /*array*/ 0
1268       << static_cast<unsigned>(getMostDerivedArraySize());
1269   else
1270     Info.CCEDiag(E, diag::note_constexpr_array_index)
1271       << N << /*non-array*/ 1;
1272   setInvalid();
1273 }
1274 
1275 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1276                                const FunctionDecl *Callee, const LValue *This,
1277                                APValue *Arguments)
1278     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1279       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1280   Info.CurrentCall = this;
1281   ++Info.CallStackDepth;
1282 }
1283 
1284 CallStackFrame::~CallStackFrame() {
1285   assert(Info.CurrentCall == this && "calls retired out of order");
1286   --Info.CallStackDepth;
1287   Info.CurrentCall = Caller;
1288 }
1289 
1290 APValue &CallStackFrame::createTemporary(const void *Key,
1291                                          bool IsLifetimeExtended) {
1292   unsigned Version = Info.CurrentCall->getTempVersion();
1293   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1294   assert(Result.isUninit() && "temporary created multiple times");
1295   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1296   return Result;
1297 }
1298 
1299 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1300 
1301 void EvalInfo::addCallStack(unsigned Limit) {
1302   // Determine which calls to skip, if any.
1303   unsigned ActiveCalls = CallStackDepth - 1;
1304   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1305   if (Limit && Limit < ActiveCalls) {
1306     SkipStart = Limit / 2 + Limit % 2;
1307     SkipEnd = ActiveCalls - Limit / 2;
1308   }
1309 
1310   // Walk the call stack and add the diagnostics.
1311   unsigned CallIdx = 0;
1312   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1313        Frame = Frame->Caller, ++CallIdx) {
1314     // Skip this call?
1315     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1316       if (CallIdx == SkipStart) {
1317         // Note that we're skipping calls.
1318         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1319           << unsigned(ActiveCalls - Limit);
1320       }
1321       continue;
1322     }
1323 
1324     // Use a different note for an inheriting constructor, because from the
1325     // user's perspective it's not really a function at all.
1326     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1327       if (CD->isInheritingConstructor()) {
1328         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1329           << CD->getParent();
1330         continue;
1331       }
1332     }
1333 
1334     SmallVector<char, 128> Buffer;
1335     llvm::raw_svector_ostream Out(Buffer);
1336     describeCall(Frame, Out);
1337     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1338   }
1339 }
1340 
1341 /// Kinds of access we can perform on an object, for diagnostics. Note that
1342 /// we consider a member function call to be a kind of access, even though
1343 /// it is not formally an access of the object, because it has (largely) the
1344 /// same set of semantic restrictions.
1345 enum AccessKinds {
1346   AK_Read,
1347   AK_Assign,
1348   AK_Increment,
1349   AK_Decrement,
1350   AK_MemberCall,
1351   AK_DynamicCast,
1352   AK_TypeId,
1353 };
1354 
1355 static bool isModification(AccessKinds AK) {
1356   switch (AK) {
1357   case AK_Read:
1358   case AK_MemberCall:
1359   case AK_DynamicCast:
1360   case AK_TypeId:
1361     return false;
1362   case AK_Assign:
1363   case AK_Increment:
1364   case AK_Decrement:
1365     return true;
1366   }
1367   llvm_unreachable("unknown access kind");
1368 }
1369 
1370 /// Is this an access per the C++ definition?
1371 static bool isFormalAccess(AccessKinds AK) {
1372   return AK == AK_Read || isModification(AK);
1373 }
1374 
1375 namespace {
1376   struct ComplexValue {
1377   private:
1378     bool IsInt;
1379 
1380   public:
1381     APSInt IntReal, IntImag;
1382     APFloat FloatReal, FloatImag;
1383 
1384     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1385 
1386     void makeComplexFloat() { IsInt = false; }
1387     bool isComplexFloat() const { return !IsInt; }
1388     APFloat &getComplexFloatReal() { return FloatReal; }
1389     APFloat &getComplexFloatImag() { return FloatImag; }
1390 
1391     void makeComplexInt() { IsInt = true; }
1392     bool isComplexInt() const { return IsInt; }
1393     APSInt &getComplexIntReal() { return IntReal; }
1394     APSInt &getComplexIntImag() { return IntImag; }
1395 
1396     void moveInto(APValue &v) const {
1397       if (isComplexFloat())
1398         v = APValue(FloatReal, FloatImag);
1399       else
1400         v = APValue(IntReal, IntImag);
1401     }
1402     void setFrom(const APValue &v) {
1403       assert(v.isComplexFloat() || v.isComplexInt());
1404       if (v.isComplexFloat()) {
1405         makeComplexFloat();
1406         FloatReal = v.getComplexFloatReal();
1407         FloatImag = v.getComplexFloatImag();
1408       } else {
1409         makeComplexInt();
1410         IntReal = v.getComplexIntReal();
1411         IntImag = v.getComplexIntImag();
1412       }
1413     }
1414   };
1415 
1416   struct LValue {
1417     APValue::LValueBase Base;
1418     CharUnits Offset;
1419     SubobjectDesignator Designator;
1420     bool IsNullPtr : 1;
1421     bool InvalidBase : 1;
1422 
1423     const APValue::LValueBase getLValueBase() const { return Base; }
1424     CharUnits &getLValueOffset() { return Offset; }
1425     const CharUnits &getLValueOffset() const { return Offset; }
1426     SubobjectDesignator &getLValueDesignator() { return Designator; }
1427     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1428     bool isNullPointer() const { return IsNullPtr;}
1429 
1430     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1431     unsigned getLValueVersion() const { return Base.getVersion(); }
1432 
1433     void moveInto(APValue &V) const {
1434       if (Designator.Invalid)
1435         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1436       else {
1437         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1438         V = APValue(Base, Offset, Designator.Entries,
1439                     Designator.IsOnePastTheEnd, IsNullPtr);
1440       }
1441     }
1442     void setFrom(ASTContext &Ctx, const APValue &V) {
1443       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1444       Base = V.getLValueBase();
1445       Offset = V.getLValueOffset();
1446       InvalidBase = false;
1447       Designator = SubobjectDesignator(Ctx, V);
1448       IsNullPtr = V.isNullPointer();
1449     }
1450 
1451     void set(APValue::LValueBase B, bool BInvalid = false) {
1452 #ifndef NDEBUG
1453       // We only allow a few types of invalid bases. Enforce that here.
1454       if (BInvalid) {
1455         const auto *E = B.get<const Expr *>();
1456         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1457                "Unexpected type of invalid base");
1458       }
1459 #endif
1460 
1461       Base = B;
1462       Offset = CharUnits::fromQuantity(0);
1463       InvalidBase = BInvalid;
1464       Designator = SubobjectDesignator(getType(B));
1465       IsNullPtr = false;
1466     }
1467 
1468     void setNull(QualType PointerTy, uint64_t TargetVal) {
1469       Base = (Expr *)nullptr;
1470       Offset = CharUnits::fromQuantity(TargetVal);
1471       InvalidBase = false;
1472       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1473       IsNullPtr = true;
1474     }
1475 
1476     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1477       set(B, true);
1478     }
1479 
1480   private:
1481     // Check that this LValue is not based on a null pointer. If it is, produce
1482     // a diagnostic and mark the designator as invalid.
1483     template <typename GenDiagType>
1484     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1485       if (Designator.Invalid)
1486         return false;
1487       if (IsNullPtr) {
1488         GenDiag();
1489         Designator.setInvalid();
1490         return false;
1491       }
1492       return true;
1493     }
1494 
1495   public:
1496     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1497                           CheckSubobjectKind CSK) {
1498       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1499         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1500       });
1501     }
1502 
1503     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1504                                        AccessKinds AK) {
1505       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1506         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1507       });
1508     }
1509 
1510     // Check this LValue refers to an object. If not, set the designator to be
1511     // invalid and emit a diagnostic.
1512     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1513       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1514              Designator.checkSubobject(Info, E, CSK);
1515     }
1516 
1517     void addDecl(EvalInfo &Info, const Expr *E,
1518                  const Decl *D, bool Virtual = false) {
1519       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1520         Designator.addDeclUnchecked(D, Virtual);
1521     }
1522     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1523       if (!Designator.Entries.empty()) {
1524         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1525         Designator.setInvalid();
1526         return;
1527       }
1528       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1529         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1530         Designator.FirstEntryIsAnUnsizedArray = true;
1531         Designator.addUnsizedArrayUnchecked(ElemTy);
1532       }
1533     }
1534     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1535       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1536         Designator.addArrayUnchecked(CAT);
1537     }
1538     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1539       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1540         Designator.addComplexUnchecked(EltTy, Imag);
1541     }
1542     void clearIsNullPointer() {
1543       IsNullPtr = false;
1544     }
1545     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1546                               const APSInt &Index, CharUnits ElementSize) {
1547       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1548       // but we're not required to diagnose it and it's valid in C++.)
1549       if (!Index)
1550         return;
1551 
1552       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1553       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1554       // offsets.
1555       uint64_t Offset64 = Offset.getQuantity();
1556       uint64_t ElemSize64 = ElementSize.getQuantity();
1557       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1558       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1559 
1560       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1561         Designator.adjustIndex(Info, E, Index);
1562       clearIsNullPointer();
1563     }
1564     void adjustOffset(CharUnits N) {
1565       Offset += N;
1566       if (N.getQuantity())
1567         clearIsNullPointer();
1568     }
1569   };
1570 
1571   struct MemberPtr {
1572     MemberPtr() {}
1573     explicit MemberPtr(const ValueDecl *Decl) :
1574       DeclAndIsDerivedMember(Decl, false), Path() {}
1575 
1576     /// The member or (direct or indirect) field referred to by this member
1577     /// pointer, or 0 if this is a null member pointer.
1578     const ValueDecl *getDecl() const {
1579       return DeclAndIsDerivedMember.getPointer();
1580     }
1581     /// Is this actually a member of some type derived from the relevant class?
1582     bool isDerivedMember() const {
1583       return DeclAndIsDerivedMember.getInt();
1584     }
1585     /// Get the class which the declaration actually lives in.
1586     const CXXRecordDecl *getContainingRecord() const {
1587       return cast<CXXRecordDecl>(
1588           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1589     }
1590 
1591     void moveInto(APValue &V) const {
1592       V = APValue(getDecl(), isDerivedMember(), Path);
1593     }
1594     void setFrom(const APValue &V) {
1595       assert(V.isMemberPointer());
1596       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1597       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1598       Path.clear();
1599       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1600       Path.insert(Path.end(), P.begin(), P.end());
1601     }
1602 
1603     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1604     /// whether the member is a member of some class derived from the class type
1605     /// of the member pointer.
1606     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1607     /// Path - The path of base/derived classes from the member declaration's
1608     /// class (exclusive) to the class type of the member pointer (inclusive).
1609     SmallVector<const CXXRecordDecl*, 4> Path;
1610 
1611     /// Perform a cast towards the class of the Decl (either up or down the
1612     /// hierarchy).
1613     bool castBack(const CXXRecordDecl *Class) {
1614       assert(!Path.empty());
1615       const CXXRecordDecl *Expected;
1616       if (Path.size() >= 2)
1617         Expected = Path[Path.size() - 2];
1618       else
1619         Expected = getContainingRecord();
1620       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1621         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1622         // if B does not contain the original member and is not a base or
1623         // derived class of the class containing the original member, the result
1624         // of the cast is undefined.
1625         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1626         // (D::*). We consider that to be a language defect.
1627         return false;
1628       }
1629       Path.pop_back();
1630       return true;
1631     }
1632     /// Perform a base-to-derived member pointer cast.
1633     bool castToDerived(const CXXRecordDecl *Derived) {
1634       if (!getDecl())
1635         return true;
1636       if (!isDerivedMember()) {
1637         Path.push_back(Derived);
1638         return true;
1639       }
1640       if (!castBack(Derived))
1641         return false;
1642       if (Path.empty())
1643         DeclAndIsDerivedMember.setInt(false);
1644       return true;
1645     }
1646     /// Perform a derived-to-base member pointer cast.
1647     bool castToBase(const CXXRecordDecl *Base) {
1648       if (!getDecl())
1649         return true;
1650       if (Path.empty())
1651         DeclAndIsDerivedMember.setInt(true);
1652       if (isDerivedMember()) {
1653         Path.push_back(Base);
1654         return true;
1655       }
1656       return castBack(Base);
1657     }
1658   };
1659 
1660   /// Compare two member pointers, which are assumed to be of the same type.
1661   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1662     if (!LHS.getDecl() || !RHS.getDecl())
1663       return !LHS.getDecl() && !RHS.getDecl();
1664     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1665       return false;
1666     return LHS.Path == RHS.Path;
1667   }
1668 }
1669 
1670 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1671 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1672                             const LValue &This, const Expr *E,
1673                             bool AllowNonLiteralTypes = false);
1674 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1675                            bool InvalidBaseOK = false);
1676 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1677                             bool InvalidBaseOK = false);
1678 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1679                                   EvalInfo &Info);
1680 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1681 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1682 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1683                                     EvalInfo &Info);
1684 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1685 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1686 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1687                            EvalInfo &Info);
1688 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1689 
1690 /// Evaluate an integer or fixed point expression into an APResult.
1691 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1692                                         EvalInfo &Info);
1693 
1694 /// Evaluate only a fixed point expression into an APResult.
1695 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1696                                EvalInfo &Info);
1697 
1698 //===----------------------------------------------------------------------===//
1699 // Misc utilities
1700 //===----------------------------------------------------------------------===//
1701 
1702 /// A helper function to create a temporary and set an LValue.
1703 template <class KeyTy>
1704 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1705                                 LValue &LV, CallStackFrame &Frame) {
1706   LV.set({Key, Frame.Info.CurrentCall->Index,
1707           Frame.Info.CurrentCall->getTempVersion()});
1708   return Frame.createTemporary(Key, IsLifetimeExtended);
1709 }
1710 
1711 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1712 /// preserving its value (by extending by up to one bit as needed).
1713 static void negateAsSigned(APSInt &Int) {
1714   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1715     Int = Int.extend(Int.getBitWidth() + 1);
1716     Int.setIsSigned(true);
1717   }
1718   Int = -Int;
1719 }
1720 
1721 /// Produce a string describing the given constexpr call.
1722 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1723   unsigned ArgIndex = 0;
1724   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1725                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1726                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1727 
1728   if (!IsMemberCall)
1729     Out << *Frame->Callee << '(';
1730 
1731   if (Frame->This && IsMemberCall) {
1732     APValue Val;
1733     Frame->This->moveInto(Val);
1734     Val.printPretty(Out, Frame->Info.Ctx,
1735                     Frame->This->Designator.MostDerivedType);
1736     // FIXME: Add parens around Val if needed.
1737     Out << "->" << *Frame->Callee << '(';
1738     IsMemberCall = false;
1739   }
1740 
1741   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1742        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1743     if (ArgIndex > (unsigned)IsMemberCall)
1744       Out << ", ";
1745 
1746     const ParmVarDecl *Param = *I;
1747     const APValue &Arg = Frame->Arguments[ArgIndex];
1748     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1749 
1750     if (ArgIndex == 0 && IsMemberCall)
1751       Out << "->" << *Frame->Callee << '(';
1752   }
1753 
1754   Out << ')';
1755 }
1756 
1757 /// Evaluate an expression to see if it had side-effects, and discard its
1758 /// result.
1759 /// \return \c true if the caller should keep evaluating.
1760 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1761   APValue Scratch;
1762   if (!Evaluate(Scratch, Info, E))
1763     // We don't need the value, but we might have skipped a side effect here.
1764     return Info.noteSideEffect();
1765   return true;
1766 }
1767 
1768 /// Should this call expression be treated as a string literal?
1769 static bool IsStringLiteralCall(const CallExpr *E) {
1770   unsigned Builtin = E->getBuiltinCallee();
1771   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1772           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1773 }
1774 
1775 static bool IsGlobalLValue(APValue::LValueBase B) {
1776   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1777   // constant expression of pointer type that evaluates to...
1778 
1779   // ... a null pointer value, or a prvalue core constant expression of type
1780   // std::nullptr_t.
1781   if (!B) return true;
1782 
1783   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1784     // ... the address of an object with static storage duration,
1785     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1786       return VD->hasGlobalStorage();
1787     // ... the address of a function,
1788     return isa<FunctionDecl>(D);
1789   }
1790 
1791   if (B.is<TypeInfoLValue>())
1792     return true;
1793 
1794   const Expr *E = B.get<const Expr*>();
1795   switch (E->getStmtClass()) {
1796   default:
1797     return false;
1798   case Expr::CompoundLiteralExprClass: {
1799     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1800     return CLE->isFileScope() && CLE->isLValue();
1801   }
1802   case Expr::MaterializeTemporaryExprClass:
1803     // A materialized temporary might have been lifetime-extended to static
1804     // storage duration.
1805     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1806   // A string literal has static storage duration.
1807   case Expr::StringLiteralClass:
1808   case Expr::PredefinedExprClass:
1809   case Expr::ObjCStringLiteralClass:
1810   case Expr::ObjCEncodeExprClass:
1811   case Expr::CXXUuidofExprClass:
1812     return true;
1813   case Expr::ObjCBoxedExprClass:
1814     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1815   case Expr::CallExprClass:
1816     return IsStringLiteralCall(cast<CallExpr>(E));
1817   // For GCC compatibility, &&label has static storage duration.
1818   case Expr::AddrLabelExprClass:
1819     return true;
1820   // A Block literal expression may be used as the initialization value for
1821   // Block variables at global or local static scope.
1822   case Expr::BlockExprClass:
1823     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1824   case Expr::ImplicitValueInitExprClass:
1825     // FIXME:
1826     // We can never form an lvalue with an implicit value initialization as its
1827     // base through expression evaluation, so these only appear in one case: the
1828     // implicit variable declaration we invent when checking whether a constexpr
1829     // constructor can produce a constant expression. We must assume that such
1830     // an expression might be a global lvalue.
1831     return true;
1832   }
1833 }
1834 
1835 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1836   return LVal.Base.dyn_cast<const ValueDecl*>();
1837 }
1838 
1839 static bool IsLiteralLValue(const LValue &Value) {
1840   if (Value.getLValueCallIndex())
1841     return false;
1842   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1843   return E && !isa<MaterializeTemporaryExpr>(E);
1844 }
1845 
1846 static bool IsWeakLValue(const LValue &Value) {
1847   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1848   return Decl && Decl->isWeak();
1849 }
1850 
1851 static bool isZeroSized(const LValue &Value) {
1852   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1853   if (Decl && isa<VarDecl>(Decl)) {
1854     QualType Ty = Decl->getType();
1855     if (Ty->isArrayType())
1856       return Ty->isIncompleteType() ||
1857              Decl->getASTContext().getTypeSize(Ty) == 0;
1858   }
1859   return false;
1860 }
1861 
1862 static bool HasSameBase(const LValue &A, const LValue &B) {
1863   if (!A.getLValueBase())
1864     return !B.getLValueBase();
1865   if (!B.getLValueBase())
1866     return false;
1867 
1868   if (A.getLValueBase().getOpaqueValue() !=
1869       B.getLValueBase().getOpaqueValue()) {
1870     const Decl *ADecl = GetLValueBaseDecl(A);
1871     if (!ADecl)
1872       return false;
1873     const Decl *BDecl = GetLValueBaseDecl(B);
1874     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1875       return false;
1876   }
1877 
1878   return IsGlobalLValue(A.getLValueBase()) ||
1879          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1880           A.getLValueVersion() == B.getLValueVersion());
1881 }
1882 
1883 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1884   assert(Base && "no location for a null lvalue");
1885   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1886   if (VD)
1887     Info.Note(VD->getLocation(), diag::note_declared_at);
1888   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1889     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1890   // We have no information to show for a typeid(T) object.
1891 }
1892 
1893 /// Check that this reference or pointer core constant expression is a valid
1894 /// value for an address or reference constant expression. Return true if we
1895 /// can fold this expression, whether or not it's a constant expression.
1896 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1897                                           QualType Type, const LValue &LVal,
1898                                           Expr::ConstExprUsage Usage) {
1899   bool IsReferenceType = Type->isReferenceType();
1900 
1901   APValue::LValueBase Base = LVal.getLValueBase();
1902   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1903 
1904   // Check that the object is a global. Note that the fake 'this' object we
1905   // manufacture when checking potential constant expressions is conservatively
1906   // assumed to be global here.
1907   if (!IsGlobalLValue(Base)) {
1908     if (Info.getLangOpts().CPlusPlus11) {
1909       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1910       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1911         << IsReferenceType << !Designator.Entries.empty()
1912         << !!VD << VD;
1913       NoteLValueLocation(Info, Base);
1914     } else {
1915       Info.FFDiag(Loc);
1916     }
1917     // Don't allow references to temporaries to escape.
1918     return false;
1919   }
1920   assert((Info.checkingPotentialConstantExpression() ||
1921           LVal.getLValueCallIndex() == 0) &&
1922          "have call index for global lvalue");
1923 
1924   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1925     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1926       // Check if this is a thread-local variable.
1927       if (Var->getTLSKind())
1928         return false;
1929 
1930       // A dllimport variable never acts like a constant.
1931       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1932         return false;
1933     }
1934     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1935       // __declspec(dllimport) must be handled very carefully:
1936       // We must never initialize an expression with the thunk in C++.
1937       // Doing otherwise would allow the same id-expression to yield
1938       // different addresses for the same function in different translation
1939       // units.  However, this means that we must dynamically initialize the
1940       // expression with the contents of the import address table at runtime.
1941       //
1942       // The C language has no notion of ODR; furthermore, it has no notion of
1943       // dynamic initialization.  This means that we are permitted to
1944       // perform initialization with the address of the thunk.
1945       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1946           FD->hasAttr<DLLImportAttr>())
1947         return false;
1948     }
1949   }
1950 
1951   // Allow address constant expressions to be past-the-end pointers. This is
1952   // an extension: the standard requires them to point to an object.
1953   if (!IsReferenceType)
1954     return true;
1955 
1956   // A reference constant expression must refer to an object.
1957   if (!Base) {
1958     // FIXME: diagnostic
1959     Info.CCEDiag(Loc);
1960     return true;
1961   }
1962 
1963   // Does this refer one past the end of some object?
1964   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1965     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1966     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1967       << !Designator.Entries.empty() << !!VD << VD;
1968     NoteLValueLocation(Info, Base);
1969   }
1970 
1971   return true;
1972 }
1973 
1974 /// Member pointers are constant expressions unless they point to a
1975 /// non-virtual dllimport member function.
1976 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1977                                                  SourceLocation Loc,
1978                                                  QualType Type,
1979                                                  const APValue &Value,
1980                                                  Expr::ConstExprUsage Usage) {
1981   const ValueDecl *Member = Value.getMemberPointerDecl();
1982   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1983   if (!FD)
1984     return true;
1985   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1986          !FD->hasAttr<DLLImportAttr>();
1987 }
1988 
1989 /// Check that this core constant expression is of literal type, and if not,
1990 /// produce an appropriate diagnostic.
1991 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1992                              const LValue *This = nullptr) {
1993   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1994     return true;
1995 
1996   // C++1y: A constant initializer for an object o [...] may also invoke
1997   // constexpr constructors for o and its subobjects even if those objects
1998   // are of non-literal class types.
1999   //
2000   // C++11 missed this detail for aggregates, so classes like this:
2001   //   struct foo_t { union { int i; volatile int j; } u; };
2002   // are not (obviously) initializable like so:
2003   //   __attribute__((__require_constant_initialization__))
2004   //   static const foo_t x = {{0}};
2005   // because "i" is a subobject with non-literal initialization (due to the
2006   // volatile member of the union). See:
2007   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2008   // Therefore, we use the C++1y behavior.
2009   if (This && Info.EvaluatingDecl == This->getLValueBase())
2010     return true;
2011 
2012   // Prvalue constant expressions must be of literal types.
2013   if (Info.getLangOpts().CPlusPlus11)
2014     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2015       << E->getType();
2016   else
2017     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2018   return false;
2019 }
2020 
2021 /// Check that this core constant expression value is a valid value for a
2022 /// constant expression. If not, report an appropriate diagnostic. Does not
2023 /// check that the expression is of literal type.
2024 static bool
2025 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2026                         const APValue &Value,
2027                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2028   if (Value.isUninit()) {
2029     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2030       << true << Type;
2031     return false;
2032   }
2033 
2034   // We allow _Atomic(T) to be initialized from anything that T can be
2035   // initialized from.
2036   if (const AtomicType *AT = Type->getAs<AtomicType>())
2037     Type = AT->getValueType();
2038 
2039   // Core issue 1454: For a literal constant expression of array or class type,
2040   // each subobject of its value shall have been initialized by a constant
2041   // expression.
2042   if (Value.isArray()) {
2043     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2044     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2045       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
2046                                    Value.getArrayInitializedElt(I), Usage))
2047         return false;
2048     }
2049     if (!Value.hasArrayFiller())
2050       return true;
2051     return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
2052                                    Usage);
2053   }
2054   if (Value.isUnion() && Value.getUnionField()) {
2055     return CheckConstantExpression(Info, DiagLoc,
2056                                    Value.getUnionField()->getType(),
2057                                    Value.getUnionValue(), Usage);
2058   }
2059   if (Value.isStruct()) {
2060     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2061     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2062       unsigned BaseIndex = 0;
2063       for (const CXXBaseSpecifier &BS : CD->bases()) {
2064         if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2065                                      Value.getStructBase(BaseIndex), Usage))
2066           return false;
2067         ++BaseIndex;
2068       }
2069     }
2070     for (const auto *I : RD->fields()) {
2071       if (I->isUnnamedBitfield())
2072         continue;
2073 
2074       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
2075                                    Value.getStructField(I->getFieldIndex()),
2076                                    Usage))
2077         return false;
2078     }
2079   }
2080 
2081   if (Value.isLValue()) {
2082     LValue LVal;
2083     LVal.setFrom(Info.Ctx, Value);
2084     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
2085   }
2086 
2087   if (Value.isMemberPointer())
2088     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2089 
2090   // Everything else is fine.
2091   return true;
2092 }
2093 
2094 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2095   // A null base expression indicates a null pointer.  These are always
2096   // evaluatable, and they are false unless the offset is zero.
2097   if (!Value.getLValueBase()) {
2098     Result = !Value.getLValueOffset().isZero();
2099     return true;
2100   }
2101 
2102   // We have a non-null base.  These are generally known to be true, but if it's
2103   // a weak declaration it can be null at runtime.
2104   Result = true;
2105   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2106   return !Decl || !Decl->isWeak();
2107 }
2108 
2109 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2110   switch (Val.getKind()) {
2111   case APValue::Uninitialized:
2112     return false;
2113   case APValue::Int:
2114     Result = Val.getInt().getBoolValue();
2115     return true;
2116   case APValue::FixedPoint:
2117     Result = Val.getFixedPoint().getBoolValue();
2118     return true;
2119   case APValue::Float:
2120     Result = !Val.getFloat().isZero();
2121     return true;
2122   case APValue::ComplexInt:
2123     Result = Val.getComplexIntReal().getBoolValue() ||
2124              Val.getComplexIntImag().getBoolValue();
2125     return true;
2126   case APValue::ComplexFloat:
2127     Result = !Val.getComplexFloatReal().isZero() ||
2128              !Val.getComplexFloatImag().isZero();
2129     return true;
2130   case APValue::LValue:
2131     return EvalPointerValueAsBool(Val, Result);
2132   case APValue::MemberPointer:
2133     Result = Val.getMemberPointerDecl();
2134     return true;
2135   case APValue::Vector:
2136   case APValue::Array:
2137   case APValue::Struct:
2138   case APValue::Union:
2139   case APValue::AddrLabelDiff:
2140     return false;
2141   }
2142 
2143   llvm_unreachable("unknown APValue kind");
2144 }
2145 
2146 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2147                                        EvalInfo &Info) {
2148   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2149   APValue Val;
2150   if (!Evaluate(Val, Info, E))
2151     return false;
2152   return HandleConversionToBool(Val, Result);
2153 }
2154 
2155 template<typename T>
2156 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2157                            const T &SrcValue, QualType DestType) {
2158   Info.CCEDiag(E, diag::note_constexpr_overflow)
2159     << SrcValue << DestType;
2160   return Info.noteUndefinedBehavior();
2161 }
2162 
2163 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2164                                  QualType SrcType, const APFloat &Value,
2165                                  QualType DestType, APSInt &Result) {
2166   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2167   // Determine whether we are converting to unsigned or signed.
2168   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2169 
2170   Result = APSInt(DestWidth, !DestSigned);
2171   bool ignored;
2172   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2173       & APFloat::opInvalidOp)
2174     return HandleOverflow(Info, E, Value, DestType);
2175   return true;
2176 }
2177 
2178 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2179                                    QualType SrcType, QualType DestType,
2180                                    APFloat &Result) {
2181   APFloat Value = Result;
2182   bool ignored;
2183   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2184                      APFloat::rmNearestTiesToEven, &ignored)
2185       & APFloat::opOverflow)
2186     return HandleOverflow(Info, E, Value, DestType);
2187   return true;
2188 }
2189 
2190 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2191                                  QualType DestType, QualType SrcType,
2192                                  const APSInt &Value) {
2193   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2194   // Figure out if this is a truncate, extend or noop cast.
2195   // If the input is signed, do a sign extend, noop, or truncate.
2196   APSInt Result = Value.extOrTrunc(DestWidth);
2197   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2198   if (DestType->isBooleanType())
2199     Result = Value.getBoolValue();
2200   return Result;
2201 }
2202 
2203 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2204                                  QualType SrcType, const APSInt &Value,
2205                                  QualType DestType, APFloat &Result) {
2206   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2207   if (Result.convertFromAPInt(Value, Value.isSigned(),
2208                               APFloat::rmNearestTiesToEven)
2209       & APFloat::opOverflow)
2210     return HandleOverflow(Info, E, Value, DestType);
2211   return true;
2212 }
2213 
2214 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2215                                   APValue &Value, const FieldDecl *FD) {
2216   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2217 
2218   if (!Value.isInt()) {
2219     // Trying to store a pointer-cast-to-integer into a bitfield.
2220     // FIXME: In this case, we should provide the diagnostic for casting
2221     // a pointer to an integer.
2222     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2223     Info.FFDiag(E);
2224     return false;
2225   }
2226 
2227   APSInt &Int = Value.getInt();
2228   unsigned OldBitWidth = Int.getBitWidth();
2229   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2230   if (NewBitWidth < OldBitWidth)
2231     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2232   return true;
2233 }
2234 
2235 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2236                                   llvm::APInt &Res) {
2237   APValue SVal;
2238   if (!Evaluate(SVal, Info, E))
2239     return false;
2240   if (SVal.isInt()) {
2241     Res = SVal.getInt();
2242     return true;
2243   }
2244   if (SVal.isFloat()) {
2245     Res = SVal.getFloat().bitcastToAPInt();
2246     return true;
2247   }
2248   if (SVal.isVector()) {
2249     QualType VecTy = E->getType();
2250     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2251     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2252     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2253     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2254     Res = llvm::APInt::getNullValue(VecSize);
2255     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2256       APValue &Elt = SVal.getVectorElt(i);
2257       llvm::APInt EltAsInt;
2258       if (Elt.isInt()) {
2259         EltAsInt = Elt.getInt();
2260       } else if (Elt.isFloat()) {
2261         EltAsInt = Elt.getFloat().bitcastToAPInt();
2262       } else {
2263         // Don't try to handle vectors of anything other than int or float
2264         // (not sure if it's possible to hit this case).
2265         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2266         return false;
2267       }
2268       unsigned BaseEltSize = EltAsInt.getBitWidth();
2269       if (BigEndian)
2270         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2271       else
2272         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2273     }
2274     return true;
2275   }
2276   // Give up if the input isn't an int, float, or vector.  For example, we
2277   // reject "(v4i16)(intptr_t)&a".
2278   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2279   return false;
2280 }
2281 
2282 /// Perform the given integer operation, which is known to need at most BitWidth
2283 /// bits, and check for overflow in the original type (if that type was not an
2284 /// unsigned type).
2285 template<typename Operation>
2286 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2287                                  const APSInt &LHS, const APSInt &RHS,
2288                                  unsigned BitWidth, Operation Op,
2289                                  APSInt &Result) {
2290   if (LHS.isUnsigned()) {
2291     Result = Op(LHS, RHS);
2292     return true;
2293   }
2294 
2295   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2296   Result = Value.trunc(LHS.getBitWidth());
2297   if (Result.extend(BitWidth) != Value) {
2298     if (Info.checkingForOverflow())
2299       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2300                                        diag::warn_integer_constant_overflow)
2301           << Result.toString(10) << E->getType();
2302     else
2303       return HandleOverflow(Info, E, Value, E->getType());
2304   }
2305   return true;
2306 }
2307 
2308 /// Perform the given binary integer operation.
2309 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2310                               BinaryOperatorKind Opcode, APSInt RHS,
2311                               APSInt &Result) {
2312   switch (Opcode) {
2313   default:
2314     Info.FFDiag(E);
2315     return false;
2316   case BO_Mul:
2317     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2318                                 std::multiplies<APSInt>(), Result);
2319   case BO_Add:
2320     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2321                                 std::plus<APSInt>(), Result);
2322   case BO_Sub:
2323     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2324                                 std::minus<APSInt>(), Result);
2325   case BO_And: Result = LHS & RHS; return true;
2326   case BO_Xor: Result = LHS ^ RHS; return true;
2327   case BO_Or:  Result = LHS | RHS; return true;
2328   case BO_Div:
2329   case BO_Rem:
2330     if (RHS == 0) {
2331       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2332       return false;
2333     }
2334     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2335     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2336     // this operation and gives the two's complement result.
2337     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2338         LHS.isSigned() && LHS.isMinSignedValue())
2339       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2340                             E->getType());
2341     return true;
2342   case BO_Shl: {
2343     if (Info.getLangOpts().OpenCL)
2344       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2345       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2346                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2347                     RHS.isUnsigned());
2348     else if (RHS.isSigned() && RHS.isNegative()) {
2349       // During constant-folding, a negative shift is an opposite shift. Such
2350       // a shift is not a constant expression.
2351       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2352       RHS = -RHS;
2353       goto shift_right;
2354     }
2355   shift_left:
2356     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2357     // the shifted type.
2358     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2359     if (SA != RHS) {
2360       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2361         << RHS << E->getType() << LHS.getBitWidth();
2362     } else if (LHS.isSigned()) {
2363       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2364       // operand, and must not overflow the corresponding unsigned type.
2365       if (LHS.isNegative())
2366         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2367       else if (LHS.countLeadingZeros() < SA)
2368         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2369     }
2370     Result = LHS << SA;
2371     return true;
2372   }
2373   case BO_Shr: {
2374     if (Info.getLangOpts().OpenCL)
2375       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2376       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2377                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2378                     RHS.isUnsigned());
2379     else if (RHS.isSigned() && RHS.isNegative()) {
2380       // During constant-folding, a negative shift is an opposite shift. Such a
2381       // shift is not a constant expression.
2382       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2383       RHS = -RHS;
2384       goto shift_left;
2385     }
2386   shift_right:
2387     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2388     // shifted type.
2389     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2390     if (SA != RHS)
2391       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2392         << RHS << E->getType() << LHS.getBitWidth();
2393     Result = LHS >> SA;
2394     return true;
2395   }
2396 
2397   case BO_LT: Result = LHS < RHS; return true;
2398   case BO_GT: Result = LHS > RHS; return true;
2399   case BO_LE: Result = LHS <= RHS; return true;
2400   case BO_GE: Result = LHS >= RHS; return true;
2401   case BO_EQ: Result = LHS == RHS; return true;
2402   case BO_NE: Result = LHS != RHS; return true;
2403   case BO_Cmp:
2404     llvm_unreachable("BO_Cmp should be handled elsewhere");
2405   }
2406 }
2407 
2408 /// Perform the given binary floating-point operation, in-place, on LHS.
2409 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2410                                   APFloat &LHS, BinaryOperatorKind Opcode,
2411                                   const APFloat &RHS) {
2412   switch (Opcode) {
2413   default:
2414     Info.FFDiag(E);
2415     return false;
2416   case BO_Mul:
2417     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2418     break;
2419   case BO_Add:
2420     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2421     break;
2422   case BO_Sub:
2423     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2424     break;
2425   case BO_Div:
2426     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2427     break;
2428   }
2429 
2430   if (LHS.isInfinity() || LHS.isNaN()) {
2431     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2432     return Info.noteUndefinedBehavior();
2433   }
2434   return true;
2435 }
2436 
2437 /// Cast an lvalue referring to a base subobject to a derived class, by
2438 /// truncating the lvalue's path to the given length.
2439 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2440                                const RecordDecl *TruncatedType,
2441                                unsigned TruncatedElements) {
2442   SubobjectDesignator &D = Result.Designator;
2443 
2444   // Check we actually point to a derived class object.
2445   if (TruncatedElements == D.Entries.size())
2446     return true;
2447   assert(TruncatedElements >= D.MostDerivedPathLength &&
2448          "not casting to a derived class");
2449   if (!Result.checkSubobject(Info, E, CSK_Derived))
2450     return false;
2451 
2452   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2453   const RecordDecl *RD = TruncatedType;
2454   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2455     if (RD->isInvalidDecl()) return false;
2456     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2457     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2458     if (isVirtualBaseClass(D.Entries[I]))
2459       Result.Offset -= Layout.getVBaseClassOffset(Base);
2460     else
2461       Result.Offset -= Layout.getBaseClassOffset(Base);
2462     RD = Base;
2463   }
2464   D.Entries.resize(TruncatedElements);
2465   return true;
2466 }
2467 
2468 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2469                                    const CXXRecordDecl *Derived,
2470                                    const CXXRecordDecl *Base,
2471                                    const ASTRecordLayout *RL = nullptr) {
2472   if (!RL) {
2473     if (Derived->isInvalidDecl()) return false;
2474     RL = &Info.Ctx.getASTRecordLayout(Derived);
2475   }
2476 
2477   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2478   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2479   return true;
2480 }
2481 
2482 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2483                              const CXXRecordDecl *DerivedDecl,
2484                              const CXXBaseSpecifier *Base) {
2485   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2486 
2487   if (!Base->isVirtual())
2488     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2489 
2490   SubobjectDesignator &D = Obj.Designator;
2491   if (D.Invalid)
2492     return false;
2493 
2494   // Extract most-derived object and corresponding type.
2495   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2496   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2497     return false;
2498 
2499   // Find the virtual base class.
2500   if (DerivedDecl->isInvalidDecl()) return false;
2501   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2502   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2503   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2504   return true;
2505 }
2506 
2507 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2508                                  QualType Type, LValue &Result) {
2509   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2510                                      PathE = E->path_end();
2511        PathI != PathE; ++PathI) {
2512     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2513                           *PathI))
2514       return false;
2515     Type = (*PathI)->getType();
2516   }
2517   return true;
2518 }
2519 
2520 /// Cast an lvalue referring to a derived class to a known base subobject.
2521 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2522                             const CXXRecordDecl *DerivedRD,
2523                             const CXXRecordDecl *BaseRD) {
2524   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2525                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2526   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2527     llvm_unreachable("Class must be derived from the passed in base class!");
2528 
2529   for (CXXBasePathElement &Elem : Paths.front())
2530     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2531       return false;
2532   return true;
2533 }
2534 
2535 /// Update LVal to refer to the given field, which must be a member of the type
2536 /// currently described by LVal.
2537 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2538                                const FieldDecl *FD,
2539                                const ASTRecordLayout *RL = nullptr) {
2540   if (!RL) {
2541     if (FD->getParent()->isInvalidDecl()) return false;
2542     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2543   }
2544 
2545   unsigned I = FD->getFieldIndex();
2546   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2547   LVal.addDecl(Info, E, FD);
2548   return true;
2549 }
2550 
2551 /// Update LVal to refer to the given indirect field.
2552 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2553                                        LValue &LVal,
2554                                        const IndirectFieldDecl *IFD) {
2555   for (const auto *C : IFD->chain())
2556     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2557       return false;
2558   return true;
2559 }
2560 
2561 /// Get the size of the given type in char units.
2562 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2563                          QualType Type, CharUnits &Size) {
2564   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2565   // extension.
2566   if (Type->isVoidType() || Type->isFunctionType()) {
2567     Size = CharUnits::One();
2568     return true;
2569   }
2570 
2571   if (Type->isDependentType()) {
2572     Info.FFDiag(Loc);
2573     return false;
2574   }
2575 
2576   if (!Type->isConstantSizeType()) {
2577     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2578     // FIXME: Better diagnostic.
2579     Info.FFDiag(Loc);
2580     return false;
2581   }
2582 
2583   Size = Info.Ctx.getTypeSizeInChars(Type);
2584   return true;
2585 }
2586 
2587 /// Update a pointer value to model pointer arithmetic.
2588 /// \param Info - Information about the ongoing evaluation.
2589 /// \param E - The expression being evaluated, for diagnostic purposes.
2590 /// \param LVal - The pointer value to be updated.
2591 /// \param EltTy - The pointee type represented by LVal.
2592 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2593 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2594                                         LValue &LVal, QualType EltTy,
2595                                         APSInt Adjustment) {
2596   CharUnits SizeOfPointee;
2597   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2598     return false;
2599 
2600   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2601   return true;
2602 }
2603 
2604 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2605                                         LValue &LVal, QualType EltTy,
2606                                         int64_t Adjustment) {
2607   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2608                                      APSInt::get(Adjustment));
2609 }
2610 
2611 /// Update an lvalue to refer to a component of a complex number.
2612 /// \param Info - Information about the ongoing evaluation.
2613 /// \param LVal - The lvalue to be updated.
2614 /// \param EltTy - The complex number's component type.
2615 /// \param Imag - False for the real component, true for the imaginary.
2616 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2617                                        LValue &LVal, QualType EltTy,
2618                                        bool Imag) {
2619   if (Imag) {
2620     CharUnits SizeOfComponent;
2621     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2622       return false;
2623     LVal.Offset += SizeOfComponent;
2624   }
2625   LVal.addComplex(Info, E, EltTy, Imag);
2626   return true;
2627 }
2628 
2629 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2630                                            QualType Type, const LValue &LVal,
2631                                            APValue &RVal);
2632 
2633 /// Try to evaluate the initializer for a variable declaration.
2634 ///
2635 /// \param Info   Information about the ongoing evaluation.
2636 /// \param E      An expression to be used when printing diagnostics.
2637 /// \param VD     The variable whose initializer should be obtained.
2638 /// \param Frame  The frame in which the variable was created. Must be null
2639 ///               if this variable is not local to the evaluation.
2640 /// \param Result Filled in with a pointer to the value of the variable.
2641 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2642                                 const VarDecl *VD, CallStackFrame *Frame,
2643                                 APValue *&Result, const LValue *LVal) {
2644 
2645   // If this is a parameter to an active constexpr function call, perform
2646   // argument substitution.
2647   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2648     // Assume arguments of a potential constant expression are unknown
2649     // constant expressions.
2650     if (Info.checkingPotentialConstantExpression())
2651       return false;
2652     if (!Frame || !Frame->Arguments) {
2653       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2654       return false;
2655     }
2656     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2657     return true;
2658   }
2659 
2660   // If this is a local variable, dig out its value.
2661   if (Frame) {
2662     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2663                   : Frame->getCurrentTemporary(VD);
2664     if (!Result) {
2665       // Assume variables referenced within a lambda's call operator that were
2666       // not declared within the call operator are captures and during checking
2667       // of a potential constant expression, assume they are unknown constant
2668       // expressions.
2669       assert(isLambdaCallOperator(Frame->Callee) &&
2670              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2671              "missing value for local variable");
2672       if (Info.checkingPotentialConstantExpression())
2673         return false;
2674       // FIXME: implement capture evaluation during constant expr evaluation.
2675       Info.FFDiag(E->getBeginLoc(),
2676                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2677           << "captures not currently allowed";
2678       return false;
2679     }
2680     return true;
2681   }
2682 
2683   // Dig out the initializer, and use the declaration which it's attached to.
2684   const Expr *Init = VD->getAnyInitializer(VD);
2685   if (!Init || Init->isValueDependent()) {
2686     // If we're checking a potential constant expression, the variable could be
2687     // initialized later.
2688     if (!Info.checkingPotentialConstantExpression())
2689       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2690     return false;
2691   }
2692 
2693   // If we're currently evaluating the initializer of this declaration, use that
2694   // in-flight value.
2695   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2696     Result = Info.EvaluatingDeclValue;
2697     return true;
2698   }
2699 
2700   // Never evaluate the initializer of a weak variable. We can't be sure that
2701   // this is the definition which will be used.
2702   if (VD->isWeak()) {
2703     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2704     return false;
2705   }
2706 
2707   // Check that we can fold the initializer. In C++, we will have already done
2708   // this in the cases where it matters for conformance.
2709   SmallVector<PartialDiagnosticAt, 8> Notes;
2710   if (!VD->evaluateValue(Notes)) {
2711     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2712               Notes.size() + 1) << VD;
2713     Info.Note(VD->getLocation(), diag::note_declared_at);
2714     Info.addNotes(Notes);
2715     return false;
2716   } else if (!VD->checkInitIsICE()) {
2717     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2718                  Notes.size() + 1) << VD;
2719     Info.Note(VD->getLocation(), diag::note_declared_at);
2720     Info.addNotes(Notes);
2721   }
2722 
2723   Result = VD->getEvaluatedValue();
2724   return true;
2725 }
2726 
2727 static bool IsConstNonVolatile(QualType T) {
2728   Qualifiers Quals = T.getQualifiers();
2729   return Quals.hasConst() && !Quals.hasVolatile();
2730 }
2731 
2732 /// Get the base index of the given base class within an APValue representing
2733 /// the given derived class.
2734 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2735                              const CXXRecordDecl *Base) {
2736   Base = Base->getCanonicalDecl();
2737   unsigned Index = 0;
2738   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2739          E = Derived->bases_end(); I != E; ++I, ++Index) {
2740     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2741       return Index;
2742   }
2743 
2744   llvm_unreachable("base class missing from derived class's bases list");
2745 }
2746 
2747 /// Extract the value of a character from a string literal.
2748 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2749                                             uint64_t Index) {
2750   assert(!isa<SourceLocExpr>(Lit) &&
2751          "SourceLocExpr should have already been converted to a StringLiteral");
2752 
2753   // FIXME: Support MakeStringConstant
2754   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2755     std::string Str;
2756     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2757     assert(Index <= Str.size() && "Index too large");
2758     return APSInt::getUnsigned(Str.c_str()[Index]);
2759   }
2760 
2761   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2762     Lit = PE->getFunctionName();
2763   const StringLiteral *S = cast<StringLiteral>(Lit);
2764   const ConstantArrayType *CAT =
2765       Info.Ctx.getAsConstantArrayType(S->getType());
2766   assert(CAT && "string literal isn't an array");
2767   QualType CharType = CAT->getElementType();
2768   assert(CharType->isIntegerType() && "unexpected character type");
2769 
2770   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2771                CharType->isUnsignedIntegerType());
2772   if (Index < S->getLength())
2773     Value = S->getCodeUnit(Index);
2774   return Value;
2775 }
2776 
2777 // Expand a string literal into an array of characters.
2778 //
2779 // FIXME: This is inefficient; we should probably introduce something similar
2780 // to the LLVM ConstantDataArray to make this cheaper.
2781 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2782                                 APValue &Result) {
2783   const ConstantArrayType *CAT =
2784       Info.Ctx.getAsConstantArrayType(S->getType());
2785   assert(CAT && "string literal isn't an array");
2786   QualType CharType = CAT->getElementType();
2787   assert(CharType->isIntegerType() && "unexpected character type");
2788 
2789   unsigned Elts = CAT->getSize().getZExtValue();
2790   Result = APValue(APValue::UninitArray(),
2791                    std::min(S->getLength(), Elts), Elts);
2792   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2793                CharType->isUnsignedIntegerType());
2794   if (Result.hasArrayFiller())
2795     Result.getArrayFiller() = APValue(Value);
2796   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2797     Value = S->getCodeUnit(I);
2798     Result.getArrayInitializedElt(I) = APValue(Value);
2799   }
2800 }
2801 
2802 // Expand an array so that it has more than Index filled elements.
2803 static void expandArray(APValue &Array, unsigned Index) {
2804   unsigned Size = Array.getArraySize();
2805   assert(Index < Size);
2806 
2807   // Always at least double the number of elements for which we store a value.
2808   unsigned OldElts = Array.getArrayInitializedElts();
2809   unsigned NewElts = std::max(Index+1, OldElts * 2);
2810   NewElts = std::min(Size, std::max(NewElts, 8u));
2811 
2812   // Copy the data across.
2813   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2814   for (unsigned I = 0; I != OldElts; ++I)
2815     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2816   for (unsigned I = OldElts; I != NewElts; ++I)
2817     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2818   if (NewValue.hasArrayFiller())
2819     NewValue.getArrayFiller() = Array.getArrayFiller();
2820   Array.swap(NewValue);
2821 }
2822 
2823 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2824 /// conversion. If it's of class type, we may assume that the copy operation
2825 /// is trivial. Note that this is never true for a union type with fields
2826 /// (because the copy always "reads" the active member) and always true for
2827 /// a non-class type.
2828 static bool isReadByLvalueToRvalueConversion(QualType T) {
2829   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2830   if (!RD || (RD->isUnion() && !RD->field_empty()))
2831     return true;
2832   if (RD->isEmpty())
2833     return false;
2834 
2835   for (auto *Field : RD->fields())
2836     if (isReadByLvalueToRvalueConversion(Field->getType()))
2837       return true;
2838 
2839   for (auto &BaseSpec : RD->bases())
2840     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2841       return true;
2842 
2843   return false;
2844 }
2845 
2846 /// Diagnose an attempt to read from any unreadable field within the specified
2847 /// type, which might be a class type.
2848 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2849                                      QualType T) {
2850   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2851   if (!RD)
2852     return false;
2853 
2854   if (!RD->hasMutableFields())
2855     return false;
2856 
2857   for (auto *Field : RD->fields()) {
2858     // If we're actually going to read this field in some way, then it can't
2859     // be mutable. If we're in a union, then assigning to a mutable field
2860     // (even an empty one) can change the active member, so that's not OK.
2861     // FIXME: Add core issue number for the union case.
2862     if (Field->isMutable() &&
2863         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2864       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2865       Info.Note(Field->getLocation(), diag::note_declared_at);
2866       return true;
2867     }
2868 
2869     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2870       return true;
2871   }
2872 
2873   for (auto &BaseSpec : RD->bases())
2874     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2875       return true;
2876 
2877   // All mutable fields were empty, and thus not actually read.
2878   return false;
2879 }
2880 
2881 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2882                                         APValue::LValueBase Base) {
2883   // A temporary we created.
2884   if (Base.getCallIndex())
2885     return true;
2886 
2887   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2888   if (!Evaluating)
2889     return false;
2890 
2891   // The variable whose initializer we're evaluating.
2892   if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2893     if (declaresSameEntity(Evaluating, BaseD))
2894       return true;
2895 
2896   // A temporary lifetime-extended by the variable whose initializer we're
2897   // evaluating.
2898   if (auto *BaseE = Base.dyn_cast<const Expr *>())
2899     if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2900       if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2901         return true;
2902 
2903   return false;
2904 }
2905 
2906 namespace {
2907 /// A handle to a complete object (an object that is not a subobject of
2908 /// another object).
2909 struct CompleteObject {
2910   /// The identity of the object.
2911   APValue::LValueBase Base;
2912   /// The value of the complete object.
2913   APValue *Value;
2914   /// The type of the complete object.
2915   QualType Type;
2916 
2917   CompleteObject() : Value(nullptr) {}
2918   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2919       : Base(Base), Value(Value), Type(Type) {}
2920 
2921   bool mayReadMutableMembers(EvalInfo &Info) const {
2922     // In C++14 onwards, it is permitted to read a mutable member whose
2923     // lifetime began within the evaluation.
2924     // FIXME: Should we also allow this in C++11?
2925     if (!Info.getLangOpts().CPlusPlus14)
2926       return false;
2927     return lifetimeStartedInEvaluation(Info, Base);
2928   }
2929 
2930   explicit operator bool() const { return !Type.isNull(); }
2931 };
2932 } // end anonymous namespace
2933 
2934 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2935                                  bool IsMutable = false) {
2936   // C++ [basic.type.qualifier]p1:
2937   // - A const object is an object of type const T or a non-mutable subobject
2938   //   of a const object.
2939   if (ObjType.isConstQualified() && !IsMutable)
2940     SubobjType.addConst();
2941   // - A volatile object is an object of type const T or a subobject of a
2942   //   volatile object.
2943   if (ObjType.isVolatileQualified())
2944     SubobjType.addVolatile();
2945   return SubobjType;
2946 }
2947 
2948 /// Find the designated sub-object of an rvalue.
2949 template<typename SubobjectHandler>
2950 typename SubobjectHandler::result_type
2951 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2952               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2953   if (Sub.Invalid)
2954     // A diagnostic will have already been produced.
2955     return handler.failed();
2956   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2957     if (Info.getLangOpts().CPlusPlus11)
2958       Info.FFDiag(E, Sub.isOnePastTheEnd()
2959                          ? diag::note_constexpr_access_past_end
2960                          : diag::note_constexpr_access_unsized_array)
2961           << handler.AccessKind;
2962     else
2963       Info.FFDiag(E);
2964     return handler.failed();
2965   }
2966 
2967   APValue *O = Obj.Value;
2968   QualType ObjType = Obj.Type;
2969   const FieldDecl *LastField = nullptr;
2970   const FieldDecl *VolatileField = nullptr;
2971 
2972   // Walk the designator's path to find the subobject.
2973   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2974     if (O->isUninit()) {
2975       if (!Info.checkingPotentialConstantExpression())
2976         Info.FFDiag(E, diag::note_constexpr_access_uninit)
2977             << handler.AccessKind;
2978       return handler.failed();
2979     }
2980 
2981     // C++ [class.ctor]p5:
2982     //    const and volatile semantics are not applied on an object under
2983     //    construction.
2984     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
2985         ObjType->isRecordType() &&
2986         Info.isEvaluatingConstructor(
2987             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
2988                                          Sub.Entries.begin() + I)) !=
2989                           ConstructionPhase::None) {
2990       ObjType = Info.Ctx.getCanonicalType(ObjType);
2991       ObjType.removeLocalConst();
2992       ObjType.removeLocalVolatile();
2993     }
2994 
2995     // If this is our last pass, check that the final object type is OK.
2996     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
2997       // Accesses to volatile objects are prohibited.
2998       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
2999         if (Info.getLangOpts().CPlusPlus) {
3000           int DiagKind;
3001           SourceLocation Loc;
3002           const NamedDecl *Decl = nullptr;
3003           if (VolatileField) {
3004             DiagKind = 2;
3005             Loc = VolatileField->getLocation();
3006             Decl = VolatileField;
3007           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3008             DiagKind = 1;
3009             Loc = VD->getLocation();
3010             Decl = VD;
3011           } else {
3012             DiagKind = 0;
3013             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3014               Loc = E->getExprLoc();
3015           }
3016           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3017               << handler.AccessKind << DiagKind << Decl;
3018           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3019         } else {
3020           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3021         }
3022         return handler.failed();
3023       }
3024 
3025       // If we are reading an object of class type, there may still be more
3026       // things we need to check: if there are any mutable subobjects, we
3027       // cannot perform this read. (This only happens when performing a trivial
3028       // copy or assignment.)
3029       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
3030           !Obj.mayReadMutableMembers(Info) &&
3031           diagnoseUnreadableFields(Info, E, ObjType))
3032         return handler.failed();
3033     }
3034 
3035     if (I == N) {
3036       if (!handler.found(*O, ObjType))
3037         return false;
3038 
3039       // If we modified a bit-field, truncate it to the right width.
3040       if (isModification(handler.AccessKind) &&
3041           LastField && LastField->isBitField() &&
3042           !truncateBitfieldValue(Info, E, *O, LastField))
3043         return false;
3044 
3045       return true;
3046     }
3047 
3048     LastField = nullptr;
3049     if (ObjType->isArrayType()) {
3050       // Next subobject is an array element.
3051       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3052       assert(CAT && "vla in literal type?");
3053       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3054       if (CAT->getSize().ule(Index)) {
3055         // Note, it should not be possible to form a pointer with a valid
3056         // designator which points more than one past the end of the array.
3057         if (Info.getLangOpts().CPlusPlus11)
3058           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3059             << handler.AccessKind;
3060         else
3061           Info.FFDiag(E);
3062         return handler.failed();
3063       }
3064 
3065       ObjType = CAT->getElementType();
3066 
3067       if (O->getArrayInitializedElts() > Index)
3068         O = &O->getArrayInitializedElt(Index);
3069       else if (handler.AccessKind != AK_Read) {
3070         expandArray(*O, Index);
3071         O = &O->getArrayInitializedElt(Index);
3072       } else
3073         O = &O->getArrayFiller();
3074     } else if (ObjType->isAnyComplexType()) {
3075       // Next subobject is a complex number.
3076       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3077       if (Index > 1) {
3078         if (Info.getLangOpts().CPlusPlus11)
3079           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3080             << handler.AccessKind;
3081         else
3082           Info.FFDiag(E);
3083         return handler.failed();
3084       }
3085 
3086       ObjType = getSubobjectType(
3087           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3088 
3089       assert(I == N - 1 && "extracting subobject of scalar?");
3090       if (O->isComplexInt()) {
3091         return handler.found(Index ? O->getComplexIntImag()
3092                                    : O->getComplexIntReal(), ObjType);
3093       } else {
3094         assert(O->isComplexFloat());
3095         return handler.found(Index ? O->getComplexFloatImag()
3096                                    : O->getComplexFloatReal(), ObjType);
3097       }
3098     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3099       if (Field->isMutable() && handler.AccessKind == AK_Read &&
3100           !Obj.mayReadMutableMembers(Info)) {
3101         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
3102           << Field;
3103         Info.Note(Field->getLocation(), diag::note_declared_at);
3104         return handler.failed();
3105       }
3106 
3107       // Next subobject is a class, struct or union field.
3108       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3109       if (RD->isUnion()) {
3110         const FieldDecl *UnionField = O->getUnionField();
3111         if (!UnionField ||
3112             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3113           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3114             << handler.AccessKind << Field << !UnionField << UnionField;
3115           return handler.failed();
3116         }
3117         O = &O->getUnionValue();
3118       } else
3119         O = &O->getStructField(Field->getFieldIndex());
3120 
3121       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3122       LastField = Field;
3123       if (Field->getType().isVolatileQualified())
3124         VolatileField = Field;
3125     } else {
3126       // Next subobject is a base class.
3127       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3128       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3129       O = &O->getStructBase(getBaseIndex(Derived, Base));
3130 
3131       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3132     }
3133   }
3134 }
3135 
3136 namespace {
3137 struct ExtractSubobjectHandler {
3138   EvalInfo &Info;
3139   APValue &Result;
3140 
3141   static const AccessKinds AccessKind = AK_Read;
3142 
3143   typedef bool result_type;
3144   bool failed() { return false; }
3145   bool found(APValue &Subobj, QualType SubobjType) {
3146     Result = Subobj;
3147     return true;
3148   }
3149   bool found(APSInt &Value, QualType SubobjType) {
3150     Result = APValue(Value);
3151     return true;
3152   }
3153   bool found(APFloat &Value, QualType SubobjType) {
3154     Result = APValue(Value);
3155     return true;
3156   }
3157 };
3158 } // end anonymous namespace
3159 
3160 const AccessKinds ExtractSubobjectHandler::AccessKind;
3161 
3162 /// Extract the designated sub-object of an rvalue.
3163 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3164                              const CompleteObject &Obj,
3165                              const SubobjectDesignator &Sub,
3166                              APValue &Result) {
3167   ExtractSubobjectHandler Handler = { Info, Result };
3168   return findSubobject(Info, E, Obj, Sub, Handler);
3169 }
3170 
3171 namespace {
3172 struct ModifySubobjectHandler {
3173   EvalInfo &Info;
3174   APValue &NewVal;
3175   const Expr *E;
3176 
3177   typedef bool result_type;
3178   static const AccessKinds AccessKind = AK_Assign;
3179 
3180   bool checkConst(QualType QT) {
3181     // Assigning to a const object has undefined behavior.
3182     if (QT.isConstQualified()) {
3183       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3184       return false;
3185     }
3186     return true;
3187   }
3188 
3189   bool failed() { return false; }
3190   bool found(APValue &Subobj, QualType SubobjType) {
3191     if (!checkConst(SubobjType))
3192       return false;
3193     // We've been given ownership of NewVal, so just swap it in.
3194     Subobj.swap(NewVal);
3195     return true;
3196   }
3197   bool found(APSInt &Value, QualType SubobjType) {
3198     if (!checkConst(SubobjType))
3199       return false;
3200     if (!NewVal.isInt()) {
3201       // Maybe trying to write a cast pointer value into a complex?
3202       Info.FFDiag(E);
3203       return false;
3204     }
3205     Value = NewVal.getInt();
3206     return true;
3207   }
3208   bool found(APFloat &Value, QualType SubobjType) {
3209     if (!checkConst(SubobjType))
3210       return false;
3211     Value = NewVal.getFloat();
3212     return true;
3213   }
3214 };
3215 } // end anonymous namespace
3216 
3217 const AccessKinds ModifySubobjectHandler::AccessKind;
3218 
3219 /// Update the designated sub-object of an rvalue to the given value.
3220 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3221                             const CompleteObject &Obj,
3222                             const SubobjectDesignator &Sub,
3223                             APValue &NewVal) {
3224   ModifySubobjectHandler Handler = { Info, NewVal, E };
3225   return findSubobject(Info, E, Obj, Sub, Handler);
3226 }
3227 
3228 /// Find the position where two subobject designators diverge, or equivalently
3229 /// the length of the common initial subsequence.
3230 static unsigned FindDesignatorMismatch(QualType ObjType,
3231                                        const SubobjectDesignator &A,
3232                                        const SubobjectDesignator &B,
3233                                        bool &WasArrayIndex) {
3234   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3235   for (/**/; I != N; ++I) {
3236     if (!ObjType.isNull() &&
3237         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3238       // Next subobject is an array element.
3239       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3240         WasArrayIndex = true;
3241         return I;
3242       }
3243       if (ObjType->isAnyComplexType())
3244         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3245       else
3246         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3247     } else {
3248       if (A.Entries[I].getAsBaseOrMember() !=
3249           B.Entries[I].getAsBaseOrMember()) {
3250         WasArrayIndex = false;
3251         return I;
3252       }
3253       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3254         // Next subobject is a field.
3255         ObjType = FD->getType();
3256       else
3257         // Next subobject is a base class.
3258         ObjType = QualType();
3259     }
3260   }
3261   WasArrayIndex = false;
3262   return I;
3263 }
3264 
3265 /// Determine whether the given subobject designators refer to elements of the
3266 /// same array object.
3267 static bool AreElementsOfSameArray(QualType ObjType,
3268                                    const SubobjectDesignator &A,
3269                                    const SubobjectDesignator &B) {
3270   if (A.Entries.size() != B.Entries.size())
3271     return false;
3272 
3273   bool IsArray = A.MostDerivedIsArrayElement;
3274   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3275     // A is a subobject of the array element.
3276     return false;
3277 
3278   // If A (and B) designates an array element, the last entry will be the array
3279   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3280   // of length 1' case, and the entire path must match.
3281   bool WasArrayIndex;
3282   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3283   return CommonLength >= A.Entries.size() - IsArray;
3284 }
3285 
3286 /// Find the complete object to which an LValue refers.
3287 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3288                                          AccessKinds AK, const LValue &LVal,
3289                                          QualType LValType) {
3290   if (LVal.InvalidBase) {
3291     Info.FFDiag(E);
3292     return CompleteObject();
3293   }
3294 
3295   if (!LVal.Base) {
3296     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3297     return CompleteObject();
3298   }
3299 
3300   CallStackFrame *Frame = nullptr;
3301   unsigned Depth = 0;
3302   if (LVal.getLValueCallIndex()) {
3303     std::tie(Frame, Depth) =
3304         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3305     if (!Frame) {
3306       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3307         << AK << LVal.Base.is<const ValueDecl*>();
3308       NoteLValueLocation(Info, LVal.Base);
3309       return CompleteObject();
3310     }
3311   }
3312 
3313   bool IsAccess = isFormalAccess(AK);
3314 
3315   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3316   // is not a constant expression (even if the object is non-volatile). We also
3317   // apply this rule to C++98, in order to conform to the expected 'volatile'
3318   // semantics.
3319   if (IsAccess && LValType.isVolatileQualified()) {
3320     if (Info.getLangOpts().CPlusPlus)
3321       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3322         << AK << LValType;
3323     else
3324       Info.FFDiag(E);
3325     return CompleteObject();
3326   }
3327 
3328   // Compute value storage location and type of base object.
3329   APValue *BaseVal = nullptr;
3330   QualType BaseType = getType(LVal.Base);
3331 
3332   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3333     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3334     // In C++11, constexpr, non-volatile variables initialized with constant
3335     // expressions are constant expressions too. Inside constexpr functions,
3336     // parameters are constant expressions even if they're non-const.
3337     // In C++1y, objects local to a constant expression (those with a Frame) are
3338     // both readable and writable inside constant expressions.
3339     // In C, such things can also be folded, although they are not ICEs.
3340     const VarDecl *VD = dyn_cast<VarDecl>(D);
3341     if (VD) {
3342       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3343         VD = VDef;
3344     }
3345     if (!VD || VD->isInvalidDecl()) {
3346       Info.FFDiag(E);
3347       return CompleteObject();
3348     }
3349 
3350     // Unless we're looking at a local variable or argument in a constexpr call,
3351     // the variable we're reading must be const.
3352     if (!Frame) {
3353       if (Info.getLangOpts().CPlusPlus14 &&
3354           declaresSameEntity(
3355               VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
3356         // OK, we can read and modify an object if we're in the process of
3357         // evaluating its initializer, because its lifetime began in this
3358         // evaluation.
3359       } else if (isModification(AK)) {
3360         // All the remaining cases do not permit modification of the object.
3361         Info.FFDiag(E, diag::note_constexpr_modify_global);
3362         return CompleteObject();
3363       } else if (VD->isConstexpr()) {
3364         // OK, we can read this variable.
3365       } else if (BaseType->isIntegralOrEnumerationType()) {
3366         // In OpenCL if a variable is in constant address space it is a const
3367         // value.
3368         if (!(BaseType.isConstQualified() ||
3369               (Info.getLangOpts().OpenCL &&
3370                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3371           if (!IsAccess)
3372             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3373           if (Info.getLangOpts().CPlusPlus) {
3374             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3375             Info.Note(VD->getLocation(), diag::note_declared_at);
3376           } else {
3377             Info.FFDiag(E);
3378           }
3379           return CompleteObject();
3380         }
3381       } else if (!IsAccess) {
3382         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3383       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3384         // We support folding of const floating-point types, in order to make
3385         // static const data members of such types (supported as an extension)
3386         // more useful.
3387         if (Info.getLangOpts().CPlusPlus11) {
3388           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3389           Info.Note(VD->getLocation(), diag::note_declared_at);
3390         } else {
3391           Info.CCEDiag(E);
3392         }
3393       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3394         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3395         // Keep evaluating to see what we can do.
3396       } else {
3397         // FIXME: Allow folding of values of any literal type in all languages.
3398         if (Info.checkingPotentialConstantExpression() &&
3399             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3400           // The definition of this variable could be constexpr. We can't
3401           // access it right now, but may be able to in future.
3402         } else if (Info.getLangOpts().CPlusPlus11) {
3403           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3404           Info.Note(VD->getLocation(), diag::note_declared_at);
3405         } else {
3406           Info.FFDiag(E);
3407         }
3408         return CompleteObject();
3409       }
3410     }
3411 
3412     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3413       return CompleteObject();
3414   } else {
3415     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3416 
3417     if (!Frame) {
3418       if (const MaterializeTemporaryExpr *MTE =
3419               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3420         assert(MTE->getStorageDuration() == SD_Static &&
3421                "should have a frame for a non-global materialized temporary");
3422 
3423         // Per C++1y [expr.const]p2:
3424         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3425         //   - a [...] glvalue of integral or enumeration type that refers to
3426         //     a non-volatile const object [...]
3427         //   [...]
3428         //   - a [...] glvalue of literal type that refers to a non-volatile
3429         //     object whose lifetime began within the evaluation of e.
3430         //
3431         // C++11 misses the 'began within the evaluation of e' check and
3432         // instead allows all temporaries, including things like:
3433         //   int &&r = 1;
3434         //   int x = ++r;
3435         //   constexpr int k = r;
3436         // Therefore we use the C++14 rules in C++11 too.
3437         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3438         const ValueDecl *ED = MTE->getExtendingDecl();
3439         if (!(BaseType.isConstQualified() &&
3440               BaseType->isIntegralOrEnumerationType()) &&
3441             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3442           if (!IsAccess)
3443             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3444           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3445           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3446           return CompleteObject();
3447         }
3448 
3449         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3450         assert(BaseVal && "got reference to unevaluated temporary");
3451       } else {
3452         if (!IsAccess)
3453           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3454         APValue Val;
3455         LVal.moveInto(Val);
3456         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3457             << AK
3458             << Val.getAsString(Info.Ctx,
3459                                Info.Ctx.getLValueReferenceType(LValType));
3460         NoteLValueLocation(Info, LVal.Base);
3461         return CompleteObject();
3462       }
3463     } else {
3464       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3465       assert(BaseVal && "missing value for temporary");
3466     }
3467   }
3468 
3469   // In C++14, we can't safely access any mutable state when we might be
3470   // evaluating after an unmodeled side effect.
3471   //
3472   // FIXME: Not all local state is mutable. Allow local constant subobjects
3473   // to be read here (but take care with 'mutable' fields).
3474   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3475        Info.EvalStatus.HasSideEffects) ||
3476       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3477     return CompleteObject();
3478 
3479   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3480 }
3481 
3482 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3483 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3484 /// glvalue referred to by an entity of reference type.
3485 ///
3486 /// \param Info - Information about the ongoing evaluation.
3487 /// \param Conv - The expression for which we are performing the conversion.
3488 ///               Used for diagnostics.
3489 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3490 ///               case of a non-class type).
3491 /// \param LVal - The glvalue on which we are attempting to perform this action.
3492 /// \param RVal - The produced value will be placed here.
3493 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3494                                            QualType Type,
3495                                            const LValue &LVal, APValue &RVal) {
3496   if (LVal.Designator.Invalid)
3497     return false;
3498 
3499   // Check for special cases where there is no existing APValue to look at.
3500   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3501 
3502   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3503     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3504       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3505       // initializer until now for such expressions. Such an expression can't be
3506       // an ICE in C, so this only matters for fold.
3507       if (Type.isVolatileQualified()) {
3508         Info.FFDiag(Conv);
3509         return false;
3510       }
3511       APValue Lit;
3512       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3513         return false;
3514       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3515       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3516     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3517       // Special-case character extraction so we don't have to construct an
3518       // APValue for the whole string.
3519       assert(LVal.Designator.Entries.size() <= 1 &&
3520              "Can only read characters from string literals");
3521       if (LVal.Designator.Entries.empty()) {
3522         // Fail for now for LValue to RValue conversion of an array.
3523         // (This shouldn't show up in C/C++, but it could be triggered by a
3524         // weird EvaluateAsRValue call from a tool.)
3525         Info.FFDiag(Conv);
3526         return false;
3527       }
3528       if (LVal.Designator.isOnePastTheEnd()) {
3529         if (Info.getLangOpts().CPlusPlus11)
3530           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3531         else
3532           Info.FFDiag(Conv);
3533         return false;
3534       }
3535       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3536       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3537       return true;
3538     }
3539   }
3540 
3541   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3542   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3543 }
3544 
3545 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3546 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3547                              QualType LValType, APValue &Val) {
3548   if (LVal.Designator.Invalid)
3549     return false;
3550 
3551   if (!Info.getLangOpts().CPlusPlus14) {
3552     Info.FFDiag(E);
3553     return false;
3554   }
3555 
3556   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3557   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3558 }
3559 
3560 namespace {
3561 struct CompoundAssignSubobjectHandler {
3562   EvalInfo &Info;
3563   const Expr *E;
3564   QualType PromotedLHSType;
3565   BinaryOperatorKind Opcode;
3566   const APValue &RHS;
3567 
3568   static const AccessKinds AccessKind = AK_Assign;
3569 
3570   typedef bool result_type;
3571 
3572   bool checkConst(QualType QT) {
3573     // Assigning to a const object has undefined behavior.
3574     if (QT.isConstQualified()) {
3575       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3576       return false;
3577     }
3578     return true;
3579   }
3580 
3581   bool failed() { return false; }
3582   bool found(APValue &Subobj, QualType SubobjType) {
3583     switch (Subobj.getKind()) {
3584     case APValue::Int:
3585       return found(Subobj.getInt(), SubobjType);
3586     case APValue::Float:
3587       return found(Subobj.getFloat(), SubobjType);
3588     case APValue::ComplexInt:
3589     case APValue::ComplexFloat:
3590       // FIXME: Implement complex compound assignment.
3591       Info.FFDiag(E);
3592       return false;
3593     case APValue::LValue:
3594       return foundPointer(Subobj, SubobjType);
3595     default:
3596       // FIXME: can this happen?
3597       Info.FFDiag(E);
3598       return false;
3599     }
3600   }
3601   bool found(APSInt &Value, QualType SubobjType) {
3602     if (!checkConst(SubobjType))
3603       return false;
3604 
3605     if (!SubobjType->isIntegerType()) {
3606       // We don't support compound assignment on integer-cast-to-pointer
3607       // values.
3608       Info.FFDiag(E);
3609       return false;
3610     }
3611 
3612     if (RHS.isInt()) {
3613       APSInt LHS =
3614           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3615       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3616         return false;
3617       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3618       return true;
3619     } else if (RHS.isFloat()) {
3620       APFloat FValue(0.0);
3621       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3622                                   FValue) &&
3623              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3624              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3625                                   Value);
3626     }
3627 
3628     Info.FFDiag(E);
3629     return false;
3630   }
3631   bool found(APFloat &Value, QualType SubobjType) {
3632     return checkConst(SubobjType) &&
3633            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3634                                   Value) &&
3635            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3636            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3637   }
3638   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3639     if (!checkConst(SubobjType))
3640       return false;
3641 
3642     QualType PointeeType;
3643     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3644       PointeeType = PT->getPointeeType();
3645 
3646     if (PointeeType.isNull() || !RHS.isInt() ||
3647         (Opcode != BO_Add && Opcode != BO_Sub)) {
3648       Info.FFDiag(E);
3649       return false;
3650     }
3651 
3652     APSInt Offset = RHS.getInt();
3653     if (Opcode == BO_Sub)
3654       negateAsSigned(Offset);
3655 
3656     LValue LVal;
3657     LVal.setFrom(Info.Ctx, Subobj);
3658     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3659       return false;
3660     LVal.moveInto(Subobj);
3661     return true;
3662   }
3663 };
3664 } // end anonymous namespace
3665 
3666 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3667 
3668 /// Perform a compound assignment of LVal <op>= RVal.
3669 static bool handleCompoundAssignment(
3670     EvalInfo &Info, const Expr *E,
3671     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3672     BinaryOperatorKind Opcode, const APValue &RVal) {
3673   if (LVal.Designator.Invalid)
3674     return false;
3675 
3676   if (!Info.getLangOpts().CPlusPlus14) {
3677     Info.FFDiag(E);
3678     return false;
3679   }
3680 
3681   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3682   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3683                                              RVal };
3684   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3685 }
3686 
3687 namespace {
3688 struct IncDecSubobjectHandler {
3689   EvalInfo &Info;
3690   const UnaryOperator *E;
3691   AccessKinds AccessKind;
3692   APValue *Old;
3693 
3694   typedef bool result_type;
3695 
3696   bool checkConst(QualType QT) {
3697     // Assigning to a const object has undefined behavior.
3698     if (QT.isConstQualified()) {
3699       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3700       return false;
3701     }
3702     return true;
3703   }
3704 
3705   bool failed() { return false; }
3706   bool found(APValue &Subobj, QualType SubobjType) {
3707     // Stash the old value. Also clear Old, so we don't clobber it later
3708     // if we're post-incrementing a complex.
3709     if (Old) {
3710       *Old = Subobj;
3711       Old = nullptr;
3712     }
3713 
3714     switch (Subobj.getKind()) {
3715     case APValue::Int:
3716       return found(Subobj.getInt(), SubobjType);
3717     case APValue::Float:
3718       return found(Subobj.getFloat(), SubobjType);
3719     case APValue::ComplexInt:
3720       return found(Subobj.getComplexIntReal(),
3721                    SubobjType->castAs<ComplexType>()->getElementType()
3722                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3723     case APValue::ComplexFloat:
3724       return found(Subobj.getComplexFloatReal(),
3725                    SubobjType->castAs<ComplexType>()->getElementType()
3726                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3727     case APValue::LValue:
3728       return foundPointer(Subobj, SubobjType);
3729     default:
3730       // FIXME: can this happen?
3731       Info.FFDiag(E);
3732       return false;
3733     }
3734   }
3735   bool found(APSInt &Value, QualType SubobjType) {
3736     if (!checkConst(SubobjType))
3737       return false;
3738 
3739     if (!SubobjType->isIntegerType()) {
3740       // We don't support increment / decrement on integer-cast-to-pointer
3741       // values.
3742       Info.FFDiag(E);
3743       return false;
3744     }
3745 
3746     if (Old) *Old = APValue(Value);
3747 
3748     // bool arithmetic promotes to int, and the conversion back to bool
3749     // doesn't reduce mod 2^n, so special-case it.
3750     if (SubobjType->isBooleanType()) {
3751       if (AccessKind == AK_Increment)
3752         Value = 1;
3753       else
3754         Value = !Value;
3755       return true;
3756     }
3757 
3758     bool WasNegative = Value.isNegative();
3759     if (AccessKind == AK_Increment) {
3760       ++Value;
3761 
3762       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3763         APSInt ActualValue(Value, /*IsUnsigned*/true);
3764         return HandleOverflow(Info, E, ActualValue, SubobjType);
3765       }
3766     } else {
3767       --Value;
3768 
3769       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3770         unsigned BitWidth = Value.getBitWidth();
3771         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3772         ActualValue.setBit(BitWidth);
3773         return HandleOverflow(Info, E, ActualValue, SubobjType);
3774       }
3775     }
3776     return true;
3777   }
3778   bool found(APFloat &Value, QualType SubobjType) {
3779     if (!checkConst(SubobjType))
3780       return false;
3781 
3782     if (Old) *Old = APValue(Value);
3783 
3784     APFloat One(Value.getSemantics(), 1);
3785     if (AccessKind == AK_Increment)
3786       Value.add(One, APFloat::rmNearestTiesToEven);
3787     else
3788       Value.subtract(One, APFloat::rmNearestTiesToEven);
3789     return true;
3790   }
3791   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3792     if (!checkConst(SubobjType))
3793       return false;
3794 
3795     QualType PointeeType;
3796     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3797       PointeeType = PT->getPointeeType();
3798     else {
3799       Info.FFDiag(E);
3800       return false;
3801     }
3802 
3803     LValue LVal;
3804     LVal.setFrom(Info.Ctx, Subobj);
3805     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3806                                      AccessKind == AK_Increment ? 1 : -1))
3807       return false;
3808     LVal.moveInto(Subobj);
3809     return true;
3810   }
3811 };
3812 } // end anonymous namespace
3813 
3814 /// Perform an increment or decrement on LVal.
3815 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3816                          QualType LValType, bool IsIncrement, APValue *Old) {
3817   if (LVal.Designator.Invalid)
3818     return false;
3819 
3820   if (!Info.getLangOpts().CPlusPlus14) {
3821     Info.FFDiag(E);
3822     return false;
3823   }
3824 
3825   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3826   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3827   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3828   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3829 }
3830 
3831 /// Build an lvalue for the object argument of a member function call.
3832 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3833                                    LValue &This) {
3834   if (Object->getType()->isPointerType())
3835     return EvaluatePointer(Object, This, Info);
3836 
3837   if (Object->isGLValue())
3838     return EvaluateLValue(Object, This, Info);
3839 
3840   if (Object->getType()->isLiteralType(Info.Ctx))
3841     return EvaluateTemporary(Object, This, Info);
3842 
3843   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3844   return false;
3845 }
3846 
3847 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3848 /// lvalue referring to the result.
3849 ///
3850 /// \param Info - Information about the ongoing evaluation.
3851 /// \param LV - An lvalue referring to the base of the member pointer.
3852 /// \param RHS - The member pointer expression.
3853 /// \param IncludeMember - Specifies whether the member itself is included in
3854 ///        the resulting LValue subobject designator. This is not possible when
3855 ///        creating a bound member function.
3856 /// \return The field or method declaration to which the member pointer refers,
3857 ///         or 0 if evaluation fails.
3858 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3859                                                   QualType LVType,
3860                                                   LValue &LV,
3861                                                   const Expr *RHS,
3862                                                   bool IncludeMember = true) {
3863   MemberPtr MemPtr;
3864   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3865     return nullptr;
3866 
3867   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3868   // member value, the behavior is undefined.
3869   if (!MemPtr.getDecl()) {
3870     // FIXME: Specific diagnostic.
3871     Info.FFDiag(RHS);
3872     return nullptr;
3873   }
3874 
3875   if (MemPtr.isDerivedMember()) {
3876     // This is a member of some derived class. Truncate LV appropriately.
3877     // The end of the derived-to-base path for the base object must match the
3878     // derived-to-base path for the member pointer.
3879     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3880         LV.Designator.Entries.size()) {
3881       Info.FFDiag(RHS);
3882       return nullptr;
3883     }
3884     unsigned PathLengthToMember =
3885         LV.Designator.Entries.size() - MemPtr.Path.size();
3886     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3887       const CXXRecordDecl *LVDecl = getAsBaseClass(
3888           LV.Designator.Entries[PathLengthToMember + I]);
3889       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3890       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3891         Info.FFDiag(RHS);
3892         return nullptr;
3893       }
3894     }
3895 
3896     // Truncate the lvalue to the appropriate derived class.
3897     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3898                             PathLengthToMember))
3899       return nullptr;
3900   } else if (!MemPtr.Path.empty()) {
3901     // Extend the LValue path with the member pointer's path.
3902     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3903                                   MemPtr.Path.size() + IncludeMember);
3904 
3905     // Walk down to the appropriate base class.
3906     if (const PointerType *PT = LVType->getAs<PointerType>())
3907       LVType = PT->getPointeeType();
3908     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3909     assert(RD && "member pointer access on non-class-type expression");
3910     // The first class in the path is that of the lvalue.
3911     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3912       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3913       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3914         return nullptr;
3915       RD = Base;
3916     }
3917     // Finally cast to the class containing the member.
3918     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3919                                 MemPtr.getContainingRecord()))
3920       return nullptr;
3921   }
3922 
3923   // Add the member. Note that we cannot build bound member functions here.
3924   if (IncludeMember) {
3925     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3926       if (!HandleLValueMember(Info, RHS, LV, FD))
3927         return nullptr;
3928     } else if (const IndirectFieldDecl *IFD =
3929                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3930       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3931         return nullptr;
3932     } else {
3933       llvm_unreachable("can't construct reference to bound member function");
3934     }
3935   }
3936 
3937   return MemPtr.getDecl();
3938 }
3939 
3940 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3941                                                   const BinaryOperator *BO,
3942                                                   LValue &LV,
3943                                                   bool IncludeMember = true) {
3944   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3945 
3946   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3947     if (Info.noteFailure()) {
3948       MemberPtr MemPtr;
3949       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3950     }
3951     return nullptr;
3952   }
3953 
3954   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3955                                    BO->getRHS(), IncludeMember);
3956 }
3957 
3958 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3959 /// the provided lvalue, which currently refers to the base object.
3960 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3961                                     LValue &Result) {
3962   SubobjectDesignator &D = Result.Designator;
3963   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3964     return false;
3965 
3966   QualType TargetQT = E->getType();
3967   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3968     TargetQT = PT->getPointeeType();
3969 
3970   // Check this cast lands within the final derived-to-base subobject path.
3971   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3972     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3973       << D.MostDerivedType << TargetQT;
3974     return false;
3975   }
3976 
3977   // Check the type of the final cast. We don't need to check the path,
3978   // since a cast can only be formed if the path is unique.
3979   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3980   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3981   const CXXRecordDecl *FinalType;
3982   if (NewEntriesSize == D.MostDerivedPathLength)
3983     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3984   else
3985     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3986   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3987     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3988       << D.MostDerivedType << TargetQT;
3989     return false;
3990   }
3991 
3992   // Truncate the lvalue to the appropriate derived class.
3993   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3994 }
3995 
3996 namespace {
3997 enum EvalStmtResult {
3998   /// Evaluation failed.
3999   ESR_Failed,
4000   /// Hit a 'return' statement.
4001   ESR_Returned,
4002   /// Evaluation succeeded.
4003   ESR_Succeeded,
4004   /// Hit a 'continue' statement.
4005   ESR_Continue,
4006   /// Hit a 'break' statement.
4007   ESR_Break,
4008   /// Still scanning for 'case' or 'default' statement.
4009   ESR_CaseNotFound
4010 };
4011 }
4012 
4013 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4014   // We don't need to evaluate the initializer for a static local.
4015   if (!VD->hasLocalStorage())
4016     return true;
4017 
4018   LValue Result;
4019   APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
4020 
4021   const Expr *InitE = VD->getInit();
4022   if (!InitE) {
4023     Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4024         << false << VD->getType();
4025     Val = APValue();
4026     return false;
4027   }
4028 
4029   if (InitE->isValueDependent())
4030     return false;
4031 
4032   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4033     // Wipe out any partially-computed value, to allow tracking that this
4034     // evaluation failed.
4035     Val = APValue();
4036     return false;
4037   }
4038 
4039   return true;
4040 }
4041 
4042 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4043   bool OK = true;
4044 
4045   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4046     OK &= EvaluateVarDecl(Info, VD);
4047 
4048   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4049     for (auto *BD : DD->bindings())
4050       if (auto *VD = BD->getHoldingVar())
4051         OK &= EvaluateDecl(Info, VD);
4052 
4053   return OK;
4054 }
4055 
4056 
4057 /// Evaluate a condition (either a variable declaration or an expression).
4058 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4059                          const Expr *Cond, bool &Result) {
4060   FullExpressionRAII Scope(Info);
4061   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4062     return false;
4063   return EvaluateAsBooleanCondition(Cond, Result, Info);
4064 }
4065 
4066 namespace {
4067 /// A location where the result (returned value) of evaluating a
4068 /// statement should be stored.
4069 struct StmtResult {
4070   /// The APValue that should be filled in with the returned value.
4071   APValue &Value;
4072   /// The location containing the result, if any (used to support RVO).
4073   const LValue *Slot;
4074 };
4075 
4076 struct TempVersionRAII {
4077   CallStackFrame &Frame;
4078 
4079   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4080     Frame.pushTempVersion();
4081   }
4082 
4083   ~TempVersionRAII() {
4084     Frame.popTempVersion();
4085   }
4086 };
4087 
4088 }
4089 
4090 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4091                                    const Stmt *S,
4092                                    const SwitchCase *SC = nullptr);
4093 
4094 /// Evaluate the body of a loop, and translate the result as appropriate.
4095 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4096                                        const Stmt *Body,
4097                                        const SwitchCase *Case = nullptr) {
4098   BlockScopeRAII Scope(Info);
4099   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
4100   case ESR_Break:
4101     return ESR_Succeeded;
4102   case ESR_Succeeded:
4103   case ESR_Continue:
4104     return ESR_Continue;
4105   case ESR_Failed:
4106   case ESR_Returned:
4107   case ESR_CaseNotFound:
4108     return ESR;
4109   }
4110   llvm_unreachable("Invalid EvalStmtResult!");
4111 }
4112 
4113 /// Evaluate a switch statement.
4114 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4115                                      const SwitchStmt *SS) {
4116   BlockScopeRAII Scope(Info);
4117 
4118   // Evaluate the switch condition.
4119   APSInt Value;
4120   {
4121     FullExpressionRAII Scope(Info);
4122     if (const Stmt *Init = SS->getInit()) {
4123       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4124       if (ESR != ESR_Succeeded)
4125         return ESR;
4126     }
4127     if (SS->getConditionVariable() &&
4128         !EvaluateDecl(Info, SS->getConditionVariable()))
4129       return ESR_Failed;
4130     if (!EvaluateInteger(SS->getCond(), Value, Info))
4131       return ESR_Failed;
4132   }
4133 
4134   // Find the switch case corresponding to the value of the condition.
4135   // FIXME: Cache this lookup.
4136   const SwitchCase *Found = nullptr;
4137   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4138        SC = SC->getNextSwitchCase()) {
4139     if (isa<DefaultStmt>(SC)) {
4140       Found = SC;
4141       continue;
4142     }
4143 
4144     const CaseStmt *CS = cast<CaseStmt>(SC);
4145     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4146     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4147                               : LHS;
4148     if (LHS <= Value && Value <= RHS) {
4149       Found = SC;
4150       break;
4151     }
4152   }
4153 
4154   if (!Found)
4155     return ESR_Succeeded;
4156 
4157   // Search the switch body for the switch case and evaluate it from there.
4158   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4159   case ESR_Break:
4160     return ESR_Succeeded;
4161   case ESR_Succeeded:
4162   case ESR_Continue:
4163   case ESR_Failed:
4164   case ESR_Returned:
4165     return ESR;
4166   case ESR_CaseNotFound:
4167     // This can only happen if the switch case is nested within a statement
4168     // expression. We have no intention of supporting that.
4169     Info.FFDiag(Found->getBeginLoc(),
4170                 diag::note_constexpr_stmt_expr_unsupported);
4171     return ESR_Failed;
4172   }
4173   llvm_unreachable("Invalid EvalStmtResult!");
4174 }
4175 
4176 // Evaluate a statement.
4177 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4178                                    const Stmt *S, const SwitchCase *Case) {
4179   if (!Info.nextStep(S))
4180     return ESR_Failed;
4181 
4182   // If we're hunting down a 'case' or 'default' label, recurse through
4183   // substatements until we hit the label.
4184   if (Case) {
4185     // FIXME: We don't start the lifetime of objects whose initialization we
4186     // jump over. However, such objects must be of class type with a trivial
4187     // default constructor that initialize all subobjects, so must be empty,
4188     // so this almost never matters.
4189     switch (S->getStmtClass()) {
4190     case Stmt::CompoundStmtClass:
4191       // FIXME: Precompute which substatement of a compound statement we
4192       // would jump to, and go straight there rather than performing a
4193       // linear scan each time.
4194     case Stmt::LabelStmtClass:
4195     case Stmt::AttributedStmtClass:
4196     case Stmt::DoStmtClass:
4197       break;
4198 
4199     case Stmt::CaseStmtClass:
4200     case Stmt::DefaultStmtClass:
4201       if (Case == S)
4202         Case = nullptr;
4203       break;
4204 
4205     case Stmt::IfStmtClass: {
4206       // FIXME: Precompute which side of an 'if' we would jump to, and go
4207       // straight there rather than scanning both sides.
4208       const IfStmt *IS = cast<IfStmt>(S);
4209 
4210       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4211       // preceded by our switch label.
4212       BlockScopeRAII Scope(Info);
4213 
4214       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4215       if (ESR != ESR_CaseNotFound || !IS->getElse())
4216         return ESR;
4217       return EvaluateStmt(Result, Info, IS->getElse(), Case);
4218     }
4219 
4220     case Stmt::WhileStmtClass: {
4221       EvalStmtResult ESR =
4222           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4223       if (ESR != ESR_Continue)
4224         return ESR;
4225       break;
4226     }
4227 
4228     case Stmt::ForStmtClass: {
4229       const ForStmt *FS = cast<ForStmt>(S);
4230       EvalStmtResult ESR =
4231           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4232       if (ESR != ESR_Continue)
4233         return ESR;
4234       if (FS->getInc()) {
4235         FullExpressionRAII IncScope(Info);
4236         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4237           return ESR_Failed;
4238       }
4239       break;
4240     }
4241 
4242     case Stmt::DeclStmtClass:
4243       // FIXME: If the variable has initialization that can't be jumped over,
4244       // bail out of any immediately-surrounding compound-statement too.
4245     default:
4246       return ESR_CaseNotFound;
4247     }
4248   }
4249 
4250   switch (S->getStmtClass()) {
4251   default:
4252     if (const Expr *E = dyn_cast<Expr>(S)) {
4253       // Don't bother evaluating beyond an expression-statement which couldn't
4254       // be evaluated.
4255       FullExpressionRAII Scope(Info);
4256       if (!EvaluateIgnoredValue(Info, E))
4257         return ESR_Failed;
4258       return ESR_Succeeded;
4259     }
4260 
4261     Info.FFDiag(S->getBeginLoc());
4262     return ESR_Failed;
4263 
4264   case Stmt::NullStmtClass:
4265     return ESR_Succeeded;
4266 
4267   case Stmt::DeclStmtClass: {
4268     const DeclStmt *DS = cast<DeclStmt>(S);
4269     for (const auto *DclIt : DS->decls()) {
4270       // Each declaration initialization is its own full-expression.
4271       // FIXME: This isn't quite right; if we're performing aggregate
4272       // initialization, each braced subexpression is its own full-expression.
4273       FullExpressionRAII Scope(Info);
4274       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4275         return ESR_Failed;
4276     }
4277     return ESR_Succeeded;
4278   }
4279 
4280   case Stmt::ReturnStmtClass: {
4281     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4282     FullExpressionRAII Scope(Info);
4283     if (RetExpr &&
4284         !(Result.Slot
4285               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4286               : Evaluate(Result.Value, Info, RetExpr)))
4287       return ESR_Failed;
4288     return ESR_Returned;
4289   }
4290 
4291   case Stmt::CompoundStmtClass: {
4292     BlockScopeRAII Scope(Info);
4293 
4294     const CompoundStmt *CS = cast<CompoundStmt>(S);
4295     for (const auto *BI : CS->body()) {
4296       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4297       if (ESR == ESR_Succeeded)
4298         Case = nullptr;
4299       else if (ESR != ESR_CaseNotFound)
4300         return ESR;
4301     }
4302     return Case ? ESR_CaseNotFound : ESR_Succeeded;
4303   }
4304 
4305   case Stmt::IfStmtClass: {
4306     const IfStmt *IS = cast<IfStmt>(S);
4307 
4308     // Evaluate the condition, as either a var decl or as an expression.
4309     BlockScopeRAII Scope(Info);
4310     if (const Stmt *Init = IS->getInit()) {
4311       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4312       if (ESR != ESR_Succeeded)
4313         return ESR;
4314     }
4315     bool Cond;
4316     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4317       return ESR_Failed;
4318 
4319     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4320       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4321       if (ESR != ESR_Succeeded)
4322         return ESR;
4323     }
4324     return ESR_Succeeded;
4325   }
4326 
4327   case Stmt::WhileStmtClass: {
4328     const WhileStmt *WS = cast<WhileStmt>(S);
4329     while (true) {
4330       BlockScopeRAII Scope(Info);
4331       bool Continue;
4332       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4333                         Continue))
4334         return ESR_Failed;
4335       if (!Continue)
4336         break;
4337 
4338       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4339       if (ESR != ESR_Continue)
4340         return ESR;
4341     }
4342     return ESR_Succeeded;
4343   }
4344 
4345   case Stmt::DoStmtClass: {
4346     const DoStmt *DS = cast<DoStmt>(S);
4347     bool Continue;
4348     do {
4349       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4350       if (ESR != ESR_Continue)
4351         return ESR;
4352       Case = nullptr;
4353 
4354       FullExpressionRAII CondScope(Info);
4355       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4356         return ESR_Failed;
4357     } while (Continue);
4358     return ESR_Succeeded;
4359   }
4360 
4361   case Stmt::ForStmtClass: {
4362     const ForStmt *FS = cast<ForStmt>(S);
4363     BlockScopeRAII Scope(Info);
4364     if (FS->getInit()) {
4365       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4366       if (ESR != ESR_Succeeded)
4367         return ESR;
4368     }
4369     while (true) {
4370       BlockScopeRAII Scope(Info);
4371       bool Continue = true;
4372       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4373                                          FS->getCond(), Continue))
4374         return ESR_Failed;
4375       if (!Continue)
4376         break;
4377 
4378       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4379       if (ESR != ESR_Continue)
4380         return ESR;
4381 
4382       if (FS->getInc()) {
4383         FullExpressionRAII IncScope(Info);
4384         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4385           return ESR_Failed;
4386       }
4387     }
4388     return ESR_Succeeded;
4389   }
4390 
4391   case Stmt::CXXForRangeStmtClass: {
4392     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4393     BlockScopeRAII Scope(Info);
4394 
4395     // Evaluate the init-statement if present.
4396     if (FS->getInit()) {
4397       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4398       if (ESR != ESR_Succeeded)
4399         return ESR;
4400     }
4401 
4402     // Initialize the __range variable.
4403     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4404     if (ESR != ESR_Succeeded)
4405       return ESR;
4406 
4407     // Create the __begin and __end iterators.
4408     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4409     if (ESR != ESR_Succeeded)
4410       return ESR;
4411     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4412     if (ESR != ESR_Succeeded)
4413       return ESR;
4414 
4415     while (true) {
4416       // Condition: __begin != __end.
4417       {
4418         bool Continue = true;
4419         FullExpressionRAII CondExpr(Info);
4420         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4421           return ESR_Failed;
4422         if (!Continue)
4423           break;
4424       }
4425 
4426       // User's variable declaration, initialized by *__begin.
4427       BlockScopeRAII InnerScope(Info);
4428       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4429       if (ESR != ESR_Succeeded)
4430         return ESR;
4431 
4432       // Loop body.
4433       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4434       if (ESR != ESR_Continue)
4435         return ESR;
4436 
4437       // Increment: ++__begin
4438       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4439         return ESR_Failed;
4440     }
4441 
4442     return ESR_Succeeded;
4443   }
4444 
4445   case Stmt::SwitchStmtClass:
4446     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4447 
4448   case Stmt::ContinueStmtClass:
4449     return ESR_Continue;
4450 
4451   case Stmt::BreakStmtClass:
4452     return ESR_Break;
4453 
4454   case Stmt::LabelStmtClass:
4455     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4456 
4457   case Stmt::AttributedStmtClass:
4458     // As a general principle, C++11 attributes can be ignored without
4459     // any semantic impact.
4460     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4461                         Case);
4462 
4463   case Stmt::CaseStmtClass:
4464   case Stmt::DefaultStmtClass:
4465     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4466   case Stmt::CXXTryStmtClass:
4467     // Evaluate try blocks by evaluating all sub statements.
4468     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4469   }
4470 }
4471 
4472 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4473 /// default constructor. If so, we'll fold it whether or not it's marked as
4474 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4475 /// so we need special handling.
4476 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4477                                            const CXXConstructorDecl *CD,
4478                                            bool IsValueInitialization) {
4479   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4480     return false;
4481 
4482   // Value-initialization does not call a trivial default constructor, so such a
4483   // call is a core constant expression whether or not the constructor is
4484   // constexpr.
4485   if (!CD->isConstexpr() && !IsValueInitialization) {
4486     if (Info.getLangOpts().CPlusPlus11) {
4487       // FIXME: If DiagDecl is an implicitly-declared special member function,
4488       // we should be much more explicit about why it's not constexpr.
4489       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4490         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4491       Info.Note(CD->getLocation(), diag::note_declared_at);
4492     } else {
4493       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4494     }
4495   }
4496   return true;
4497 }
4498 
4499 /// CheckConstexprFunction - Check that a function can be called in a constant
4500 /// expression.
4501 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4502                                    const FunctionDecl *Declaration,
4503                                    const FunctionDecl *Definition,
4504                                    const Stmt *Body) {
4505   // Potential constant expressions can contain calls to declared, but not yet
4506   // defined, constexpr functions.
4507   if (Info.checkingPotentialConstantExpression() && !Definition &&
4508       Declaration->isConstexpr())
4509     return false;
4510 
4511   // Bail out if the function declaration itself is invalid.  We will
4512   // have produced a relevant diagnostic while parsing it, so just
4513   // note the problematic sub-expression.
4514   if (Declaration->isInvalidDecl()) {
4515     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4516     return false;
4517   }
4518 
4519   // DR1872: An instantiated virtual constexpr function can't be called in a
4520   // constant expression (prior to C++20). We can still constant-fold such a
4521   // call.
4522   if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4523       cast<CXXMethodDecl>(Declaration)->isVirtual())
4524     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4525 
4526   if (Definition && Definition->isInvalidDecl()) {
4527     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4528     return false;
4529   }
4530 
4531   // Can we evaluate this function call?
4532   if (Definition && Definition->isConstexpr() && Body)
4533     return true;
4534 
4535   if (Info.getLangOpts().CPlusPlus11) {
4536     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4537 
4538     // If this function is not constexpr because it is an inherited
4539     // non-constexpr constructor, diagnose that directly.
4540     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4541     if (CD && CD->isInheritingConstructor()) {
4542       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4543       if (!Inherited->isConstexpr())
4544         DiagDecl = CD = Inherited;
4545     }
4546 
4547     // FIXME: If DiagDecl is an implicitly-declared special member function
4548     // or an inheriting constructor, we should be much more explicit about why
4549     // it's not constexpr.
4550     if (CD && CD->isInheritingConstructor())
4551       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4552         << CD->getInheritedConstructor().getConstructor()->getParent();
4553     else
4554       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4555         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4556     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4557   } else {
4558     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4559   }
4560   return false;
4561 }
4562 
4563 namespace {
4564 struct CheckDynamicTypeHandler {
4565   AccessKinds AccessKind;
4566   typedef bool result_type;
4567   bool failed() { return false; }
4568   bool found(APValue &Subobj, QualType SubobjType) { return true; }
4569   bool found(APSInt &Value, QualType SubobjType) { return true; }
4570   bool found(APFloat &Value, QualType SubobjType) { return true; }
4571 };
4572 } // end anonymous namespace
4573 
4574 /// Check that we can access the notional vptr of an object / determine its
4575 /// dynamic type.
4576 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4577                              AccessKinds AK, bool Polymorphic) {
4578   if (This.Designator.Invalid)
4579     return false;
4580 
4581   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4582 
4583   if (!Obj)
4584     return false;
4585 
4586   if (!Obj.Value) {
4587     // The object is not usable in constant expressions, so we can't inspect
4588     // its value to see if it's in-lifetime or what the active union members
4589     // are. We can still check for a one-past-the-end lvalue.
4590     if (This.Designator.isOnePastTheEnd() ||
4591         This.Designator.isMostDerivedAnUnsizedArray()) {
4592       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4593                          ? diag::note_constexpr_access_past_end
4594                          : diag::note_constexpr_access_unsized_array)
4595           << AK;
4596       return false;
4597     } else if (Polymorphic) {
4598       // Conservatively refuse to perform a polymorphic operation if we would
4599       // not be able to read a notional 'vptr' value.
4600       APValue Val;
4601       This.moveInto(Val);
4602       QualType StarThisType =
4603           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
4604       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4605           << AK << Val.getAsString(Info.Ctx, StarThisType);
4606       return false;
4607     }
4608     return true;
4609   }
4610 
4611   CheckDynamicTypeHandler Handler{AK};
4612   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4613 }
4614 
4615 /// Check that the pointee of the 'this' pointer in a member function call is
4616 /// either within its lifetime or in its period of construction or destruction.
4617 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4618                                                  const LValue &This) {
4619   return checkDynamicType(Info, E, This, AK_MemberCall, false);
4620 }
4621 
4622 struct DynamicType {
4623   /// The dynamic class type of the object.
4624   const CXXRecordDecl *Type;
4625   /// The corresponding path length in the lvalue.
4626   unsigned PathLength;
4627 };
4628 
4629 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4630                                              unsigned PathLength) {
4631   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4632       Designator.Entries.size() && "invalid path length");
4633   return (PathLength == Designator.MostDerivedPathLength)
4634              ? Designator.MostDerivedType->getAsCXXRecordDecl()
4635              : getAsBaseClass(Designator.Entries[PathLength - 1]);
4636 }
4637 
4638 /// Determine the dynamic type of an object.
4639 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4640                                                 LValue &This, AccessKinds AK) {
4641   // If we don't have an lvalue denoting an object of class type, there is no
4642   // meaningful dynamic type. (We consider objects of non-class type to have no
4643   // dynamic type.)
4644   if (!checkDynamicType(Info, E, This, AK, true))
4645     return None;
4646 
4647   // Refuse to compute a dynamic type in the presence of virtual bases. This
4648   // shouldn't happen other than in constant-folding situations, since literal
4649   // types can't have virtual bases.
4650   //
4651   // Note that consumers of DynamicType assume that the type has no virtual
4652   // bases, and will need modifications if this restriction is relaxed.
4653   const CXXRecordDecl *Class =
4654       This.Designator.MostDerivedType->getAsCXXRecordDecl();
4655   if (!Class || Class->getNumVBases()) {
4656     Info.FFDiag(E);
4657     return None;
4658   }
4659 
4660   // FIXME: For very deep class hierarchies, it might be beneficial to use a
4661   // binary search here instead. But the overwhelmingly common case is that
4662   // we're not in the middle of a constructor, so it probably doesn't matter
4663   // in practice.
4664   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4665   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4666        PathLength <= Path.size(); ++PathLength) {
4667     switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4668                                          Path.slice(0, PathLength))) {
4669     case ConstructionPhase::Bases:
4670       // We're constructing a base class. This is not the dynamic type.
4671       break;
4672 
4673     case ConstructionPhase::None:
4674     case ConstructionPhase::AfterBases:
4675       // We've finished constructing the base classes, so this is the dynamic
4676       // type.
4677       return DynamicType{getBaseClassType(This.Designator, PathLength),
4678                          PathLength};
4679     }
4680   }
4681 
4682   // CWG issue 1517: we're constructing a base class of the object described by
4683   // 'This', so that object has not yet begun its period of construction and
4684   // any polymorphic operation on it results in undefined behavior.
4685   Info.FFDiag(E);
4686   return None;
4687 }
4688 
4689 /// Perform virtual dispatch.
4690 static const CXXMethodDecl *HandleVirtualDispatch(
4691     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4692     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
4693   Optional<DynamicType> DynType =
4694       ComputeDynamicType(Info, E, This, AK_MemberCall);
4695   if (!DynType)
4696     return nullptr;
4697 
4698   // Find the final overrider. It must be declared in one of the classes on the
4699   // path from the dynamic type to the static type.
4700   // FIXME: If we ever allow literal types to have virtual base classes, that
4701   // won't be true.
4702   const CXXMethodDecl *Callee = Found;
4703   unsigned PathLength = DynType->PathLength;
4704   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4705     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
4706     const CXXMethodDecl *Overrider =
4707         Found->getCorrespondingMethodDeclaredInClass(Class, false);
4708     if (Overrider) {
4709       Callee = Overrider;
4710       break;
4711     }
4712   }
4713 
4714   // C++2a [class.abstract]p6:
4715   //   the effect of making a virtual call to a pure virtual function [...] is
4716   //   undefined
4717   if (Callee->isPure()) {
4718     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4719     Info.Note(Callee->getLocation(), diag::note_declared_at);
4720     return nullptr;
4721   }
4722 
4723   // If necessary, walk the rest of the path to determine the sequence of
4724   // covariant adjustment steps to apply.
4725   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4726                                        Found->getReturnType())) {
4727     CovariantAdjustmentPath.push_back(Callee->getReturnType());
4728     for (unsigned CovariantPathLength = PathLength + 1;
4729          CovariantPathLength != This.Designator.Entries.size();
4730          ++CovariantPathLength) {
4731       const CXXRecordDecl *NextClass =
4732           getBaseClassType(This.Designator, CovariantPathLength);
4733       const CXXMethodDecl *Next =
4734           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4735       if (Next && !Info.Ctx.hasSameUnqualifiedType(
4736                       Next->getReturnType(), CovariantAdjustmentPath.back()))
4737         CovariantAdjustmentPath.push_back(Next->getReturnType());
4738     }
4739     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4740                                          CovariantAdjustmentPath.back()))
4741       CovariantAdjustmentPath.push_back(Found->getReturnType());
4742   }
4743 
4744   // Perform 'this' adjustment.
4745   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4746     return nullptr;
4747 
4748   return Callee;
4749 }
4750 
4751 /// Perform the adjustment from a value returned by a virtual function to
4752 /// a value of the statically expected type, which may be a pointer or
4753 /// reference to a base class of the returned type.
4754 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4755                                             APValue &Result,
4756                                             ArrayRef<QualType> Path) {
4757   assert(Result.isLValue() &&
4758          "unexpected kind of APValue for covariant return");
4759   if (Result.isNullPointer())
4760     return true;
4761 
4762   LValue LVal;
4763   LVal.setFrom(Info.Ctx, Result);
4764 
4765   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4766   for (unsigned I = 1; I != Path.size(); ++I) {
4767     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4768     assert(OldClass && NewClass && "unexpected kind of covariant return");
4769     if (OldClass != NewClass &&
4770         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4771       return false;
4772     OldClass = NewClass;
4773   }
4774 
4775   LVal.moveInto(Result);
4776   return true;
4777 }
4778 
4779 /// Determine whether \p Base, which is known to be a direct base class of
4780 /// \p Derived, is a public base class.
4781 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4782                               const CXXRecordDecl *Base) {
4783   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4784     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4785     if (BaseClass && declaresSameEntity(BaseClass, Base))
4786       return BaseSpec.getAccessSpecifier() == AS_public;
4787   }
4788   llvm_unreachable("Base is not a direct base of Derived");
4789 }
4790 
4791 /// Apply the given dynamic cast operation on the provided lvalue.
4792 ///
4793 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
4794 /// to find a suitable target subobject.
4795 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4796                               LValue &Ptr) {
4797   // We can't do anything with a non-symbolic pointer value.
4798   SubobjectDesignator &D = Ptr.Designator;
4799   if (D.Invalid)
4800     return false;
4801 
4802   // C++ [expr.dynamic.cast]p6:
4803   //   If v is a null pointer value, the result is a null pointer value.
4804   if (Ptr.isNullPointer() && !E->isGLValue())
4805     return true;
4806 
4807   // For all the other cases, we need the pointer to point to an object within
4808   // its lifetime / period of construction / destruction, and we need to know
4809   // its dynamic type.
4810   Optional<DynamicType> DynType =
4811       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4812   if (!DynType)
4813     return false;
4814 
4815   // C++ [expr.dynamic.cast]p7:
4816   //   If T is "pointer to cv void", then the result is a pointer to the most
4817   //   derived object
4818   if (E->getType()->isVoidPointerType())
4819     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4820 
4821   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4822   assert(C && "dynamic_cast target is not void pointer nor class");
4823   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4824 
4825   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4826     // C++ [expr.dynamic.cast]p9:
4827     if (!E->isGLValue()) {
4828       //   The value of a failed cast to pointer type is the null pointer value
4829       //   of the required result type.
4830       auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4831       Ptr.setNull(E->getType(), TargetVal);
4832       return true;
4833     }
4834 
4835     //   A failed cast to reference type throws [...] std::bad_cast.
4836     unsigned DiagKind;
4837     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4838                    DynType->Type->isDerivedFrom(C)))
4839       DiagKind = 0;
4840     else if (!Paths || Paths->begin() == Paths->end())
4841       DiagKind = 1;
4842     else if (Paths->isAmbiguous(CQT))
4843       DiagKind = 2;
4844     else {
4845       assert(Paths->front().Access != AS_public && "why did the cast fail?");
4846       DiagKind = 3;
4847     }
4848     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4849         << DiagKind << Ptr.Designator.getType(Info.Ctx)
4850         << Info.Ctx.getRecordType(DynType->Type)
4851         << E->getType().getUnqualifiedType();
4852     return false;
4853   };
4854 
4855   // Runtime check, phase 1:
4856   //   Walk from the base subobject towards the derived object looking for the
4857   //   target type.
4858   for (int PathLength = Ptr.Designator.Entries.size();
4859        PathLength >= (int)DynType->PathLength; --PathLength) {
4860     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4861     if (declaresSameEntity(Class, C))
4862       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4863     // We can only walk across public inheritance edges.
4864     if (PathLength > (int)DynType->PathLength &&
4865         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4866                            Class))
4867       return RuntimeCheckFailed(nullptr);
4868   }
4869 
4870   // Runtime check, phase 2:
4871   //   Search the dynamic type for an unambiguous public base of type C.
4872   CXXBasePaths Paths(/*FindAmbiguities=*/true,
4873                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
4874   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4875       Paths.front().Access == AS_public) {
4876     // Downcast to the dynamic type...
4877     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4878       return false;
4879     // ... then upcast to the chosen base class subobject.
4880     for (CXXBasePathElement &Elem : Paths.front())
4881       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4882         return false;
4883     return true;
4884   }
4885 
4886   // Otherwise, the runtime check fails.
4887   return RuntimeCheckFailed(&Paths);
4888 }
4889 
4890 /// Determine if a class has any fields that might need to be copied by a
4891 /// trivial copy or move operation.
4892 static bool hasFields(const CXXRecordDecl *RD) {
4893   if (!RD || RD->isEmpty())
4894     return false;
4895   for (auto *FD : RD->fields()) {
4896     if (FD->isUnnamedBitfield())
4897       continue;
4898     return true;
4899   }
4900   for (auto &Base : RD->bases())
4901     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4902       return true;
4903   return false;
4904 }
4905 
4906 namespace {
4907 typedef SmallVector<APValue, 8> ArgVector;
4908 }
4909 
4910 /// EvaluateArgs - Evaluate the arguments to a function call.
4911 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4912                          EvalInfo &Info) {
4913   bool Success = true;
4914   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4915        I != E; ++I) {
4916     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4917       // If we're checking for a potential constant expression, evaluate all
4918       // initializers even if some of them fail.
4919       if (!Info.noteFailure())
4920         return false;
4921       Success = false;
4922     }
4923   }
4924   return Success;
4925 }
4926 
4927 /// Evaluate a function call.
4928 static bool HandleFunctionCall(SourceLocation CallLoc,
4929                                const FunctionDecl *Callee, const LValue *This,
4930                                ArrayRef<const Expr*> Args, const Stmt *Body,
4931                                EvalInfo &Info, APValue &Result,
4932                                const LValue *ResultSlot) {
4933   ArgVector ArgValues(Args.size());
4934   if (!EvaluateArgs(Args, ArgValues, Info))
4935     return false;
4936 
4937   if (!Info.CheckCallLimit(CallLoc))
4938     return false;
4939 
4940   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4941 
4942   // For a trivial copy or move assignment, perform an APValue copy. This is
4943   // essential for unions, where the operations performed by the assignment
4944   // operator cannot be represented as statements.
4945   //
4946   // Skip this for non-union classes with no fields; in that case, the defaulted
4947   // copy/move does not actually read the object.
4948   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4949   if (MD && MD->isDefaulted() &&
4950       (MD->getParent()->isUnion() ||
4951        (MD->isTrivial() && hasFields(MD->getParent())))) {
4952     assert(This &&
4953            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4954     LValue RHS;
4955     RHS.setFrom(Info.Ctx, ArgValues[0]);
4956     APValue RHSValue;
4957     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4958                                         RHS, RHSValue))
4959       return false;
4960     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
4961                           RHSValue))
4962       return false;
4963     This->moveInto(Result);
4964     return true;
4965   } else if (MD && isLambdaCallOperator(MD)) {
4966     // We're in a lambda; determine the lambda capture field maps unless we're
4967     // just constexpr checking a lambda's call operator. constexpr checking is
4968     // done before the captures have been added to the closure object (unless
4969     // we're inferring constexpr-ness), so we don't have access to them in this
4970     // case. But since we don't need the captures to constexpr check, we can
4971     // just ignore them.
4972     if (!Info.checkingPotentialConstantExpression())
4973       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4974                                         Frame.LambdaThisCaptureField);
4975   }
4976 
4977   StmtResult Ret = {Result, ResultSlot};
4978   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4979   if (ESR == ESR_Succeeded) {
4980     if (Callee->getReturnType()->isVoidType())
4981       return true;
4982     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
4983   }
4984   return ESR == ESR_Returned;
4985 }
4986 
4987 /// Evaluate a constructor call.
4988 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4989                                   APValue *ArgValues,
4990                                   const CXXConstructorDecl *Definition,
4991                                   EvalInfo &Info, APValue &Result) {
4992   SourceLocation CallLoc = E->getExprLoc();
4993   if (!Info.CheckCallLimit(CallLoc))
4994     return false;
4995 
4996   const CXXRecordDecl *RD = Definition->getParent();
4997   if (RD->getNumVBases()) {
4998     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4999     return false;
5000   }
5001 
5002   EvalInfo::EvaluatingConstructorRAII EvalObj(
5003       Info,
5004       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5005       RD->getNumBases());
5006   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5007 
5008   // FIXME: Creating an APValue just to hold a nonexistent return value is
5009   // wasteful.
5010   APValue RetVal;
5011   StmtResult Ret = {RetVal, nullptr};
5012 
5013   // If it's a delegating constructor, delegate.
5014   if (Definition->isDelegatingConstructor()) {
5015     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5016     {
5017       FullExpressionRAII InitScope(Info);
5018       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5019         return false;
5020     }
5021     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5022   }
5023 
5024   // For a trivial copy or move constructor, perform an APValue copy. This is
5025   // essential for unions (or classes with anonymous union members), where the
5026   // operations performed by the constructor cannot be represented by
5027   // ctor-initializers.
5028   //
5029   // Skip this for empty non-union classes; we should not perform an
5030   // lvalue-to-rvalue conversion on them because their copy constructor does not
5031   // actually read them.
5032   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5033       (Definition->getParent()->isUnion() ||
5034        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5035     LValue RHS;
5036     RHS.setFrom(Info.Ctx, ArgValues[0]);
5037     return handleLValueToRValueConversion(
5038         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5039         RHS, Result);
5040   }
5041 
5042   // Reserve space for the struct members.
5043   if (!RD->isUnion() && Result.isUninit())
5044     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5045                      std::distance(RD->field_begin(), RD->field_end()));
5046 
5047   if (RD->isInvalidDecl()) return false;
5048   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5049 
5050   // A scope for temporaries lifetime-extended by reference members.
5051   BlockScopeRAII LifetimeExtendedScope(Info);
5052 
5053   bool Success = true;
5054   unsigned BasesSeen = 0;
5055 #ifndef NDEBUG
5056   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5057 #endif
5058   for (const auto *I : Definition->inits()) {
5059     LValue Subobject = This;
5060     LValue SubobjectParent = This;
5061     APValue *Value = &Result;
5062 
5063     // Determine the subobject to initialize.
5064     FieldDecl *FD = nullptr;
5065     if (I->isBaseInitializer()) {
5066       QualType BaseType(I->getBaseClass(), 0);
5067 #ifndef NDEBUG
5068       // Non-virtual base classes are initialized in the order in the class
5069       // definition. We have already checked for virtual base classes.
5070       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5071       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5072              "base class initializers not in expected order");
5073       ++BaseIt;
5074 #endif
5075       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5076                                   BaseType->getAsCXXRecordDecl(), &Layout))
5077         return false;
5078       Value = &Result.getStructBase(BasesSeen++);
5079     } else if ((FD = I->getMember())) {
5080       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5081         return false;
5082       if (RD->isUnion()) {
5083         Result = APValue(FD);
5084         Value = &Result.getUnionValue();
5085       } else {
5086         Value = &Result.getStructField(FD->getFieldIndex());
5087       }
5088     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5089       // Walk the indirect field decl's chain to find the object to initialize,
5090       // and make sure we've initialized every step along it.
5091       auto IndirectFieldChain = IFD->chain();
5092       for (auto *C : IndirectFieldChain) {
5093         FD = cast<FieldDecl>(C);
5094         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5095         // Switch the union field if it differs. This happens if we had
5096         // preceding zero-initialization, and we're now initializing a union
5097         // subobject other than the first.
5098         // FIXME: In this case, the values of the other subobjects are
5099         // specified, since zero-initialization sets all padding bits to zero.
5100         if (Value->isUninit() ||
5101             (Value->isUnion() && Value->getUnionField() != FD)) {
5102           if (CD->isUnion())
5103             *Value = APValue(FD);
5104           else
5105             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
5106                              std::distance(CD->field_begin(), CD->field_end()));
5107         }
5108         // Store Subobject as its parent before updating it for the last element
5109         // in the chain.
5110         if (C == IndirectFieldChain.back())
5111           SubobjectParent = Subobject;
5112         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5113           return false;
5114         if (CD->isUnion())
5115           Value = &Value->getUnionValue();
5116         else
5117           Value = &Value->getStructField(FD->getFieldIndex());
5118       }
5119     } else {
5120       llvm_unreachable("unknown base initializer kind");
5121     }
5122 
5123     // Need to override This for implicit field initializers as in this case
5124     // This refers to innermost anonymous struct/union containing initializer,
5125     // not to currently constructed class.
5126     const Expr *Init = I->getInit();
5127     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5128                                   isa<CXXDefaultInitExpr>(Init));
5129     FullExpressionRAII InitScope(Info);
5130     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5131         (FD && FD->isBitField() &&
5132          !truncateBitfieldValue(Info, Init, *Value, FD))) {
5133       // If we're checking for a potential constant expression, evaluate all
5134       // initializers even if some of them fail.
5135       if (!Info.noteFailure())
5136         return false;
5137       Success = false;
5138     }
5139 
5140     // This is the point at which the dynamic type of the object becomes this
5141     // class type.
5142     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5143       EvalObj.finishedConstructingBases();
5144   }
5145 
5146   return Success &&
5147          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5148 }
5149 
5150 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5151                                   ArrayRef<const Expr*> Args,
5152                                   const CXXConstructorDecl *Definition,
5153                                   EvalInfo &Info, APValue &Result) {
5154   ArgVector ArgValues(Args.size());
5155   if (!EvaluateArgs(Args, ArgValues, Info))
5156     return false;
5157 
5158   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5159                                Info, Result);
5160 }
5161 
5162 //===----------------------------------------------------------------------===//
5163 // Generic Evaluation
5164 //===----------------------------------------------------------------------===//
5165 namespace {
5166 
5167 template <class Derived>
5168 class ExprEvaluatorBase
5169   : public ConstStmtVisitor<Derived, bool> {
5170 private:
5171   Derived &getDerived() { return static_cast<Derived&>(*this); }
5172   bool DerivedSuccess(const APValue &V, const Expr *E) {
5173     return getDerived().Success(V, E);
5174   }
5175   bool DerivedZeroInitialization(const Expr *E) {
5176     return getDerived().ZeroInitialization(E);
5177   }
5178 
5179   // Check whether a conditional operator with a non-constant condition is a
5180   // potential constant expression. If neither arm is a potential constant
5181   // expression, then the conditional operator is not either.
5182   template<typename ConditionalOperator>
5183   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
5184     assert(Info.checkingPotentialConstantExpression());
5185 
5186     // Speculatively evaluate both arms.
5187     SmallVector<PartialDiagnosticAt, 8> Diag;
5188     {
5189       SpeculativeEvaluationRAII Speculate(Info, &Diag);
5190       StmtVisitorTy::Visit(E->getFalseExpr());
5191       if (Diag.empty())
5192         return;
5193     }
5194 
5195     {
5196       SpeculativeEvaluationRAII Speculate(Info, &Diag);
5197       Diag.clear();
5198       StmtVisitorTy::Visit(E->getTrueExpr());
5199       if (Diag.empty())
5200         return;
5201     }
5202 
5203     Error(E, diag::note_constexpr_conditional_never_const);
5204   }
5205 
5206 
5207   template<typename ConditionalOperator>
5208   bool HandleConditionalOperator(const ConditionalOperator *E) {
5209     bool BoolResult;
5210     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
5211       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
5212         CheckPotentialConstantConditional(E);
5213         return false;
5214       }
5215       if (Info.noteFailure()) {
5216         StmtVisitorTy::Visit(E->getTrueExpr());
5217         StmtVisitorTy::Visit(E->getFalseExpr());
5218       }
5219       return false;
5220     }
5221 
5222     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5223     return StmtVisitorTy::Visit(EvalExpr);
5224   }
5225 
5226 protected:
5227   EvalInfo &Info;
5228   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
5229   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5230 
5231   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5232     return Info.CCEDiag(E, D);
5233   }
5234 
5235   bool ZeroInitialization(const Expr *E) { return Error(E); }
5236 
5237 public:
5238   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5239 
5240   EvalInfo &getEvalInfo() { return Info; }
5241 
5242   /// Report an evaluation error. This should only be called when an error is
5243   /// first discovered. When propagating an error, just return false.
5244   bool Error(const Expr *E, diag::kind D) {
5245     Info.FFDiag(E, D);
5246     return false;
5247   }
5248   bool Error(const Expr *E) {
5249     return Error(E, diag::note_invalid_subexpr_in_const_expr);
5250   }
5251 
5252   bool VisitStmt(const Stmt *) {
5253     llvm_unreachable("Expression evaluator should not be called on stmts");
5254   }
5255   bool VisitExpr(const Expr *E) {
5256     return Error(E);
5257   }
5258 
5259   bool VisitConstantExpr(const ConstantExpr *E)
5260     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5261   bool VisitParenExpr(const ParenExpr *E)
5262     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5263   bool VisitUnaryExtension(const UnaryOperator *E)
5264     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5265   bool VisitUnaryPlus(const UnaryOperator *E)
5266     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5267   bool VisitChooseExpr(const ChooseExpr *E)
5268     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
5269   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
5270     { return StmtVisitorTy::Visit(E->getResultExpr()); }
5271   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
5272     { return StmtVisitorTy::Visit(E->getReplacement()); }
5273   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5274     TempVersionRAII RAII(*Info.CurrentCall);
5275     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5276     return StmtVisitorTy::Visit(E->getExpr());
5277   }
5278   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
5279     TempVersionRAII RAII(*Info.CurrentCall);
5280     // The initializer may not have been parsed yet, or might be erroneous.
5281     if (!E->getExpr())
5282       return Error(E);
5283     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5284     return StmtVisitorTy::Visit(E->getExpr());
5285   }
5286 
5287   // We cannot create any objects for which cleanups are required, so there is
5288   // nothing to do here; all cleanups must come from unevaluated subexpressions.
5289   bool VisitExprWithCleanups(const ExprWithCleanups *E)
5290     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5291 
5292   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
5293     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5294     return static_cast<Derived*>(this)->VisitCastExpr(E);
5295   }
5296   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
5297     if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5298       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
5299     return static_cast<Derived*>(this)->VisitCastExpr(E);
5300   }
5301 
5302   bool VisitBinaryOperator(const BinaryOperator *E) {
5303     switch (E->getOpcode()) {
5304     default:
5305       return Error(E);
5306 
5307     case BO_Comma:
5308       VisitIgnoredValue(E->getLHS());
5309       return StmtVisitorTy::Visit(E->getRHS());
5310 
5311     case BO_PtrMemD:
5312     case BO_PtrMemI: {
5313       LValue Obj;
5314       if (!HandleMemberPointerAccess(Info, E, Obj))
5315         return false;
5316       APValue Result;
5317       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
5318         return false;
5319       return DerivedSuccess(Result, E);
5320     }
5321     }
5322   }
5323 
5324   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
5325     // Evaluate and cache the common expression. We treat it as a temporary,
5326     // even though it's not quite the same thing.
5327     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
5328                   Info, E->getCommon()))
5329       return false;
5330 
5331     return HandleConditionalOperator(E);
5332   }
5333 
5334   bool VisitConditionalOperator(const ConditionalOperator *E) {
5335     bool IsBcpCall = false;
5336     // If the condition (ignoring parens) is a __builtin_constant_p call,
5337     // the result is a constant expression if it can be folded without
5338     // side-effects. This is an important GNU extension. See GCC PR38377
5339     // for discussion.
5340     if (const CallExpr *CallCE =
5341           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
5342       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
5343         IsBcpCall = true;
5344 
5345     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
5346     // constant expression; we can't check whether it's potentially foldable.
5347     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
5348       return false;
5349 
5350     FoldConstant Fold(Info, IsBcpCall);
5351     if (!HandleConditionalOperator(E)) {
5352       Fold.keepDiagnostics();
5353       return false;
5354     }
5355 
5356     return true;
5357   }
5358 
5359   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
5360     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
5361       return DerivedSuccess(*Value, E);
5362 
5363     const Expr *Source = E->getSourceExpr();
5364     if (!Source)
5365       return Error(E);
5366     if (Source == E) { // sanity checking.
5367       assert(0 && "OpaqueValueExpr recursively refers to itself");
5368       return Error(E);
5369     }
5370     return StmtVisitorTy::Visit(Source);
5371   }
5372 
5373   bool VisitCallExpr(const CallExpr *E) {
5374     APValue Result;
5375     if (!handleCallExpr(E, Result, nullptr))
5376       return false;
5377     return DerivedSuccess(Result, E);
5378   }
5379 
5380   bool handleCallExpr(const CallExpr *E, APValue &Result,
5381                      const LValue *ResultSlot) {
5382     const Expr *Callee = E->getCallee()->IgnoreParens();
5383     QualType CalleeType = Callee->getType();
5384 
5385     const FunctionDecl *FD = nullptr;
5386     LValue *This = nullptr, ThisVal;
5387     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5388     bool HasQualifier = false;
5389 
5390     // Extract function decl and 'this' pointer from the callee.
5391     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
5392       const CXXMethodDecl *Member = nullptr;
5393       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
5394         // Explicit bound member calls, such as x.f() or p->g();
5395         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
5396           return false;
5397         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
5398         if (!Member)
5399           return Error(Callee);
5400         This = &ThisVal;
5401         HasQualifier = ME->hasQualifier();
5402       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
5403         // Indirect bound member calls ('.*' or '->*').
5404         Member = dyn_cast_or_null<CXXMethodDecl>(
5405             HandleMemberPointerAccess(Info, BE, ThisVal, false));
5406         if (!Member)
5407           return Error(Callee);
5408         This = &ThisVal;
5409       } else
5410         return Error(Callee);
5411       FD = Member;
5412     } else if (CalleeType->isFunctionPointerType()) {
5413       LValue Call;
5414       if (!EvaluatePointer(Callee, Call, Info))
5415         return false;
5416 
5417       if (!Call.getLValueOffset().isZero())
5418         return Error(Callee);
5419       FD = dyn_cast_or_null<FunctionDecl>(
5420                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
5421       if (!FD)
5422         return Error(Callee);
5423       // Don't call function pointers which have been cast to some other type.
5424       // Per DR (no number yet), the caller and callee can differ in noexcept.
5425       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
5426         CalleeType->getPointeeType(), FD->getType())) {
5427         return Error(E);
5428       }
5429 
5430       // Overloaded operator calls to member functions are represented as normal
5431       // calls with '*this' as the first argument.
5432       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
5433       if (MD && !MD->isStatic()) {
5434         // FIXME: When selecting an implicit conversion for an overloaded
5435         // operator delete, we sometimes try to evaluate calls to conversion
5436         // operators without a 'this' parameter!
5437         if (Args.empty())
5438           return Error(E);
5439 
5440         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
5441           return false;
5442         This = &ThisVal;
5443         Args = Args.slice(1);
5444       } else if (MD && MD->isLambdaStaticInvoker()) {
5445         // Map the static invoker for the lambda back to the call operator.
5446         // Conveniently, we don't have to slice out the 'this' argument (as is
5447         // being done for the non-static case), since a static member function
5448         // doesn't have an implicit argument passed in.
5449         const CXXRecordDecl *ClosureClass = MD->getParent();
5450         assert(
5451             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
5452             "Number of captures must be zero for conversion to function-ptr");
5453 
5454         const CXXMethodDecl *LambdaCallOp =
5455             ClosureClass->getLambdaCallOperator();
5456 
5457         // Set 'FD', the function that will be called below, to the call
5458         // operator.  If the closure object represents a generic lambda, find
5459         // the corresponding specialization of the call operator.
5460 
5461         if (ClosureClass->isGenericLambda()) {
5462           assert(MD->isFunctionTemplateSpecialization() &&
5463                  "A generic lambda's static-invoker function must be a "
5464                  "template specialization");
5465           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
5466           FunctionTemplateDecl *CallOpTemplate =
5467               LambdaCallOp->getDescribedFunctionTemplate();
5468           void *InsertPos = nullptr;
5469           FunctionDecl *CorrespondingCallOpSpecialization =
5470               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
5471           assert(CorrespondingCallOpSpecialization &&
5472                  "We must always have a function call operator specialization "
5473                  "that corresponds to our static invoker specialization");
5474           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
5475         } else
5476           FD = LambdaCallOp;
5477       }
5478     } else
5479       return Error(E);
5480 
5481     SmallVector<QualType, 4> CovariantAdjustmentPath;
5482     if (This) {
5483       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
5484       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
5485         // Perform virtual dispatch, if necessary.
5486         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
5487                                    CovariantAdjustmentPath);
5488         if (!FD)
5489           return false;
5490       } else {
5491         // Check that the 'this' pointer points to an object of the right type.
5492         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
5493           return false;
5494       }
5495     }
5496 
5497     const FunctionDecl *Definition = nullptr;
5498     Stmt *Body = FD->getBody(Definition);
5499 
5500     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5501         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
5502                             Result, ResultSlot))
5503       return false;
5504 
5505     if (!CovariantAdjustmentPath.empty() &&
5506         !HandleCovariantReturnAdjustment(Info, E, Result,
5507                                          CovariantAdjustmentPath))
5508       return false;
5509 
5510     return true;
5511   }
5512 
5513   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5514     return StmtVisitorTy::Visit(E->getInitializer());
5515   }
5516   bool VisitInitListExpr(const InitListExpr *E) {
5517     if (E->getNumInits() == 0)
5518       return DerivedZeroInitialization(E);
5519     if (E->getNumInits() == 1)
5520       return StmtVisitorTy::Visit(E->getInit(0));
5521     return Error(E);
5522   }
5523   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
5524     return DerivedZeroInitialization(E);
5525   }
5526   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
5527     return DerivedZeroInitialization(E);
5528   }
5529   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
5530     return DerivedZeroInitialization(E);
5531   }
5532 
5533   /// A member expression where the object is a prvalue is itself a prvalue.
5534   bool VisitMemberExpr(const MemberExpr *E) {
5535     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
5536            "missing temporary materialization conversion");
5537     assert(!E->isArrow() && "missing call to bound member function?");
5538 
5539     APValue Val;
5540     if (!Evaluate(Val, Info, E->getBase()))
5541       return false;
5542 
5543     QualType BaseTy = E->getBase()->getType();
5544 
5545     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
5546     if (!FD) return Error(E);
5547     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
5548     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5549            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5550 
5551     // Note: there is no lvalue base here. But this case should only ever
5552     // happen in C or in C++98, where we cannot be evaluating a constexpr
5553     // constructor, which is the only case the base matters.
5554     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
5555     SubobjectDesignator Designator(BaseTy);
5556     Designator.addDeclUnchecked(FD);
5557 
5558     APValue Result;
5559     return extractSubobject(Info, E, Obj, Designator, Result) &&
5560            DerivedSuccess(Result, E);
5561   }
5562 
5563   bool VisitCastExpr(const CastExpr *E) {
5564     switch (E->getCastKind()) {
5565     default:
5566       break;
5567 
5568     case CK_AtomicToNonAtomic: {
5569       APValue AtomicVal;
5570       // This does not need to be done in place even for class/array types:
5571       // atomic-to-non-atomic conversion implies copying the object
5572       // representation.
5573       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
5574         return false;
5575       return DerivedSuccess(AtomicVal, E);
5576     }
5577 
5578     case CK_NoOp:
5579     case CK_UserDefinedConversion:
5580       return StmtVisitorTy::Visit(E->getSubExpr());
5581 
5582     case CK_LValueToRValue: {
5583       LValue LVal;
5584       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5585         return false;
5586       APValue RVal;
5587       // Note, we use the subexpression's type in order to retain cv-qualifiers.
5588       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5589                                           LVal, RVal))
5590         return false;
5591       return DerivedSuccess(RVal, E);
5592     }
5593     }
5594 
5595     return Error(E);
5596   }
5597 
5598   bool VisitUnaryPostInc(const UnaryOperator *UO) {
5599     return VisitUnaryPostIncDec(UO);
5600   }
5601   bool VisitUnaryPostDec(const UnaryOperator *UO) {
5602     return VisitUnaryPostIncDec(UO);
5603   }
5604   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
5605     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5606       return Error(UO);
5607 
5608     LValue LVal;
5609     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5610       return false;
5611     APValue RVal;
5612     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5613                       UO->isIncrementOp(), &RVal))
5614       return false;
5615     return DerivedSuccess(RVal, UO);
5616   }
5617 
5618   bool VisitStmtExpr(const StmtExpr *E) {
5619     // We will have checked the full-expressions inside the statement expression
5620     // when they were completed, and don't need to check them again now.
5621     if (Info.checkingForOverflow())
5622       return Error(E);
5623 
5624     BlockScopeRAII Scope(Info);
5625     const CompoundStmt *CS = E->getSubStmt();
5626     if (CS->body_empty())
5627       return true;
5628 
5629     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5630                                            BE = CS->body_end();
5631          /**/; ++BI) {
5632       if (BI + 1 == BE) {
5633         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5634         if (!FinalExpr) {
5635           Info.FFDiag((*BI)->getBeginLoc(),
5636                       diag::note_constexpr_stmt_expr_unsupported);
5637           return false;
5638         }
5639         return this->Visit(FinalExpr);
5640       }
5641 
5642       APValue ReturnValue;
5643       StmtResult Result = { ReturnValue, nullptr };
5644       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5645       if (ESR != ESR_Succeeded) {
5646         // FIXME: If the statement-expression terminated due to 'return',
5647         // 'break', or 'continue', it would be nice to propagate that to
5648         // the outer statement evaluation rather than bailing out.
5649         if (ESR != ESR_Failed)
5650           Info.FFDiag((*BI)->getBeginLoc(),
5651                       diag::note_constexpr_stmt_expr_unsupported);
5652         return false;
5653       }
5654     }
5655 
5656     llvm_unreachable("Return from function from the loop above.");
5657   }
5658 
5659   /// Visit a value which is evaluated, but whose value is ignored.
5660   void VisitIgnoredValue(const Expr *E) {
5661     EvaluateIgnoredValue(Info, E);
5662   }
5663 
5664   /// Potentially visit a MemberExpr's base expression.
5665   void VisitIgnoredBaseExpression(const Expr *E) {
5666     // While MSVC doesn't evaluate the base expression, it does diagnose the
5667     // presence of side-effecting behavior.
5668     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5669       return;
5670     VisitIgnoredValue(E);
5671   }
5672 };
5673 
5674 } // namespace
5675 
5676 //===----------------------------------------------------------------------===//
5677 // Common base class for lvalue and temporary evaluation.
5678 //===----------------------------------------------------------------------===//
5679 namespace {
5680 template<class Derived>
5681 class LValueExprEvaluatorBase
5682   : public ExprEvaluatorBase<Derived> {
5683 protected:
5684   LValue &Result;
5685   bool InvalidBaseOK;
5686   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5687   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5688 
5689   bool Success(APValue::LValueBase B) {
5690     Result.set(B);
5691     return true;
5692   }
5693 
5694   bool evaluatePointer(const Expr *E, LValue &Result) {
5695     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5696   }
5697 
5698 public:
5699   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5700       : ExprEvaluatorBaseTy(Info), Result(Result),
5701         InvalidBaseOK(InvalidBaseOK) {}
5702 
5703   bool Success(const APValue &V, const Expr *E) {
5704     Result.setFrom(this->Info.Ctx, V);
5705     return true;
5706   }
5707 
5708   bool VisitMemberExpr(const MemberExpr *E) {
5709     // Handle non-static data members.
5710     QualType BaseTy;
5711     bool EvalOK;
5712     if (E->isArrow()) {
5713       EvalOK = evaluatePointer(E->getBase(), Result);
5714       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5715     } else if (E->getBase()->isRValue()) {
5716       assert(E->getBase()->getType()->isRecordType());
5717       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5718       BaseTy = E->getBase()->getType();
5719     } else {
5720       EvalOK = this->Visit(E->getBase());
5721       BaseTy = E->getBase()->getType();
5722     }
5723     if (!EvalOK) {
5724       if (!InvalidBaseOK)
5725         return false;
5726       Result.setInvalid(E);
5727       return true;
5728     }
5729 
5730     const ValueDecl *MD = E->getMemberDecl();
5731     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5732       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5733              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5734       (void)BaseTy;
5735       if (!HandleLValueMember(this->Info, E, Result, FD))
5736         return false;
5737     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5738       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5739         return false;
5740     } else
5741       return this->Error(E);
5742 
5743     if (MD->getType()->isReferenceType()) {
5744       APValue RefValue;
5745       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5746                                           RefValue))
5747         return false;
5748       return Success(RefValue, E);
5749     }
5750     return true;
5751   }
5752 
5753   bool VisitBinaryOperator(const BinaryOperator *E) {
5754     switch (E->getOpcode()) {
5755     default:
5756       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5757 
5758     case BO_PtrMemD:
5759     case BO_PtrMemI:
5760       return HandleMemberPointerAccess(this->Info, E, Result);
5761     }
5762   }
5763 
5764   bool VisitCastExpr(const CastExpr *E) {
5765     switch (E->getCastKind()) {
5766     default:
5767       return ExprEvaluatorBaseTy::VisitCastExpr(E);
5768 
5769     case CK_DerivedToBase:
5770     case CK_UncheckedDerivedToBase:
5771       if (!this->Visit(E->getSubExpr()))
5772         return false;
5773 
5774       // Now figure out the necessary offset to add to the base LV to get from
5775       // the derived class to the base class.
5776       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5777                                   Result);
5778     }
5779   }
5780 };
5781 }
5782 
5783 //===----------------------------------------------------------------------===//
5784 // LValue Evaluation
5785 //
5786 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5787 // function designators (in C), decl references to void objects (in C), and
5788 // temporaries (if building with -Wno-address-of-temporary).
5789 //
5790 // LValue evaluation produces values comprising a base expression of one of the
5791 // following types:
5792 // - Declarations
5793 //  * VarDecl
5794 //  * FunctionDecl
5795 // - Literals
5796 //  * CompoundLiteralExpr in C (and in global scope in C++)
5797 //  * StringLiteral
5798 //  * PredefinedExpr
5799 //  * ObjCStringLiteralExpr
5800 //  * ObjCEncodeExpr
5801 //  * AddrLabelExpr
5802 //  * BlockExpr
5803 //  * CallExpr for a MakeStringConstant builtin
5804 // - typeid(T) expressions, as TypeInfoLValues
5805 // - Locals and temporaries
5806 //  * MaterializeTemporaryExpr
5807 //  * Any Expr, with a CallIndex indicating the function in which the temporary
5808 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
5809 //    from the AST (FIXME).
5810 //  * A MaterializeTemporaryExpr that has static storage duration, with no
5811 //    CallIndex, for a lifetime-extended temporary.
5812 // plus an offset in bytes.
5813 //===----------------------------------------------------------------------===//
5814 namespace {
5815 class LValueExprEvaluator
5816   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5817 public:
5818   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5819     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5820 
5821   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5822   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5823 
5824   bool VisitDeclRefExpr(const DeclRefExpr *E);
5825   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5826   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5827   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5828   bool VisitMemberExpr(const MemberExpr *E);
5829   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5830   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5831   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5832   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5833   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5834   bool VisitUnaryDeref(const UnaryOperator *E);
5835   bool VisitUnaryReal(const UnaryOperator *E);
5836   bool VisitUnaryImag(const UnaryOperator *E);
5837   bool VisitUnaryPreInc(const UnaryOperator *UO) {
5838     return VisitUnaryPreIncDec(UO);
5839   }
5840   bool VisitUnaryPreDec(const UnaryOperator *UO) {
5841     return VisitUnaryPreIncDec(UO);
5842   }
5843   bool VisitBinAssign(const BinaryOperator *BO);
5844   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5845 
5846   bool VisitCastExpr(const CastExpr *E) {
5847     switch (E->getCastKind()) {
5848     default:
5849       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5850 
5851     case CK_LValueBitCast:
5852       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5853       if (!Visit(E->getSubExpr()))
5854         return false;
5855       Result.Designator.setInvalid();
5856       return true;
5857 
5858     case CK_BaseToDerived:
5859       if (!Visit(E->getSubExpr()))
5860         return false;
5861       return HandleBaseToDerivedCast(Info, E, Result);
5862 
5863     case CK_Dynamic:
5864       if (!Visit(E->getSubExpr()))
5865         return false;
5866       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
5867     }
5868   }
5869 };
5870 } // end anonymous namespace
5871 
5872 /// Evaluate an expression as an lvalue. This can be legitimately called on
5873 /// expressions which are not glvalues, in three cases:
5874 ///  * function designators in C, and
5875 ///  * "extern void" objects
5876 ///  * @selector() expressions in Objective-C
5877 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5878                            bool InvalidBaseOK) {
5879   assert(E->isGLValue() || E->getType()->isFunctionType() ||
5880          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5881   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5882 }
5883 
5884 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5885   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5886     return Success(FD);
5887   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5888     return VisitVarDecl(E, VD);
5889   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5890     return Visit(BD->getBinding());
5891   return Error(E);
5892 }
5893 
5894 
5895 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5896 
5897   // If we are within a lambda's call operator, check whether the 'VD' referred
5898   // to within 'E' actually represents a lambda-capture that maps to a
5899   // data-member/field within the closure object, and if so, evaluate to the
5900   // field or what the field refers to.
5901   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5902       isa<DeclRefExpr>(E) &&
5903       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5904     // We don't always have a complete capture-map when checking or inferring if
5905     // the function call operator meets the requirements of a constexpr function
5906     // - but we don't need to evaluate the captures to determine constexprness
5907     // (dcl.constexpr C++17).
5908     if (Info.checkingPotentialConstantExpression())
5909       return false;
5910 
5911     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5912       // Start with 'Result' referring to the complete closure object...
5913       Result = *Info.CurrentCall->This;
5914       // ... then update it to refer to the field of the closure object
5915       // that represents the capture.
5916       if (!HandleLValueMember(Info, E, Result, FD))
5917         return false;
5918       // And if the field is of reference type, update 'Result' to refer to what
5919       // the field refers to.
5920       if (FD->getType()->isReferenceType()) {
5921         APValue RVal;
5922         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5923                                             RVal))
5924           return false;
5925         Result.setFrom(Info.Ctx, RVal);
5926       }
5927       return true;
5928     }
5929   }
5930   CallStackFrame *Frame = nullptr;
5931   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5932     // Only if a local variable was declared in the function currently being
5933     // evaluated, do we expect to be able to find its value in the current
5934     // frame. (Otherwise it was likely declared in an enclosing context and
5935     // could either have a valid evaluatable value (for e.g. a constexpr
5936     // variable) or be ill-formed (and trigger an appropriate evaluation
5937     // diagnostic)).
5938     if (Info.CurrentCall->Callee &&
5939         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5940       Frame = Info.CurrentCall;
5941     }
5942   }
5943 
5944   if (!VD->getType()->isReferenceType()) {
5945     if (Frame) {
5946       Result.set({VD, Frame->Index,
5947                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
5948       return true;
5949     }
5950     return Success(VD);
5951   }
5952 
5953   APValue *V;
5954   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
5955     return false;
5956   if (V->isUninit()) {
5957     if (!Info.checkingPotentialConstantExpression())
5958       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5959     return false;
5960   }
5961   return Success(*V, E);
5962 }
5963 
5964 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5965     const MaterializeTemporaryExpr *E) {
5966   // Walk through the expression to find the materialized temporary itself.
5967   SmallVector<const Expr *, 2> CommaLHSs;
5968   SmallVector<SubobjectAdjustment, 2> Adjustments;
5969   const Expr *Inner = E->GetTemporaryExpr()->
5970       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5971 
5972   // If we passed any comma operators, evaluate their LHSs.
5973   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5974     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5975       return false;
5976 
5977   // A materialized temporary with static storage duration can appear within the
5978   // result of a constant expression evaluation, so we need to preserve its
5979   // value for use outside this evaluation.
5980   APValue *Value;
5981   if (E->getStorageDuration() == SD_Static) {
5982     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5983     *Value = APValue();
5984     Result.set(E);
5985   } else {
5986     Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5987                              *Info.CurrentCall);
5988   }
5989 
5990   QualType Type = Inner->getType();
5991 
5992   // Materialize the temporary itself.
5993   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5994       (E->getStorageDuration() == SD_Static &&
5995        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5996     *Value = APValue();
5997     return false;
5998   }
5999 
6000   // Adjust our lvalue to refer to the desired subobject.
6001   for (unsigned I = Adjustments.size(); I != 0; /**/) {
6002     --I;
6003     switch (Adjustments[I].Kind) {
6004     case SubobjectAdjustment::DerivedToBaseAdjustment:
6005       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6006                                 Type, Result))
6007         return false;
6008       Type = Adjustments[I].DerivedToBase.BasePath->getType();
6009       break;
6010 
6011     case SubobjectAdjustment::FieldAdjustment:
6012       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6013         return false;
6014       Type = Adjustments[I].Field->getType();
6015       break;
6016 
6017     case SubobjectAdjustment::MemberPointerAdjustment:
6018       if (!HandleMemberPointerAccess(this->Info, Type, Result,
6019                                      Adjustments[I].Ptr.RHS))
6020         return false;
6021       Type = Adjustments[I].Ptr.MPT->getPointeeType();
6022       break;
6023     }
6024   }
6025 
6026   return true;
6027 }
6028 
6029 bool
6030 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6031   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6032          "lvalue compound literal in c++?");
6033   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6034   // only see this when folding in C, so there's no standard to follow here.
6035   return Success(E);
6036 }
6037 
6038 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
6039   TypeInfoLValue TypeInfo;
6040 
6041   if (!E->isPotentiallyEvaluated()) {
6042     if (E->isTypeOperand())
6043       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6044     else
6045       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
6046   } else {
6047     if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6048       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6049         << E->getExprOperand()->getType()
6050         << E->getExprOperand()->getSourceRange();
6051     }
6052 
6053     if (!Visit(E->getExprOperand()))
6054       return false;
6055 
6056     Optional<DynamicType> DynType =
6057         ComputeDynamicType(Info, E, Result, AK_TypeId);
6058     if (!DynType)
6059       return false;
6060 
6061     TypeInfo =
6062         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
6063   }
6064 
6065   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
6066 }
6067 
6068 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6069   return Success(E);
6070 }
6071 
6072 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
6073   // Handle static data members.
6074   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
6075     VisitIgnoredBaseExpression(E->getBase());
6076     return VisitVarDecl(E, VD);
6077   }
6078 
6079   // Handle static member functions.
6080   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6081     if (MD->isStatic()) {
6082       VisitIgnoredBaseExpression(E->getBase());
6083       return Success(MD);
6084     }
6085   }
6086 
6087   // Handle non-static data members.
6088   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
6089 }
6090 
6091 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
6092   // FIXME: Deal with vectors as array subscript bases.
6093   if (E->getBase()->getType()->isVectorType())
6094     return Error(E);
6095 
6096   bool Success = true;
6097   if (!evaluatePointer(E->getBase(), Result)) {
6098     if (!Info.noteFailure())
6099       return false;
6100     Success = false;
6101   }
6102 
6103   APSInt Index;
6104   if (!EvaluateInteger(E->getIdx(), Index, Info))
6105     return false;
6106 
6107   return Success &&
6108          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
6109 }
6110 
6111 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
6112   return evaluatePointer(E->getSubExpr(), Result);
6113 }
6114 
6115 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6116   if (!Visit(E->getSubExpr()))
6117     return false;
6118   // __real is a no-op on scalar lvalues.
6119   if (E->getSubExpr()->getType()->isAnyComplexType())
6120     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6121   return true;
6122 }
6123 
6124 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6125   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6126          "lvalue __imag__ on scalar?");
6127   if (!Visit(E->getSubExpr()))
6128     return false;
6129   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6130   return true;
6131 }
6132 
6133 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
6134   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6135     return Error(UO);
6136 
6137   if (!this->Visit(UO->getSubExpr()))
6138     return false;
6139 
6140   return handleIncDec(
6141       this->Info, UO, Result, UO->getSubExpr()->getType(),
6142       UO->isIncrementOp(), nullptr);
6143 }
6144 
6145 bool LValueExprEvaluator::VisitCompoundAssignOperator(
6146     const CompoundAssignOperator *CAO) {
6147   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6148     return Error(CAO);
6149 
6150   APValue RHS;
6151 
6152   // The overall lvalue result is the result of evaluating the LHS.
6153   if (!this->Visit(CAO->getLHS())) {
6154     if (Info.noteFailure())
6155       Evaluate(RHS, this->Info, CAO->getRHS());
6156     return false;
6157   }
6158 
6159   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6160     return false;
6161 
6162   return handleCompoundAssignment(
6163       this->Info, CAO,
6164       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6165       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
6166 }
6167 
6168 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
6169   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6170     return Error(E);
6171 
6172   APValue NewVal;
6173 
6174   if (!this->Visit(E->getLHS())) {
6175     if (Info.noteFailure())
6176       Evaluate(NewVal, this->Info, E->getRHS());
6177     return false;
6178   }
6179 
6180   if (!Evaluate(NewVal, this->Info, E->getRHS()))
6181     return false;
6182 
6183   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
6184                           NewVal);
6185 }
6186 
6187 //===----------------------------------------------------------------------===//
6188 // Pointer Evaluation
6189 //===----------------------------------------------------------------------===//
6190 
6191 /// Attempts to compute the number of bytes available at the pointer
6192 /// returned by a function with the alloc_size attribute. Returns true if we
6193 /// were successful. Places an unsigned number into `Result`.
6194 ///
6195 /// This expects the given CallExpr to be a call to a function with an
6196 /// alloc_size attribute.
6197 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6198                                             const CallExpr *Call,
6199                                             llvm::APInt &Result) {
6200   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6201 
6202   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6203   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
6204   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6205   if (Call->getNumArgs() <= SizeArgNo)
6206     return false;
6207 
6208   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
6209     Expr::EvalResult ExprResult;
6210     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
6211       return false;
6212     Into = ExprResult.Val.getInt();
6213     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6214       return false;
6215     Into = Into.zextOrSelf(BitsInSizeT);
6216     return true;
6217   };
6218 
6219   APSInt SizeOfElem;
6220   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6221     return false;
6222 
6223   if (!AllocSize->getNumElemsParam().isValid()) {
6224     Result = std::move(SizeOfElem);
6225     return true;
6226   }
6227 
6228   APSInt NumberOfElems;
6229   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
6230   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6231     return false;
6232 
6233   bool Overflow;
6234   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6235   if (Overflow)
6236     return false;
6237 
6238   Result = std::move(BytesAvailable);
6239   return true;
6240 }
6241 
6242 /// Convenience function. LVal's base must be a call to an alloc_size
6243 /// function.
6244 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6245                                             const LValue &LVal,
6246                                             llvm::APInt &Result) {
6247   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6248          "Can't get the size of a non alloc_size function");
6249   const auto *Base = LVal.getLValueBase().get<const Expr *>();
6250   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6251   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6252 }
6253 
6254 /// Attempts to evaluate the given LValueBase as the result of a call to
6255 /// a function with the alloc_size attribute. If it was possible to do so, this
6256 /// function will return true, make Result's Base point to said function call,
6257 /// and mark Result's Base as invalid.
6258 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6259                                       LValue &Result) {
6260   if (Base.isNull())
6261     return false;
6262 
6263   // Because we do no form of static analysis, we only support const variables.
6264   //
6265   // Additionally, we can't support parameters, nor can we support static
6266   // variables (in the latter case, use-before-assign isn't UB; in the former,
6267   // we have no clue what they'll be assigned to).
6268   const auto *VD =
6269       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6270   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6271     return false;
6272 
6273   const Expr *Init = VD->getAnyInitializer();
6274   if (!Init)
6275     return false;
6276 
6277   const Expr *E = Init->IgnoreParens();
6278   if (!tryUnwrapAllocSizeCall(E))
6279     return false;
6280 
6281   // Store E instead of E unwrapped so that the type of the LValue's base is
6282   // what the user wanted.
6283   Result.setInvalid(E);
6284 
6285   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
6286   Result.addUnsizedArray(Info, E, Pointee);
6287   return true;
6288 }
6289 
6290 namespace {
6291 class PointerExprEvaluator
6292   : public ExprEvaluatorBase<PointerExprEvaluator> {
6293   LValue &Result;
6294   bool InvalidBaseOK;
6295 
6296   bool Success(const Expr *E) {
6297     Result.set(E);
6298     return true;
6299   }
6300 
6301   bool evaluateLValue(const Expr *E, LValue &Result) {
6302     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
6303   }
6304 
6305   bool evaluatePointer(const Expr *E, LValue &Result) {
6306     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
6307   }
6308 
6309   bool visitNonBuiltinCallExpr(const CallExpr *E);
6310 public:
6311 
6312   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
6313       : ExprEvaluatorBaseTy(info), Result(Result),
6314         InvalidBaseOK(InvalidBaseOK) {}
6315 
6316   bool Success(const APValue &V, const Expr *E) {
6317     Result.setFrom(Info.Ctx, V);
6318     return true;
6319   }
6320   bool ZeroInitialization(const Expr *E) {
6321     auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
6322     Result.setNull(E->getType(), TargetVal);
6323     return true;
6324   }
6325 
6326   bool VisitBinaryOperator(const BinaryOperator *E);
6327   bool VisitCastExpr(const CastExpr* E);
6328   bool VisitUnaryAddrOf(const UnaryOperator *E);
6329   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
6330       { return Success(E); }
6331   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
6332     if (E->isExpressibleAsConstantInitializer())
6333       return Success(E);
6334     if (Info.noteFailure())
6335       EvaluateIgnoredValue(Info, E->getSubExpr());
6336     return Error(E);
6337   }
6338   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
6339       { return Success(E); }
6340   bool VisitCallExpr(const CallExpr *E);
6341   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6342   bool VisitBlockExpr(const BlockExpr *E) {
6343     if (!E->getBlockDecl()->hasCaptures())
6344       return Success(E);
6345     return Error(E);
6346   }
6347   bool VisitCXXThisExpr(const CXXThisExpr *E) {
6348     // Can't look at 'this' when checking a potential constant expression.
6349     if (Info.checkingPotentialConstantExpression())
6350       return false;
6351     if (!Info.CurrentCall->This) {
6352       if (Info.getLangOpts().CPlusPlus11)
6353         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
6354       else
6355         Info.FFDiag(E);
6356       return false;
6357     }
6358     Result = *Info.CurrentCall->This;
6359     // If we are inside a lambda's call operator, the 'this' expression refers
6360     // to the enclosing '*this' object (either by value or reference) which is
6361     // either copied into the closure object's field that represents the '*this'
6362     // or refers to '*this'.
6363     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
6364       // Update 'Result' to refer to the data member/field of the closure object
6365       // that represents the '*this' capture.
6366       if (!HandleLValueMember(Info, E, Result,
6367                              Info.CurrentCall->LambdaThisCaptureField))
6368         return false;
6369       // If we captured '*this' by reference, replace the field with its referent.
6370       if (Info.CurrentCall->LambdaThisCaptureField->getType()
6371               ->isPointerType()) {
6372         APValue RVal;
6373         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
6374                                             RVal))
6375           return false;
6376 
6377         Result.setFrom(Info.Ctx, RVal);
6378       }
6379     }
6380     return true;
6381   }
6382 
6383   bool VisitSourceLocExpr(const SourceLocExpr *E) {
6384     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
6385     APValue LValResult = E->EvaluateInContext(
6386         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
6387     Result.setFrom(Info.Ctx, LValResult);
6388     return true;
6389   }
6390 
6391   // FIXME: Missing: @protocol, @selector
6392 };
6393 } // end anonymous namespace
6394 
6395 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
6396                             bool InvalidBaseOK) {
6397   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6398   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
6399 }
6400 
6401 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6402   if (E->getOpcode() != BO_Add &&
6403       E->getOpcode() != BO_Sub)
6404     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6405 
6406   const Expr *PExp = E->getLHS();
6407   const Expr *IExp = E->getRHS();
6408   if (IExp->getType()->isPointerType())
6409     std::swap(PExp, IExp);
6410 
6411   bool EvalPtrOK = evaluatePointer(PExp, Result);
6412   if (!EvalPtrOK && !Info.noteFailure())
6413     return false;
6414 
6415   llvm::APSInt Offset;
6416   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
6417     return false;
6418 
6419   if (E->getOpcode() == BO_Sub)
6420     negateAsSigned(Offset);
6421 
6422   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
6423   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
6424 }
6425 
6426 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6427   return evaluateLValue(E->getSubExpr(), Result);
6428 }
6429 
6430 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6431   const Expr *SubExpr = E->getSubExpr();
6432 
6433   switch (E->getCastKind()) {
6434   default:
6435     break;
6436 
6437   case CK_BitCast:
6438   case CK_CPointerToObjCPointerCast:
6439   case CK_BlockPointerToObjCPointerCast:
6440   case CK_AnyPointerToBlockPointerCast:
6441   case CK_AddressSpaceConversion:
6442     if (!Visit(SubExpr))
6443       return false;
6444     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
6445     // permitted in constant expressions in C++11. Bitcasts from cv void* are
6446     // also static_casts, but we disallow them as a resolution to DR1312.
6447     if (!E->getType()->isVoidPointerType()) {
6448       Result.Designator.setInvalid();
6449       if (SubExpr->getType()->isVoidPointerType())
6450         CCEDiag(E, diag::note_constexpr_invalid_cast)
6451           << 3 << SubExpr->getType();
6452       else
6453         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6454     }
6455     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
6456       ZeroInitialization(E);
6457     return true;
6458 
6459   case CK_DerivedToBase:
6460   case CK_UncheckedDerivedToBase:
6461     if (!evaluatePointer(E->getSubExpr(), Result))
6462       return false;
6463     if (!Result.Base && Result.Offset.isZero())
6464       return true;
6465 
6466     // Now figure out the necessary offset to add to the base LV to get from
6467     // the derived class to the base class.
6468     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
6469                                   castAs<PointerType>()->getPointeeType(),
6470                                 Result);
6471 
6472   case CK_BaseToDerived:
6473     if (!Visit(E->getSubExpr()))
6474       return false;
6475     if (!Result.Base && Result.Offset.isZero())
6476       return true;
6477     return HandleBaseToDerivedCast(Info, E, Result);
6478 
6479   case CK_Dynamic:
6480     if (!Visit(E->getSubExpr()))
6481       return false;
6482     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6483 
6484   case CK_NullToPointer:
6485     VisitIgnoredValue(E->getSubExpr());
6486     return ZeroInitialization(E);
6487 
6488   case CK_IntegralToPointer: {
6489     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6490 
6491     APValue Value;
6492     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
6493       break;
6494 
6495     if (Value.isInt()) {
6496       unsigned Size = Info.Ctx.getTypeSize(E->getType());
6497       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
6498       Result.Base = (Expr*)nullptr;
6499       Result.InvalidBase = false;
6500       Result.Offset = CharUnits::fromQuantity(N);
6501       Result.Designator.setInvalid();
6502       Result.IsNullPtr = false;
6503       return true;
6504     } else {
6505       // Cast is of an lvalue, no need to change value.
6506       Result.setFrom(Info.Ctx, Value);
6507       return true;
6508     }
6509   }
6510 
6511   case CK_ArrayToPointerDecay: {
6512     if (SubExpr->isGLValue()) {
6513       if (!evaluateLValue(SubExpr, Result))
6514         return false;
6515     } else {
6516       APValue &Value = createTemporary(SubExpr, false, Result,
6517                                        *Info.CurrentCall);
6518       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
6519         return false;
6520     }
6521     // The result is a pointer to the first element of the array.
6522     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
6523     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
6524       Result.addArray(Info, E, CAT);
6525     else
6526       Result.addUnsizedArray(Info, E, AT->getElementType());
6527     return true;
6528   }
6529 
6530   case CK_FunctionToPointerDecay:
6531     return evaluateLValue(SubExpr, Result);
6532 
6533   case CK_LValueToRValue: {
6534     LValue LVal;
6535     if (!evaluateLValue(E->getSubExpr(), LVal))
6536       return false;
6537 
6538     APValue RVal;
6539     // Note, we use the subexpression's type in order to retain cv-qualifiers.
6540     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6541                                         LVal, RVal))
6542       return InvalidBaseOK &&
6543              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
6544     return Success(RVal, E);
6545   }
6546   }
6547 
6548   return ExprEvaluatorBaseTy::VisitCastExpr(E);
6549 }
6550 
6551 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
6552                                 UnaryExprOrTypeTrait ExprKind) {
6553   // C++ [expr.alignof]p3:
6554   //     When alignof is applied to a reference type, the result is the
6555   //     alignment of the referenced type.
6556   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6557     T = Ref->getPointeeType();
6558 
6559   if (T.getQualifiers().hasUnaligned())
6560     return CharUnits::One();
6561 
6562   const bool AlignOfReturnsPreferred =
6563       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6564 
6565   // __alignof is defined to return the preferred alignment.
6566   // Before 8, clang returned the preferred alignment for alignof and _Alignof
6567   // as well.
6568   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6569     return Info.Ctx.toCharUnitsFromBits(
6570       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6571   // alignof and _Alignof are defined to return the ABI alignment.
6572   else if (ExprKind == UETT_AlignOf)
6573     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6574   else
6575     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
6576 }
6577 
6578 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6579                                 UnaryExprOrTypeTrait ExprKind) {
6580   E = E->IgnoreParens();
6581 
6582   // The kinds of expressions that we have special-case logic here for
6583   // should be kept up to date with the special checks for those
6584   // expressions in Sema.
6585 
6586   // alignof decl is always accepted, even if it doesn't make sense: we default
6587   // to 1 in those cases.
6588   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6589     return Info.Ctx.getDeclAlign(DRE->getDecl(),
6590                                  /*RefAsPointee*/true);
6591 
6592   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6593     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6594                                  /*RefAsPointee*/true);
6595 
6596   return GetAlignOfType(Info, E->getType(), ExprKind);
6597 }
6598 
6599 // To be clear: this happily visits unsupported builtins. Better name welcomed.
6600 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6601   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6602     return true;
6603 
6604   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
6605     return false;
6606 
6607   Result.setInvalid(E);
6608   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
6609   Result.addUnsizedArray(Info, E, PointeeTy);
6610   return true;
6611 }
6612 
6613 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
6614   if (IsStringLiteralCall(E))
6615     return Success(E);
6616 
6617   if (unsigned BuiltinOp = E->getBuiltinCallee())
6618     return VisitBuiltinCallExpr(E, BuiltinOp);
6619 
6620   return visitNonBuiltinCallExpr(E);
6621 }
6622 
6623 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6624                                                 unsigned BuiltinOp) {
6625   switch (BuiltinOp) {
6626   case Builtin::BI__builtin_addressof:
6627     return evaluateLValue(E->getArg(0), Result);
6628   case Builtin::BI__builtin_assume_aligned: {
6629     // We need to be very careful here because: if the pointer does not have the
6630     // asserted alignment, then the behavior is undefined, and undefined
6631     // behavior is non-constant.
6632     if (!evaluatePointer(E->getArg(0), Result))
6633       return false;
6634 
6635     LValue OffsetResult(Result);
6636     APSInt Alignment;
6637     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6638       return false;
6639     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
6640 
6641     if (E->getNumArgs() > 2) {
6642       APSInt Offset;
6643       if (!EvaluateInteger(E->getArg(2), Offset, Info))
6644         return false;
6645 
6646       int64_t AdditionalOffset = -Offset.getZExtValue();
6647       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6648     }
6649 
6650     // If there is a base object, then it must have the correct alignment.
6651     if (OffsetResult.Base) {
6652       CharUnits BaseAlignment;
6653       if (const ValueDecl *VD =
6654           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6655         BaseAlignment = Info.Ctx.getDeclAlign(VD);
6656       } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
6657         BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
6658       } else {
6659         BaseAlignment = GetAlignOfType(
6660             Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
6661       }
6662 
6663       if (BaseAlignment < Align) {
6664         Result.Designator.setInvalid();
6665         // FIXME: Add support to Diagnostic for long / long long.
6666         CCEDiag(E->getArg(0),
6667                 diag::note_constexpr_baa_insufficient_alignment) << 0
6668           << (unsigned)BaseAlignment.getQuantity()
6669           << (unsigned)Align.getQuantity();
6670         return false;
6671       }
6672     }
6673 
6674     // The offset must also have the correct alignment.
6675     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
6676       Result.Designator.setInvalid();
6677 
6678       (OffsetResult.Base
6679            ? CCEDiag(E->getArg(0),
6680                      diag::note_constexpr_baa_insufficient_alignment) << 1
6681            : CCEDiag(E->getArg(0),
6682                      diag::note_constexpr_baa_value_insufficient_alignment))
6683         << (int)OffsetResult.Offset.getQuantity()
6684         << (unsigned)Align.getQuantity();
6685       return false;
6686     }
6687 
6688     return true;
6689   }
6690   case Builtin::BI__builtin_launder:
6691     return evaluatePointer(E->getArg(0), Result);
6692   case Builtin::BIstrchr:
6693   case Builtin::BIwcschr:
6694   case Builtin::BImemchr:
6695   case Builtin::BIwmemchr:
6696     if (Info.getLangOpts().CPlusPlus11)
6697       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6698         << /*isConstexpr*/0 << /*isConstructor*/0
6699         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6700     else
6701       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6702     LLVM_FALLTHROUGH;
6703   case Builtin::BI__builtin_strchr:
6704   case Builtin::BI__builtin_wcschr:
6705   case Builtin::BI__builtin_memchr:
6706   case Builtin::BI__builtin_char_memchr:
6707   case Builtin::BI__builtin_wmemchr: {
6708     if (!Visit(E->getArg(0)))
6709       return false;
6710     APSInt Desired;
6711     if (!EvaluateInteger(E->getArg(1), Desired, Info))
6712       return false;
6713     uint64_t MaxLength = uint64_t(-1);
6714     if (BuiltinOp != Builtin::BIstrchr &&
6715         BuiltinOp != Builtin::BIwcschr &&
6716         BuiltinOp != Builtin::BI__builtin_strchr &&
6717         BuiltinOp != Builtin::BI__builtin_wcschr) {
6718       APSInt N;
6719       if (!EvaluateInteger(E->getArg(2), N, Info))
6720         return false;
6721       MaxLength = N.getExtValue();
6722     }
6723     // We cannot find the value if there are no candidates to match against.
6724     if (MaxLength == 0u)
6725       return ZeroInitialization(E);
6726     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6727         Result.Designator.Invalid)
6728       return false;
6729     QualType CharTy = Result.Designator.getType(Info.Ctx);
6730     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6731                      BuiltinOp == Builtin::BI__builtin_memchr;
6732     assert(IsRawByte ||
6733            Info.Ctx.hasSameUnqualifiedType(
6734                CharTy, E->getArg(0)->getType()->getPointeeType()));
6735     // Pointers to const void may point to objects of incomplete type.
6736     if (IsRawByte && CharTy->isIncompleteType()) {
6737       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6738       return false;
6739     }
6740     // Give up on byte-oriented matching against multibyte elements.
6741     // FIXME: We can compare the bytes in the correct order.
6742     if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6743       return false;
6744     // Figure out what value we're actually looking for (after converting to
6745     // the corresponding unsigned type if necessary).
6746     uint64_t DesiredVal;
6747     bool StopAtNull = false;
6748     switch (BuiltinOp) {
6749     case Builtin::BIstrchr:
6750     case Builtin::BI__builtin_strchr:
6751       // strchr compares directly to the passed integer, and therefore
6752       // always fails if given an int that is not a char.
6753       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6754                                                   E->getArg(1)->getType(),
6755                                                   Desired),
6756                                Desired))
6757         return ZeroInitialization(E);
6758       StopAtNull = true;
6759       LLVM_FALLTHROUGH;
6760     case Builtin::BImemchr:
6761     case Builtin::BI__builtin_memchr:
6762     case Builtin::BI__builtin_char_memchr:
6763       // memchr compares by converting both sides to unsigned char. That's also
6764       // correct for strchr if we get this far (to cope with plain char being
6765       // unsigned in the strchr case).
6766       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6767       break;
6768 
6769     case Builtin::BIwcschr:
6770     case Builtin::BI__builtin_wcschr:
6771       StopAtNull = true;
6772       LLVM_FALLTHROUGH;
6773     case Builtin::BIwmemchr:
6774     case Builtin::BI__builtin_wmemchr:
6775       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6776       DesiredVal = Desired.getZExtValue();
6777       break;
6778     }
6779 
6780     for (; MaxLength; --MaxLength) {
6781       APValue Char;
6782       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6783           !Char.isInt())
6784         return false;
6785       if (Char.getInt().getZExtValue() == DesiredVal)
6786         return true;
6787       if (StopAtNull && !Char.getInt())
6788         break;
6789       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6790         return false;
6791     }
6792     // Not found: return nullptr.
6793     return ZeroInitialization(E);
6794   }
6795 
6796   case Builtin::BImemcpy:
6797   case Builtin::BImemmove:
6798   case Builtin::BIwmemcpy:
6799   case Builtin::BIwmemmove:
6800     if (Info.getLangOpts().CPlusPlus11)
6801       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6802         << /*isConstexpr*/0 << /*isConstructor*/0
6803         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6804     else
6805       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6806     LLVM_FALLTHROUGH;
6807   case Builtin::BI__builtin_memcpy:
6808   case Builtin::BI__builtin_memmove:
6809   case Builtin::BI__builtin_wmemcpy:
6810   case Builtin::BI__builtin_wmemmove: {
6811     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6812                  BuiltinOp == Builtin::BIwmemmove ||
6813                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6814                  BuiltinOp == Builtin::BI__builtin_wmemmove;
6815     bool Move = BuiltinOp == Builtin::BImemmove ||
6816                 BuiltinOp == Builtin::BIwmemmove ||
6817                 BuiltinOp == Builtin::BI__builtin_memmove ||
6818                 BuiltinOp == Builtin::BI__builtin_wmemmove;
6819 
6820     // The result of mem* is the first argument.
6821     if (!Visit(E->getArg(0)))
6822       return false;
6823     LValue Dest = Result;
6824 
6825     LValue Src;
6826     if (!EvaluatePointer(E->getArg(1), Src, Info))
6827       return false;
6828 
6829     APSInt N;
6830     if (!EvaluateInteger(E->getArg(2), N, Info))
6831       return false;
6832     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6833 
6834     // If the size is zero, we treat this as always being a valid no-op.
6835     // (Even if one of the src and dest pointers is null.)
6836     if (!N)
6837       return true;
6838 
6839     // Otherwise, if either of the operands is null, we can't proceed. Don't
6840     // try to determine the type of the copied objects, because there aren't
6841     // any.
6842     if (!Src.Base || !Dest.Base) {
6843       APValue Val;
6844       (!Src.Base ? Src : Dest).moveInto(Val);
6845       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6846           << Move << WChar << !!Src.Base
6847           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6848       return false;
6849     }
6850     if (Src.Designator.Invalid || Dest.Designator.Invalid)
6851       return false;
6852 
6853     // We require that Src and Dest are both pointers to arrays of
6854     // trivially-copyable type. (For the wide version, the designator will be
6855     // invalid if the designated object is not a wchar_t.)
6856     QualType T = Dest.Designator.getType(Info.Ctx);
6857     QualType SrcT = Src.Designator.getType(Info.Ctx);
6858     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6859       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6860       return false;
6861     }
6862     if (T->isIncompleteType()) {
6863       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6864       return false;
6865     }
6866     if (!T.isTriviallyCopyableType(Info.Ctx)) {
6867       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6868       return false;
6869     }
6870 
6871     // Figure out how many T's we're copying.
6872     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6873     if (!WChar) {
6874       uint64_t Remainder;
6875       llvm::APInt OrigN = N;
6876       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6877       if (Remainder) {
6878         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6879             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6880             << (unsigned)TSize;
6881         return false;
6882       }
6883     }
6884 
6885     // Check that the copying will remain within the arrays, just so that we
6886     // can give a more meaningful diagnostic. This implicitly also checks that
6887     // N fits into 64 bits.
6888     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6889     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6890     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6891       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6892           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6893           << N.toString(10, /*Signed*/false);
6894       return false;
6895     }
6896     uint64_t NElems = N.getZExtValue();
6897     uint64_t NBytes = NElems * TSize;
6898 
6899     // Check for overlap.
6900     int Direction = 1;
6901     if (HasSameBase(Src, Dest)) {
6902       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6903       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6904       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6905         // Dest is inside the source region.
6906         if (!Move) {
6907           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6908           return false;
6909         }
6910         // For memmove and friends, copy backwards.
6911         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6912             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6913           return false;
6914         Direction = -1;
6915       } else if (!Move && SrcOffset >= DestOffset &&
6916                  SrcOffset - DestOffset < NBytes) {
6917         // Src is inside the destination region for memcpy: invalid.
6918         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6919         return false;
6920       }
6921     }
6922 
6923     while (true) {
6924       APValue Val;
6925       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6926           !handleAssignment(Info, E, Dest, T, Val))
6927         return false;
6928       // Do not iterate past the last element; if we're copying backwards, that
6929       // might take us off the start of the array.
6930       if (--NElems == 0)
6931         return true;
6932       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6933           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6934         return false;
6935     }
6936   }
6937 
6938   default:
6939     return visitNonBuiltinCallExpr(E);
6940   }
6941 }
6942 
6943 //===----------------------------------------------------------------------===//
6944 // Member Pointer Evaluation
6945 //===----------------------------------------------------------------------===//
6946 
6947 namespace {
6948 class MemberPointerExprEvaluator
6949   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6950   MemberPtr &Result;
6951 
6952   bool Success(const ValueDecl *D) {
6953     Result = MemberPtr(D);
6954     return true;
6955   }
6956 public:
6957 
6958   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6959     : ExprEvaluatorBaseTy(Info), Result(Result) {}
6960 
6961   bool Success(const APValue &V, const Expr *E) {
6962     Result.setFrom(V);
6963     return true;
6964   }
6965   bool ZeroInitialization(const Expr *E) {
6966     return Success((const ValueDecl*)nullptr);
6967   }
6968 
6969   bool VisitCastExpr(const CastExpr *E);
6970   bool VisitUnaryAddrOf(const UnaryOperator *E);
6971 };
6972 } // end anonymous namespace
6973 
6974 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6975                                   EvalInfo &Info) {
6976   assert(E->isRValue() && E->getType()->isMemberPointerType());
6977   return MemberPointerExprEvaluator(Info, Result).Visit(E);
6978 }
6979 
6980 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6981   switch (E->getCastKind()) {
6982   default:
6983     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6984 
6985   case CK_NullToMemberPointer:
6986     VisitIgnoredValue(E->getSubExpr());
6987     return ZeroInitialization(E);
6988 
6989   case CK_BaseToDerivedMemberPointer: {
6990     if (!Visit(E->getSubExpr()))
6991       return false;
6992     if (E->path_empty())
6993       return true;
6994     // Base-to-derived member pointer casts store the path in derived-to-base
6995     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6996     // the wrong end of the derived->base arc, so stagger the path by one class.
6997     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6998     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6999          PathI != PathE; ++PathI) {
7000       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7001       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7002       if (!Result.castToDerived(Derived))
7003         return Error(E);
7004     }
7005     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7006     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
7007       return Error(E);
7008     return true;
7009   }
7010 
7011   case CK_DerivedToBaseMemberPointer:
7012     if (!Visit(E->getSubExpr()))
7013       return false;
7014     for (CastExpr::path_const_iterator PathI = E->path_begin(),
7015          PathE = E->path_end(); PathI != PathE; ++PathI) {
7016       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7017       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7018       if (!Result.castToBase(Base))
7019         return Error(E);
7020     }
7021     return true;
7022   }
7023 }
7024 
7025 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7026   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7027   // member can be formed.
7028   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7029 }
7030 
7031 //===----------------------------------------------------------------------===//
7032 // Record Evaluation
7033 //===----------------------------------------------------------------------===//
7034 
7035 namespace {
7036   class RecordExprEvaluator
7037   : public ExprEvaluatorBase<RecordExprEvaluator> {
7038     const LValue &This;
7039     APValue &Result;
7040   public:
7041 
7042     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7043       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7044 
7045     bool Success(const APValue &V, const Expr *E) {
7046       Result = V;
7047       return true;
7048     }
7049     bool ZeroInitialization(const Expr *E) {
7050       return ZeroInitialization(E, E->getType());
7051     }
7052     bool ZeroInitialization(const Expr *E, QualType T);
7053 
7054     bool VisitCallExpr(const CallExpr *E) {
7055       return handleCallExpr(E, Result, &This);
7056     }
7057     bool VisitCastExpr(const CastExpr *E);
7058     bool VisitInitListExpr(const InitListExpr *E);
7059     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7060       return VisitCXXConstructExpr(E, E->getType());
7061     }
7062     bool VisitLambdaExpr(const LambdaExpr *E);
7063     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
7064     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
7065     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
7066 
7067     bool VisitBinCmp(const BinaryOperator *E);
7068   };
7069 }
7070 
7071 /// Perform zero-initialization on an object of non-union class type.
7072 /// C++11 [dcl.init]p5:
7073 ///  To zero-initialize an object or reference of type T means:
7074 ///    [...]
7075 ///    -- if T is a (possibly cv-qualified) non-union class type,
7076 ///       each non-static data member and each base-class subobject is
7077 ///       zero-initialized
7078 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7079                                           const RecordDecl *RD,
7080                                           const LValue &This, APValue &Result) {
7081   assert(!RD->isUnion() && "Expected non-union class type");
7082   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7083   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
7084                    std::distance(RD->field_begin(), RD->field_end()));
7085 
7086   if (RD->isInvalidDecl()) return false;
7087   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7088 
7089   if (CD) {
7090     unsigned Index = 0;
7091     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
7092            End = CD->bases_end(); I != End; ++I, ++Index) {
7093       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7094       LValue Subobject = This;
7095       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7096         return false;
7097       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
7098                                          Result.getStructBase(Index)))
7099         return false;
7100     }
7101   }
7102 
7103   for (const auto *I : RD->fields()) {
7104     // -- if T is a reference type, no initialization is performed.
7105     if (I->getType()->isReferenceType())
7106       continue;
7107 
7108     LValue Subobject = This;
7109     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
7110       return false;
7111 
7112     ImplicitValueInitExpr VIE(I->getType());
7113     if (!EvaluateInPlace(
7114           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
7115       return false;
7116   }
7117 
7118   return true;
7119 }
7120 
7121 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7122   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
7123   if (RD->isInvalidDecl()) return false;
7124   if (RD->isUnion()) {
7125     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7126     // object's first non-static named data member is zero-initialized
7127     RecordDecl::field_iterator I = RD->field_begin();
7128     if (I == RD->field_end()) {
7129       Result = APValue((const FieldDecl*)nullptr);
7130       return true;
7131     }
7132 
7133     LValue Subobject = This;
7134     if (!HandleLValueMember(Info, E, Subobject, *I))
7135       return false;
7136     Result = APValue(*I);
7137     ImplicitValueInitExpr VIE(I->getType());
7138     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
7139   }
7140 
7141   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
7142     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
7143     return false;
7144   }
7145 
7146   return HandleClassZeroInitialization(Info, E, RD, This, Result);
7147 }
7148 
7149 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7150   switch (E->getCastKind()) {
7151   default:
7152     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7153 
7154   case CK_ConstructorConversion:
7155     return Visit(E->getSubExpr());
7156 
7157   case CK_DerivedToBase:
7158   case CK_UncheckedDerivedToBase: {
7159     APValue DerivedObject;
7160     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
7161       return false;
7162     if (!DerivedObject.isStruct())
7163       return Error(E->getSubExpr());
7164 
7165     // Derived-to-base rvalue conversion: just slice off the derived part.
7166     APValue *Value = &DerivedObject;
7167     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7168     for (CastExpr::path_const_iterator PathI = E->path_begin(),
7169          PathE = E->path_end(); PathI != PathE; ++PathI) {
7170       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7171       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7172       Value = &Value->getStructBase(getBaseIndex(RD, Base));
7173       RD = Base;
7174     }
7175     Result = *Value;
7176     return true;
7177   }
7178   }
7179 }
7180 
7181 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7182   if (E->isTransparent())
7183     return Visit(E->getInit(0));
7184 
7185   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
7186   if (RD->isInvalidDecl()) return false;
7187   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7188   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7189 
7190   EvalInfo::EvaluatingConstructorRAII EvalObj(
7191       Info,
7192       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7193       CXXRD && CXXRD->getNumBases());
7194 
7195   if (RD->isUnion()) {
7196     const FieldDecl *Field = E->getInitializedFieldInUnion();
7197     Result = APValue(Field);
7198     if (!Field)
7199       return true;
7200 
7201     // If the initializer list for a union does not contain any elements, the
7202     // first element of the union is value-initialized.
7203     // FIXME: The element should be initialized from an initializer list.
7204     //        Is this difference ever observable for initializer lists which
7205     //        we don't build?
7206     ImplicitValueInitExpr VIE(Field->getType());
7207     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7208 
7209     LValue Subobject = This;
7210     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7211       return false;
7212 
7213     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7214     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7215                                   isa<CXXDefaultInitExpr>(InitExpr));
7216 
7217     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
7218   }
7219 
7220   if (Result.isUninit())
7221     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7222                      std::distance(RD->field_begin(), RD->field_end()));
7223   unsigned ElementNo = 0;
7224   bool Success = true;
7225 
7226   // Initialize base classes.
7227   if (CXXRD && CXXRD->getNumBases()) {
7228     for (const auto &Base : CXXRD->bases()) {
7229       assert(ElementNo < E->getNumInits() && "missing init for base class");
7230       const Expr *Init = E->getInit(ElementNo);
7231 
7232       LValue Subobject = This;
7233       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7234         return false;
7235 
7236       APValue &FieldVal = Result.getStructBase(ElementNo);
7237       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
7238         if (!Info.noteFailure())
7239           return false;
7240         Success = false;
7241       }
7242       ++ElementNo;
7243     }
7244 
7245     EvalObj.finishedConstructingBases();
7246   }
7247 
7248   // Initialize members.
7249   for (const auto *Field : RD->fields()) {
7250     // Anonymous bit-fields are not considered members of the class for
7251     // purposes of aggregate initialization.
7252     if (Field->isUnnamedBitfield())
7253       continue;
7254 
7255     LValue Subobject = This;
7256 
7257     bool HaveInit = ElementNo < E->getNumInits();
7258 
7259     // FIXME: Diagnostics here should point to the end of the initializer
7260     // list, not the start.
7261     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
7262                             Subobject, Field, &Layout))
7263       return false;
7264 
7265     // Perform an implicit value-initialization for members beyond the end of
7266     // the initializer list.
7267     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
7268     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
7269 
7270     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7271     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7272                                   isa<CXXDefaultInitExpr>(Init));
7273 
7274     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7275     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7276         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
7277                                                        FieldVal, Field))) {
7278       if (!Info.noteFailure())
7279         return false;
7280       Success = false;
7281     }
7282   }
7283 
7284   return Success;
7285 }
7286 
7287 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7288                                                 QualType T) {
7289   // Note that E's type is not necessarily the type of our class here; we might
7290   // be initializing an array element instead.
7291   const CXXConstructorDecl *FD = E->getConstructor();
7292   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7293 
7294   bool ZeroInit = E->requiresZeroInitialization();
7295   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
7296     // If we've already performed zero-initialization, we're already done.
7297     if (!Result.isUninit())
7298       return true;
7299 
7300     // We can get here in two different ways:
7301     //  1) We're performing value-initialization, and should zero-initialize
7302     //     the object, or
7303     //  2) We're performing default-initialization of an object with a trivial
7304     //     constexpr default constructor, in which case we should start the
7305     //     lifetimes of all the base subobjects (there can be no data member
7306     //     subobjects in this case) per [basic.life]p1.
7307     // Either way, ZeroInitialization is appropriate.
7308     return ZeroInitialization(E, T);
7309   }
7310 
7311   const FunctionDecl *Definition = nullptr;
7312   auto Body = FD->getBody(Definition);
7313 
7314   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7315     return false;
7316 
7317   // Avoid materializing a temporary for an elidable copy/move constructor.
7318   if (E->isElidable() && !ZeroInit)
7319     if (const MaterializeTemporaryExpr *ME
7320           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
7321       return Visit(ME->GetTemporaryExpr());
7322 
7323   if (ZeroInit && !ZeroInitialization(E, T))
7324     return false;
7325 
7326   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7327   return HandleConstructorCall(E, This, Args,
7328                                cast<CXXConstructorDecl>(Definition), Info,
7329                                Result);
7330 }
7331 
7332 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
7333     const CXXInheritedCtorInitExpr *E) {
7334   if (!Info.CurrentCall) {
7335     assert(Info.checkingPotentialConstantExpression());
7336     return false;
7337   }
7338 
7339   const CXXConstructorDecl *FD = E->getConstructor();
7340   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
7341     return false;
7342 
7343   const FunctionDecl *Definition = nullptr;
7344   auto Body = FD->getBody(Definition);
7345 
7346   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7347     return false;
7348 
7349   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
7350                                cast<CXXConstructorDecl>(Definition), Info,
7351                                Result);
7352 }
7353 
7354 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
7355     const CXXStdInitializerListExpr *E) {
7356   const ConstantArrayType *ArrayType =
7357       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
7358 
7359   LValue Array;
7360   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
7361     return false;
7362 
7363   // Get a pointer to the first element of the array.
7364   Array.addArray(Info, E, ArrayType);
7365 
7366   // FIXME: Perform the checks on the field types in SemaInit.
7367   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
7368   RecordDecl::field_iterator Field = Record->field_begin();
7369   if (Field == Record->field_end())
7370     return Error(E);
7371 
7372   // Start pointer.
7373   if (!Field->getType()->isPointerType() ||
7374       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7375                             ArrayType->getElementType()))
7376     return Error(E);
7377 
7378   // FIXME: What if the initializer_list type has base classes, etc?
7379   Result = APValue(APValue::UninitStruct(), 0, 2);
7380   Array.moveInto(Result.getStructField(0));
7381 
7382   if (++Field == Record->field_end())
7383     return Error(E);
7384 
7385   if (Field->getType()->isPointerType() &&
7386       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7387                            ArrayType->getElementType())) {
7388     // End pointer.
7389     if (!HandleLValueArrayAdjustment(Info, E, Array,
7390                                      ArrayType->getElementType(),
7391                                      ArrayType->getSize().getZExtValue()))
7392       return false;
7393     Array.moveInto(Result.getStructField(1));
7394   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
7395     // Length.
7396     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
7397   else
7398     return Error(E);
7399 
7400   if (++Field != Record->field_end())
7401     return Error(E);
7402 
7403   return true;
7404 }
7405 
7406 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
7407   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
7408   if (ClosureClass->isInvalidDecl()) return false;
7409 
7410   if (Info.checkingPotentialConstantExpression()) return true;
7411 
7412   const size_t NumFields =
7413       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
7414 
7415   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
7416                                             E->capture_init_end()) &&
7417          "The number of lambda capture initializers should equal the number of "
7418          "fields within the closure type");
7419 
7420   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
7421   // Iterate through all the lambda's closure object's fields and initialize
7422   // them.
7423   auto *CaptureInitIt = E->capture_init_begin();
7424   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
7425   bool Success = true;
7426   for (const auto *Field : ClosureClass->fields()) {
7427     assert(CaptureInitIt != E->capture_init_end());
7428     // Get the initializer for this field
7429     Expr *const CurFieldInit = *CaptureInitIt++;
7430 
7431     // If there is no initializer, either this is a VLA or an error has
7432     // occurred.
7433     if (!CurFieldInit)
7434       return Error(E);
7435 
7436     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7437     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
7438       if (!Info.keepEvaluatingAfterFailure())
7439         return false;
7440       Success = false;
7441     }
7442     ++CaptureIt;
7443   }
7444   return Success;
7445 }
7446 
7447 static bool EvaluateRecord(const Expr *E, const LValue &This,
7448                            APValue &Result, EvalInfo &Info) {
7449   assert(E->isRValue() && E->getType()->isRecordType() &&
7450          "can't evaluate expression as a record rvalue");
7451   return RecordExprEvaluator(Info, This, Result).Visit(E);
7452 }
7453 
7454 //===----------------------------------------------------------------------===//
7455 // Temporary Evaluation
7456 //
7457 // Temporaries are represented in the AST as rvalues, but generally behave like
7458 // lvalues. The full-object of which the temporary is a subobject is implicitly
7459 // materialized so that a reference can bind to it.
7460 //===----------------------------------------------------------------------===//
7461 namespace {
7462 class TemporaryExprEvaluator
7463   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
7464 public:
7465   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
7466     LValueExprEvaluatorBaseTy(Info, Result, false) {}
7467 
7468   /// Visit an expression which constructs the value of this temporary.
7469   bool VisitConstructExpr(const Expr *E) {
7470     APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
7471     return EvaluateInPlace(Value, Info, Result, E);
7472   }
7473 
7474   bool VisitCastExpr(const CastExpr *E) {
7475     switch (E->getCastKind()) {
7476     default:
7477       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7478 
7479     case CK_ConstructorConversion:
7480       return VisitConstructExpr(E->getSubExpr());
7481     }
7482   }
7483   bool VisitInitListExpr(const InitListExpr *E) {
7484     return VisitConstructExpr(E);
7485   }
7486   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7487     return VisitConstructExpr(E);
7488   }
7489   bool VisitCallExpr(const CallExpr *E) {
7490     return VisitConstructExpr(E);
7491   }
7492   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
7493     return VisitConstructExpr(E);
7494   }
7495   bool VisitLambdaExpr(const LambdaExpr *E) {
7496     return VisitConstructExpr(E);
7497   }
7498 };
7499 } // end anonymous namespace
7500 
7501 /// Evaluate an expression of record type as a temporary.
7502 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
7503   assert(E->isRValue() && E->getType()->isRecordType());
7504   return TemporaryExprEvaluator(Info, Result).Visit(E);
7505 }
7506 
7507 //===----------------------------------------------------------------------===//
7508 // Vector Evaluation
7509 //===----------------------------------------------------------------------===//
7510 
7511 namespace {
7512   class VectorExprEvaluator
7513   : public ExprEvaluatorBase<VectorExprEvaluator> {
7514     APValue &Result;
7515   public:
7516 
7517     VectorExprEvaluator(EvalInfo &info, APValue &Result)
7518       : ExprEvaluatorBaseTy(info), Result(Result) {}
7519 
7520     bool Success(ArrayRef<APValue> V, const Expr *E) {
7521       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
7522       // FIXME: remove this APValue copy.
7523       Result = APValue(V.data(), V.size());
7524       return true;
7525     }
7526     bool Success(const APValue &V, const Expr *E) {
7527       assert(V.isVector());
7528       Result = V;
7529       return true;
7530     }
7531     bool ZeroInitialization(const Expr *E);
7532 
7533     bool VisitUnaryReal(const UnaryOperator *E)
7534       { return Visit(E->getSubExpr()); }
7535     bool VisitCastExpr(const CastExpr* E);
7536     bool VisitInitListExpr(const InitListExpr *E);
7537     bool VisitUnaryImag(const UnaryOperator *E);
7538     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
7539     //                 binary comparisons, binary and/or/xor,
7540     //                 shufflevector, ExtVectorElementExpr
7541   };
7542 } // end anonymous namespace
7543 
7544 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
7545   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
7546   return VectorExprEvaluator(Info, Result).Visit(E);
7547 }
7548 
7549 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
7550   const VectorType *VTy = E->getType()->castAs<VectorType>();
7551   unsigned NElts = VTy->getNumElements();
7552 
7553   const Expr *SE = E->getSubExpr();
7554   QualType SETy = SE->getType();
7555 
7556   switch (E->getCastKind()) {
7557   case CK_VectorSplat: {
7558     APValue Val = APValue();
7559     if (SETy->isIntegerType()) {
7560       APSInt IntResult;
7561       if (!EvaluateInteger(SE, IntResult, Info))
7562         return false;
7563       Val = APValue(std::move(IntResult));
7564     } else if (SETy->isRealFloatingType()) {
7565       APFloat FloatResult(0.0);
7566       if (!EvaluateFloat(SE, FloatResult, Info))
7567         return false;
7568       Val = APValue(std::move(FloatResult));
7569     } else {
7570       return Error(E);
7571     }
7572 
7573     // Splat and create vector APValue.
7574     SmallVector<APValue, 4> Elts(NElts, Val);
7575     return Success(Elts, E);
7576   }
7577   case CK_BitCast: {
7578     // Evaluate the operand into an APInt we can extract from.
7579     llvm::APInt SValInt;
7580     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7581       return false;
7582     // Extract the elements
7583     QualType EltTy = VTy->getElementType();
7584     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7585     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7586     SmallVector<APValue, 4> Elts;
7587     if (EltTy->isRealFloatingType()) {
7588       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
7589       unsigned FloatEltSize = EltSize;
7590       if (&Sem == &APFloat::x87DoubleExtended())
7591         FloatEltSize = 80;
7592       for (unsigned i = 0; i < NElts; i++) {
7593         llvm::APInt Elt;
7594         if (BigEndian)
7595           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7596         else
7597           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
7598         Elts.push_back(APValue(APFloat(Sem, Elt)));
7599       }
7600     } else if (EltTy->isIntegerType()) {
7601       for (unsigned i = 0; i < NElts; i++) {
7602         llvm::APInt Elt;
7603         if (BigEndian)
7604           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7605         else
7606           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7607         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7608       }
7609     } else {
7610       return Error(E);
7611     }
7612     return Success(Elts, E);
7613   }
7614   default:
7615     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7616   }
7617 }
7618 
7619 bool
7620 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7621   const VectorType *VT = E->getType()->castAs<VectorType>();
7622   unsigned NumInits = E->getNumInits();
7623   unsigned NumElements = VT->getNumElements();
7624 
7625   QualType EltTy = VT->getElementType();
7626   SmallVector<APValue, 4> Elements;
7627 
7628   // The number of initializers can be less than the number of
7629   // vector elements. For OpenCL, this can be due to nested vector
7630   // initialization. For GCC compatibility, missing trailing elements
7631   // should be initialized with zeroes.
7632   unsigned CountInits = 0, CountElts = 0;
7633   while (CountElts < NumElements) {
7634     // Handle nested vector initialization.
7635     if (CountInits < NumInits
7636         && E->getInit(CountInits)->getType()->isVectorType()) {
7637       APValue v;
7638       if (!EvaluateVector(E->getInit(CountInits), v, Info))
7639         return Error(E);
7640       unsigned vlen = v.getVectorLength();
7641       for (unsigned j = 0; j < vlen; j++)
7642         Elements.push_back(v.getVectorElt(j));
7643       CountElts += vlen;
7644     } else if (EltTy->isIntegerType()) {
7645       llvm::APSInt sInt(32);
7646       if (CountInits < NumInits) {
7647         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
7648           return false;
7649       } else // trailing integer zero.
7650         sInt = Info.Ctx.MakeIntValue(0, EltTy);
7651       Elements.push_back(APValue(sInt));
7652       CountElts++;
7653     } else {
7654       llvm::APFloat f(0.0);
7655       if (CountInits < NumInits) {
7656         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
7657           return false;
7658       } else // trailing float zero.
7659         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7660       Elements.push_back(APValue(f));
7661       CountElts++;
7662     }
7663     CountInits++;
7664   }
7665   return Success(Elements, E);
7666 }
7667 
7668 bool
7669 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
7670   const VectorType *VT = E->getType()->getAs<VectorType>();
7671   QualType EltTy = VT->getElementType();
7672   APValue ZeroElement;
7673   if (EltTy->isIntegerType())
7674     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7675   else
7676     ZeroElement =
7677         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7678 
7679   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
7680   return Success(Elements, E);
7681 }
7682 
7683 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7684   VisitIgnoredValue(E->getSubExpr());
7685   return ZeroInitialization(E);
7686 }
7687 
7688 //===----------------------------------------------------------------------===//
7689 // Array Evaluation
7690 //===----------------------------------------------------------------------===//
7691 
7692 namespace {
7693   class ArrayExprEvaluator
7694   : public ExprEvaluatorBase<ArrayExprEvaluator> {
7695     const LValue &This;
7696     APValue &Result;
7697   public:
7698 
7699     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7700       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
7701 
7702     bool Success(const APValue &V, const Expr *E) {
7703       assert(V.isArray() && "expected array");
7704       Result = V;
7705       return true;
7706     }
7707 
7708     bool ZeroInitialization(const Expr *E) {
7709       const ConstantArrayType *CAT =
7710           Info.Ctx.getAsConstantArrayType(E->getType());
7711       if (!CAT)
7712         return Error(E);
7713 
7714       Result = APValue(APValue::UninitArray(), 0,
7715                        CAT->getSize().getZExtValue());
7716       if (!Result.hasArrayFiller()) return true;
7717 
7718       // Zero-initialize all elements.
7719       LValue Subobject = This;
7720       Subobject.addArray(Info, E, CAT);
7721       ImplicitValueInitExpr VIE(CAT->getElementType());
7722       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
7723     }
7724 
7725     bool VisitCallExpr(const CallExpr *E) {
7726       return handleCallExpr(E, Result, &This);
7727     }
7728     bool VisitInitListExpr(const InitListExpr *E);
7729     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
7730     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
7731     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7732                                const LValue &Subobject,
7733                                APValue *Value, QualType Type);
7734     bool VisitStringLiteral(const StringLiteral *E) {
7735       expandStringLiteral(Info, E, Result);
7736       return true;
7737     }
7738   };
7739 } // end anonymous namespace
7740 
7741 static bool EvaluateArray(const Expr *E, const LValue &This,
7742                           APValue &Result, EvalInfo &Info) {
7743   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
7744   return ArrayExprEvaluator(Info, This, Result).Visit(E);
7745 }
7746 
7747 // Return true iff the given array filler may depend on the element index.
7748 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7749   // For now, just whitelist non-class value-initialization and initialization
7750   // lists comprised of them.
7751   if (isa<ImplicitValueInitExpr>(FillerExpr))
7752     return false;
7753   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7754     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7755       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7756         return true;
7757     }
7758     return false;
7759   }
7760   return true;
7761 }
7762 
7763 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7764   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7765   if (!CAT)
7766     return Error(E);
7767 
7768   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7769   // an appropriately-typed string literal enclosed in braces.
7770   if (E->isStringLiteralInit())
7771     return Visit(E->getInit(0));
7772 
7773   bool Success = true;
7774 
7775   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7776          "zero-initialized array shouldn't have any initialized elts");
7777   APValue Filler;
7778   if (Result.isArray() && Result.hasArrayFiller())
7779     Filler = Result.getArrayFiller();
7780 
7781   unsigned NumEltsToInit = E->getNumInits();
7782   unsigned NumElts = CAT->getSize().getZExtValue();
7783   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
7784 
7785   // If the initializer might depend on the array index, run it for each
7786   // array element.
7787   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
7788     NumEltsToInit = NumElts;
7789 
7790   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7791                           << NumEltsToInit << ".\n");
7792 
7793   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
7794 
7795   // If the array was previously zero-initialized, preserve the
7796   // zero-initialized values.
7797   if (!Filler.isUninit()) {
7798     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7799       Result.getArrayInitializedElt(I) = Filler;
7800     if (Result.hasArrayFiller())
7801       Result.getArrayFiller() = Filler;
7802   }
7803 
7804   LValue Subobject = This;
7805   Subobject.addArray(Info, E, CAT);
7806   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7807     const Expr *Init =
7808         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
7809     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7810                          Info, Subobject, Init) ||
7811         !HandleLValueArrayAdjustment(Info, Init, Subobject,
7812                                      CAT->getElementType(), 1)) {
7813       if (!Info.noteFailure())
7814         return false;
7815       Success = false;
7816     }
7817   }
7818 
7819   if (!Result.hasArrayFiller())
7820     return Success;
7821 
7822   // If we get here, we have a trivial filler, which we can just evaluate
7823   // once and splat over the rest of the array elements.
7824   assert(FillerExpr && "no array filler for incomplete init list");
7825   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7826                          FillerExpr) && Success;
7827 }
7828 
7829 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7830   if (E->getCommonExpr() &&
7831       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7832                 Info, E->getCommonExpr()->getSourceExpr()))
7833     return false;
7834 
7835   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7836 
7837   uint64_t Elements = CAT->getSize().getZExtValue();
7838   Result = APValue(APValue::UninitArray(), Elements, Elements);
7839 
7840   LValue Subobject = This;
7841   Subobject.addArray(Info, E, CAT);
7842 
7843   bool Success = true;
7844   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7845     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7846                          Info, Subobject, E->getSubExpr()) ||
7847         !HandleLValueArrayAdjustment(Info, E, Subobject,
7848                                      CAT->getElementType(), 1)) {
7849       if (!Info.noteFailure())
7850         return false;
7851       Success = false;
7852     }
7853   }
7854 
7855   return Success;
7856 }
7857 
7858 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
7859   return VisitCXXConstructExpr(E, This, &Result, E->getType());
7860 }
7861 
7862 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7863                                                const LValue &Subobject,
7864                                                APValue *Value,
7865                                                QualType Type) {
7866   bool HadZeroInit = !Value->isUninit();
7867 
7868   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7869     unsigned N = CAT->getSize().getZExtValue();
7870 
7871     // Preserve the array filler if we had prior zero-initialization.
7872     APValue Filler =
7873       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7874                                              : APValue();
7875 
7876     *Value = APValue(APValue::UninitArray(), N, N);
7877 
7878     if (HadZeroInit)
7879       for (unsigned I = 0; I != N; ++I)
7880         Value->getArrayInitializedElt(I) = Filler;
7881 
7882     // Initialize the elements.
7883     LValue ArrayElt = Subobject;
7884     ArrayElt.addArray(Info, E, CAT);
7885     for (unsigned I = 0; I != N; ++I)
7886       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7887                                  CAT->getElementType()) ||
7888           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7889                                        CAT->getElementType(), 1))
7890         return false;
7891 
7892     return true;
7893   }
7894 
7895   if (!Type->isRecordType())
7896     return Error(E);
7897 
7898   return RecordExprEvaluator(Info, Subobject, *Value)
7899              .VisitCXXConstructExpr(E, Type);
7900 }
7901 
7902 //===----------------------------------------------------------------------===//
7903 // Integer Evaluation
7904 //
7905 // As a GNU extension, we support casting pointers to sufficiently-wide integer
7906 // types and back in constant folding. Integer values are thus represented
7907 // either as an integer-valued APValue, or as an lvalue-valued APValue.
7908 //===----------------------------------------------------------------------===//
7909 
7910 namespace {
7911 class IntExprEvaluator
7912         : public ExprEvaluatorBase<IntExprEvaluator> {
7913   APValue &Result;
7914 public:
7915   IntExprEvaluator(EvalInfo &info, APValue &result)
7916       : ExprEvaluatorBaseTy(info), Result(result) {}
7917 
7918   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7919     assert(E->getType()->isIntegralOrEnumerationType() &&
7920            "Invalid evaluation result.");
7921     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
7922            "Invalid evaluation result.");
7923     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7924            "Invalid evaluation result.");
7925     Result = APValue(SI);
7926     return true;
7927   }
7928   bool Success(const llvm::APSInt &SI, const Expr *E) {
7929     return Success(SI, E, Result);
7930   }
7931 
7932   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7933     assert(E->getType()->isIntegralOrEnumerationType() &&
7934            "Invalid evaluation result.");
7935     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7936            "Invalid evaluation result.");
7937     Result = APValue(APSInt(I));
7938     Result.getInt().setIsUnsigned(
7939                             E->getType()->isUnsignedIntegerOrEnumerationType());
7940     return true;
7941   }
7942   bool Success(const llvm::APInt &I, const Expr *E) {
7943     return Success(I, E, Result);
7944   }
7945 
7946   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7947     assert(E->getType()->isIntegralOrEnumerationType() &&
7948            "Invalid evaluation result.");
7949     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7950     return true;
7951   }
7952   bool Success(uint64_t Value, const Expr *E) {
7953     return Success(Value, E, Result);
7954   }
7955 
7956   bool Success(CharUnits Size, const Expr *E) {
7957     return Success(Size.getQuantity(), E);
7958   }
7959 
7960   bool Success(const APValue &V, const Expr *E) {
7961     if (V.isLValue() || V.isAddrLabelDiff()) {
7962       Result = V;
7963       return true;
7964     }
7965     return Success(V.getInt(), E);
7966   }
7967 
7968   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7969 
7970   //===--------------------------------------------------------------------===//
7971   //                            Visitor Methods
7972   //===--------------------------------------------------------------------===//
7973 
7974   bool VisitConstantExpr(const ConstantExpr *E);
7975 
7976   bool VisitIntegerLiteral(const IntegerLiteral *E) {
7977     return Success(E->getValue(), E);
7978   }
7979   bool VisitCharacterLiteral(const CharacterLiteral *E) {
7980     return Success(E->getValue(), E);
7981   }
7982 
7983   bool CheckReferencedDecl(const Expr *E, const Decl *D);
7984   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7985     if (CheckReferencedDecl(E, E->getDecl()))
7986       return true;
7987 
7988     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7989   }
7990   bool VisitMemberExpr(const MemberExpr *E) {
7991     if (CheckReferencedDecl(E, E->getMemberDecl())) {
7992       VisitIgnoredBaseExpression(E->getBase());
7993       return true;
7994     }
7995 
7996     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7997   }
7998 
7999   bool VisitCallExpr(const CallExpr *E);
8000   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8001   bool VisitBinaryOperator(const BinaryOperator *E);
8002   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
8003   bool VisitUnaryOperator(const UnaryOperator *E);
8004 
8005   bool VisitCastExpr(const CastExpr* E);
8006   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
8007 
8008   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
8009     return Success(E->getValue(), E);
8010   }
8011 
8012   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8013     return Success(E->getValue(), E);
8014   }
8015 
8016   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8017     if (Info.ArrayInitIndex == uint64_t(-1)) {
8018       // We were asked to evaluate this subexpression independent of the
8019       // enclosing ArrayInitLoopExpr. We can't do that.
8020       Info.FFDiag(E);
8021       return false;
8022     }
8023     return Success(Info.ArrayInitIndex, E);
8024   }
8025 
8026   // Note, GNU defines __null as an integer, not a pointer.
8027   bool VisitGNUNullExpr(const GNUNullExpr *E) {
8028     return ZeroInitialization(E);
8029   }
8030 
8031   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8032     return Success(E->getValue(), E);
8033   }
8034 
8035   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8036     return Success(E->getValue(), E);
8037   }
8038 
8039   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8040     return Success(E->getValue(), E);
8041   }
8042 
8043   bool VisitUnaryReal(const UnaryOperator *E);
8044   bool VisitUnaryImag(const UnaryOperator *E);
8045 
8046   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
8047   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
8048   bool VisitSourceLocExpr(const SourceLocExpr *E);
8049   // FIXME: Missing: array subscript of vector, member of vector
8050 };
8051 
8052 class FixedPointExprEvaluator
8053     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8054   APValue &Result;
8055 
8056  public:
8057   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8058       : ExprEvaluatorBaseTy(info), Result(result) {}
8059 
8060   bool Success(const llvm::APInt &I, const Expr *E) {
8061     return Success(
8062         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8063   }
8064 
8065   bool Success(uint64_t Value, const Expr *E) {
8066     return Success(
8067         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8068   }
8069 
8070   bool Success(const APValue &V, const Expr *E) {
8071     return Success(V.getFixedPoint(), E);
8072   }
8073 
8074   bool Success(const APFixedPoint &V, const Expr *E) {
8075     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8076     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8077            "Invalid evaluation result.");
8078     Result = APValue(V);
8079     return true;
8080   }
8081 
8082   //===--------------------------------------------------------------------===//
8083   //                            Visitor Methods
8084   //===--------------------------------------------------------------------===//
8085 
8086   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8087     return Success(E->getValue(), E);
8088   }
8089 
8090   bool VisitCastExpr(const CastExpr *E);
8091   bool VisitUnaryOperator(const UnaryOperator *E);
8092   bool VisitBinaryOperator(const BinaryOperator *E);
8093 };
8094 } // end anonymous namespace
8095 
8096 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8097 /// produce either the integer value or a pointer.
8098 ///
8099 /// GCC has a heinous extension which folds casts between pointer types and
8100 /// pointer-sized integral types. We support this by allowing the evaluation of
8101 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8102 /// Some simple arithmetic on such values is supported (they are treated much
8103 /// like char*).
8104 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
8105                                     EvalInfo &Info) {
8106   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
8107   return IntExprEvaluator(Info, Result).Visit(E);
8108 }
8109 
8110 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
8111   APValue Val;
8112   if (!EvaluateIntegerOrLValue(E, Val, Info))
8113     return false;
8114   if (!Val.isInt()) {
8115     // FIXME: It would be better to produce the diagnostic for casting
8116     //        a pointer to an integer.
8117     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8118     return false;
8119   }
8120   Result = Val.getInt();
8121   return true;
8122 }
8123 
8124 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8125   APValue Evaluated = E->EvaluateInContext(
8126       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8127   return Success(Evaluated, E);
8128 }
8129 
8130 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8131                                EvalInfo &Info) {
8132   if (E->getType()->isFixedPointType()) {
8133     APValue Val;
8134     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8135       return false;
8136     if (!Val.isFixedPoint())
8137       return false;
8138 
8139     Result = Val.getFixedPoint();
8140     return true;
8141   }
8142   return false;
8143 }
8144 
8145 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8146                                         EvalInfo &Info) {
8147   if (E->getType()->isIntegerType()) {
8148     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8149     APSInt Val;
8150     if (!EvaluateInteger(E, Val, Info))
8151       return false;
8152     Result = APFixedPoint(Val, FXSema);
8153     return true;
8154   } else if (E->getType()->isFixedPointType()) {
8155     return EvaluateFixedPoint(E, Result, Info);
8156   }
8157   return false;
8158 }
8159 
8160 /// Check whether the given declaration can be directly converted to an integral
8161 /// rvalue. If not, no diagnostic is produced; there are other things we can
8162 /// try.
8163 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
8164   // Enums are integer constant exprs.
8165   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
8166     // Check for signedness/width mismatches between E type and ECD value.
8167     bool SameSign = (ECD->getInitVal().isSigned()
8168                      == E->getType()->isSignedIntegerOrEnumerationType());
8169     bool SameWidth = (ECD->getInitVal().getBitWidth()
8170                       == Info.Ctx.getIntWidth(E->getType()));
8171     if (SameSign && SameWidth)
8172       return Success(ECD->getInitVal(), E);
8173     else {
8174       // Get rid of mismatch (otherwise Success assertions will fail)
8175       // by computing a new value matching the type of E.
8176       llvm::APSInt Val = ECD->getInitVal();
8177       if (!SameSign)
8178         Val.setIsSigned(!ECD->getInitVal().isSigned());
8179       if (!SameWidth)
8180         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8181       return Success(Val, E);
8182     }
8183   }
8184   return false;
8185 }
8186 
8187 /// Values returned by __builtin_classify_type, chosen to match the values
8188 /// produced by GCC's builtin.
8189 enum class GCCTypeClass {
8190   None = -1,
8191   Void = 0,
8192   Integer = 1,
8193   // GCC reserves 2 for character types, but instead classifies them as
8194   // integers.
8195   Enum = 3,
8196   Bool = 4,
8197   Pointer = 5,
8198   // GCC reserves 6 for references, but appears to never use it (because
8199   // expressions never have reference type, presumably).
8200   PointerToDataMember = 7,
8201   RealFloat = 8,
8202   Complex = 9,
8203   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8204   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8205   // GCC claims to reserve 11 for pointers to member functions, but *actually*
8206   // uses 12 for that purpose, same as for a class or struct. Maybe it
8207   // internally implements a pointer to member as a struct?  Who knows.
8208   PointerToMemberFunction = 12, // Not a bug, see above.
8209   ClassOrStruct = 12,
8210   Union = 13,
8211   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8212   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8213   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8214   // literals.
8215 };
8216 
8217 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8218 /// as GCC.
8219 static GCCTypeClass
8220 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8221   assert(!T->isDependentType() && "unexpected dependent type");
8222 
8223   QualType CanTy = T.getCanonicalType();
8224   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8225 
8226   switch (CanTy->getTypeClass()) {
8227 #define TYPE(ID, BASE)
8228 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8229 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8230 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8231 #include "clang/AST/TypeNodes.def"
8232   case Type::Auto:
8233   case Type::DeducedTemplateSpecialization:
8234       llvm_unreachable("unexpected non-canonical or dependent type");
8235 
8236   case Type::Builtin:
8237     switch (BT->getKind()) {
8238 #define BUILTIN_TYPE(ID, SINGLETON_ID)
8239 #define SIGNED_TYPE(ID, SINGLETON_ID) \
8240     case BuiltinType::ID: return GCCTypeClass::Integer;
8241 #define FLOATING_TYPE(ID, SINGLETON_ID) \
8242     case BuiltinType::ID: return GCCTypeClass::RealFloat;
8243 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8244     case BuiltinType::ID: break;
8245 #include "clang/AST/BuiltinTypes.def"
8246     case BuiltinType::Void:
8247       return GCCTypeClass::Void;
8248 
8249     case BuiltinType::Bool:
8250       return GCCTypeClass::Bool;
8251 
8252     case BuiltinType::Char_U:
8253     case BuiltinType::UChar:
8254     case BuiltinType::WChar_U:
8255     case BuiltinType::Char8:
8256     case BuiltinType::Char16:
8257     case BuiltinType::Char32:
8258     case BuiltinType::UShort:
8259     case BuiltinType::UInt:
8260     case BuiltinType::ULong:
8261     case BuiltinType::ULongLong:
8262     case BuiltinType::UInt128:
8263       return GCCTypeClass::Integer;
8264 
8265     case BuiltinType::UShortAccum:
8266     case BuiltinType::UAccum:
8267     case BuiltinType::ULongAccum:
8268     case BuiltinType::UShortFract:
8269     case BuiltinType::UFract:
8270     case BuiltinType::ULongFract:
8271     case BuiltinType::SatUShortAccum:
8272     case BuiltinType::SatUAccum:
8273     case BuiltinType::SatULongAccum:
8274     case BuiltinType::SatUShortFract:
8275     case BuiltinType::SatUFract:
8276     case BuiltinType::SatULongFract:
8277       return GCCTypeClass::None;
8278 
8279     case BuiltinType::NullPtr:
8280 
8281     case BuiltinType::ObjCId:
8282     case BuiltinType::ObjCClass:
8283     case BuiltinType::ObjCSel:
8284 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8285     case BuiltinType::Id:
8286 #include "clang/Basic/OpenCLImageTypes.def"
8287 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8288     case BuiltinType::Id:
8289 #include "clang/Basic/OpenCLExtensionTypes.def"
8290     case BuiltinType::OCLSampler:
8291     case BuiltinType::OCLEvent:
8292     case BuiltinType::OCLClkEvent:
8293     case BuiltinType::OCLQueue:
8294     case BuiltinType::OCLReserveID:
8295       return GCCTypeClass::None;
8296 
8297     case BuiltinType::Dependent:
8298       llvm_unreachable("unexpected dependent type");
8299     };
8300     llvm_unreachable("unexpected placeholder type");
8301 
8302   case Type::Enum:
8303     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
8304 
8305   case Type::Pointer:
8306   case Type::ConstantArray:
8307   case Type::VariableArray:
8308   case Type::IncompleteArray:
8309   case Type::FunctionNoProto:
8310   case Type::FunctionProto:
8311     return GCCTypeClass::Pointer;
8312 
8313   case Type::MemberPointer:
8314     return CanTy->isMemberDataPointerType()
8315                ? GCCTypeClass::PointerToDataMember
8316                : GCCTypeClass::PointerToMemberFunction;
8317 
8318   case Type::Complex:
8319     return GCCTypeClass::Complex;
8320 
8321   case Type::Record:
8322     return CanTy->isUnionType() ? GCCTypeClass::Union
8323                                 : GCCTypeClass::ClassOrStruct;
8324 
8325   case Type::Atomic:
8326     // GCC classifies _Atomic T the same as T.
8327     return EvaluateBuiltinClassifyType(
8328         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
8329 
8330   case Type::BlockPointer:
8331   case Type::Vector:
8332   case Type::ExtVector:
8333   case Type::ObjCObject:
8334   case Type::ObjCInterface:
8335   case Type::ObjCObjectPointer:
8336   case Type::Pipe:
8337     // GCC classifies vectors as None. We follow its lead and classify all
8338     // other types that don't fit into the regular classification the same way.
8339     return GCCTypeClass::None;
8340 
8341   case Type::LValueReference:
8342   case Type::RValueReference:
8343     llvm_unreachable("invalid type for expression");
8344   }
8345 
8346   llvm_unreachable("unexpected type class");
8347 }
8348 
8349 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8350 /// as GCC.
8351 static GCCTypeClass
8352 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
8353   // If no argument was supplied, default to None. This isn't
8354   // ideal, however it is what gcc does.
8355   if (E->getNumArgs() == 0)
8356     return GCCTypeClass::None;
8357 
8358   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
8359   // being an ICE, but still folds it to a constant using the type of the first
8360   // argument.
8361   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
8362 }
8363 
8364 /// EvaluateBuiltinConstantPForLValue - Determine the result of
8365 /// __builtin_constant_p when applied to the given pointer.
8366 ///
8367 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
8368 /// or it points to the first character of a string literal.
8369 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
8370   APValue::LValueBase Base = LV.getLValueBase();
8371   if (Base.isNull()) {
8372     // A null base is acceptable.
8373     return true;
8374   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
8375     if (!isa<StringLiteral>(E))
8376       return false;
8377     return LV.getLValueOffset().isZero();
8378   } else if (Base.is<TypeInfoLValue>()) {
8379     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
8380     // evaluate to true.
8381     return true;
8382   } else {
8383     // Any other base is not constant enough for GCC.
8384     return false;
8385   }
8386 }
8387 
8388 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
8389 /// GCC as we can manage.
8390 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
8391   // This evaluation is not permitted to have side-effects, so evaluate it in
8392   // a speculative evaluation context.
8393   SpeculativeEvaluationRAII SpeculativeEval(Info);
8394 
8395   // Constant-folding is always enabled for the operand of __builtin_constant_p
8396   // (even when the enclosing evaluation context otherwise requires a strict
8397   // language-specific constant expression).
8398   FoldConstant Fold(Info, true);
8399 
8400   QualType ArgType = Arg->getType();
8401 
8402   // __builtin_constant_p always has one operand. The rules which gcc follows
8403   // are not precisely documented, but are as follows:
8404   //
8405   //  - If the operand is of integral, floating, complex or enumeration type,
8406   //    and can be folded to a known value of that type, it returns 1.
8407   //  - If the operand can be folded to a pointer to the first character
8408   //    of a string literal (or such a pointer cast to an integral type)
8409   //    or to a null pointer or an integer cast to a pointer, it returns 1.
8410   //
8411   // Otherwise, it returns 0.
8412   //
8413   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
8414   // its support for this did not work prior to GCC 9 and is not yet well
8415   // understood.
8416   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
8417       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
8418       ArgType->isNullPtrType()) {
8419     APValue V;
8420     if (!::EvaluateAsRValue(Info, Arg, V)) {
8421       Fold.keepDiagnostics();
8422       return false;
8423     }
8424 
8425     // For a pointer (possibly cast to integer), there are special rules.
8426     if (V.getKind() == APValue::LValue)
8427       return EvaluateBuiltinConstantPForLValue(V);
8428 
8429     // Otherwise, any constant value is good enough.
8430     return V.getKind() != APValue::Uninitialized;
8431   }
8432 
8433   // Anything else isn't considered to be sufficiently constant.
8434   return false;
8435 }
8436 
8437 /// Retrieves the "underlying object type" of the given expression,
8438 /// as used by __builtin_object_size.
8439 static QualType getObjectType(APValue::LValueBase B) {
8440   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
8441     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8442       return VD->getType();
8443   } else if (const Expr *E = B.get<const Expr*>()) {
8444     if (isa<CompoundLiteralExpr>(E))
8445       return E->getType();
8446   } else if (B.is<TypeInfoLValue>()) {
8447     return B.getTypeInfoType();
8448   }
8449 
8450   return QualType();
8451 }
8452 
8453 /// A more selective version of E->IgnoreParenCasts for
8454 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
8455 /// to change the type of E.
8456 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
8457 ///
8458 /// Always returns an RValue with a pointer representation.
8459 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
8460   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8461 
8462   auto *NoParens = E->IgnoreParens();
8463   auto *Cast = dyn_cast<CastExpr>(NoParens);
8464   if (Cast == nullptr)
8465     return NoParens;
8466 
8467   // We only conservatively allow a few kinds of casts, because this code is
8468   // inherently a simple solution that seeks to support the common case.
8469   auto CastKind = Cast->getCastKind();
8470   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
8471       CastKind != CK_AddressSpaceConversion)
8472     return NoParens;
8473 
8474   auto *SubExpr = Cast->getSubExpr();
8475   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
8476     return NoParens;
8477   return ignorePointerCastsAndParens(SubExpr);
8478 }
8479 
8480 /// Checks to see if the given LValue's Designator is at the end of the LValue's
8481 /// record layout. e.g.
8482 ///   struct { struct { int a, b; } fst, snd; } obj;
8483 ///   obj.fst   // no
8484 ///   obj.snd   // yes
8485 ///   obj.fst.a // no
8486 ///   obj.fst.b // no
8487 ///   obj.snd.a // no
8488 ///   obj.snd.b // yes
8489 ///
8490 /// Please note: this function is specialized for how __builtin_object_size
8491 /// views "objects".
8492 ///
8493 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
8494 /// correct result, it will always return true.
8495 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
8496   assert(!LVal.Designator.Invalid);
8497 
8498   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
8499     const RecordDecl *Parent = FD->getParent();
8500     Invalid = Parent->isInvalidDecl();
8501     if (Invalid || Parent->isUnion())
8502       return true;
8503     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
8504     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
8505   };
8506 
8507   auto &Base = LVal.getLValueBase();
8508   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
8509     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
8510       bool Invalid;
8511       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8512         return Invalid;
8513     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
8514       for (auto *FD : IFD->chain()) {
8515         bool Invalid;
8516         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
8517           return Invalid;
8518       }
8519     }
8520   }
8521 
8522   unsigned I = 0;
8523   QualType BaseType = getType(Base);
8524   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
8525     // If we don't know the array bound, conservatively assume we're looking at
8526     // the final array element.
8527     ++I;
8528     if (BaseType->isIncompleteArrayType())
8529       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
8530     else
8531       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
8532   }
8533 
8534   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
8535     const auto &Entry = LVal.Designator.Entries[I];
8536     if (BaseType->isArrayType()) {
8537       // Because __builtin_object_size treats arrays as objects, we can ignore
8538       // the index iff this is the last array in the Designator.
8539       if (I + 1 == E)
8540         return true;
8541       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
8542       uint64_t Index = Entry.getAsArrayIndex();
8543       if (Index + 1 != CAT->getSize())
8544         return false;
8545       BaseType = CAT->getElementType();
8546     } else if (BaseType->isAnyComplexType()) {
8547       const auto *CT = BaseType->castAs<ComplexType>();
8548       uint64_t Index = Entry.getAsArrayIndex();
8549       if (Index != 1)
8550         return false;
8551       BaseType = CT->getElementType();
8552     } else if (auto *FD = getAsField(Entry)) {
8553       bool Invalid;
8554       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8555         return Invalid;
8556       BaseType = FD->getType();
8557     } else {
8558       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
8559       return false;
8560     }
8561   }
8562   return true;
8563 }
8564 
8565 /// Tests to see if the LValue has a user-specified designator (that isn't
8566 /// necessarily valid). Note that this always returns 'true' if the LValue has
8567 /// an unsized array as its first designator entry, because there's currently no
8568 /// way to tell if the user typed *foo or foo[0].
8569 static bool refersToCompleteObject(const LValue &LVal) {
8570   if (LVal.Designator.Invalid)
8571     return false;
8572 
8573   if (!LVal.Designator.Entries.empty())
8574     return LVal.Designator.isMostDerivedAnUnsizedArray();
8575 
8576   if (!LVal.InvalidBase)
8577     return true;
8578 
8579   // If `E` is a MemberExpr, then the first part of the designator is hiding in
8580   // the LValueBase.
8581   const auto *E = LVal.Base.dyn_cast<const Expr *>();
8582   return !E || !isa<MemberExpr>(E);
8583 }
8584 
8585 /// Attempts to detect a user writing into a piece of memory that's impossible
8586 /// to figure out the size of by just using types.
8587 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
8588   const SubobjectDesignator &Designator = LVal.Designator;
8589   // Notes:
8590   // - Users can only write off of the end when we have an invalid base. Invalid
8591   //   bases imply we don't know where the memory came from.
8592   // - We used to be a bit more aggressive here; we'd only be conservative if
8593   //   the array at the end was flexible, or if it had 0 or 1 elements. This
8594   //   broke some common standard library extensions (PR30346), but was
8595   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
8596   //   with some sort of whitelist. OTOH, it seems that GCC is always
8597   //   conservative with the last element in structs (if it's an array), so our
8598   //   current behavior is more compatible than a whitelisting approach would
8599   //   be.
8600   return LVal.InvalidBase &&
8601          Designator.Entries.size() == Designator.MostDerivedPathLength &&
8602          Designator.MostDerivedIsArrayElement &&
8603          isDesignatorAtObjectEnd(Ctx, LVal);
8604 }
8605 
8606 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8607 /// Fails if the conversion would cause loss of precision.
8608 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8609                                             CharUnits &Result) {
8610   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8611   if (Int.ugt(CharUnitsMax))
8612     return false;
8613   Result = CharUnits::fromQuantity(Int.getZExtValue());
8614   return true;
8615 }
8616 
8617 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8618 /// determine how many bytes exist from the beginning of the object to either
8619 /// the end of the current subobject, or the end of the object itself, depending
8620 /// on what the LValue looks like + the value of Type.
8621 ///
8622 /// If this returns false, the value of Result is undefined.
8623 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8624                                unsigned Type, const LValue &LVal,
8625                                CharUnits &EndOffset) {
8626   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
8627 
8628   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8629     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8630       return false;
8631     return HandleSizeof(Info, ExprLoc, Ty, Result);
8632   };
8633 
8634   // We want to evaluate the size of the entire object. This is a valid fallback
8635   // for when Type=1 and the designator is invalid, because we're asked for an
8636   // upper-bound.
8637   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8638     // Type=3 wants a lower bound, so we can't fall back to this.
8639     if (Type == 3 && !DetermineForCompleteObject)
8640       return false;
8641 
8642     llvm::APInt APEndOffset;
8643     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8644         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8645       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8646 
8647     if (LVal.InvalidBase)
8648       return false;
8649 
8650     QualType BaseTy = getObjectType(LVal.getLValueBase());
8651     return CheckedHandleSizeof(BaseTy, EndOffset);
8652   }
8653 
8654   // We want to evaluate the size of a subobject.
8655   const SubobjectDesignator &Designator = LVal.Designator;
8656 
8657   // The following is a moderately common idiom in C:
8658   //
8659   // struct Foo { int a; char c[1]; };
8660   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8661   // strcpy(&F->c[0], Bar);
8662   //
8663   // In order to not break too much legacy code, we need to support it.
8664   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8665     // If we can resolve this to an alloc_size call, we can hand that back,
8666     // because we know for certain how many bytes there are to write to.
8667     llvm::APInt APEndOffset;
8668     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8669         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8670       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8671 
8672     // If we cannot determine the size of the initial allocation, then we can't
8673     // given an accurate upper-bound. However, we are still able to give
8674     // conservative lower-bounds for Type=3.
8675     if (Type == 1)
8676       return false;
8677   }
8678 
8679   CharUnits BytesPerElem;
8680   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
8681     return false;
8682 
8683   // According to the GCC documentation, we want the size of the subobject
8684   // denoted by the pointer. But that's not quite right -- what we actually
8685   // want is the size of the immediately-enclosing array, if there is one.
8686   int64_t ElemsRemaining;
8687   if (Designator.MostDerivedIsArrayElement &&
8688       Designator.Entries.size() == Designator.MostDerivedPathLength) {
8689     uint64_t ArraySize = Designator.getMostDerivedArraySize();
8690     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
8691     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8692   } else {
8693     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8694   }
8695 
8696   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8697   return true;
8698 }
8699 
8700 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
8701 /// returns true and stores the result in @p Size.
8702 ///
8703 /// If @p WasError is non-null, this will report whether the failure to evaluate
8704 /// is to be treated as an Error in IntExprEvaluator.
8705 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8706                                          EvalInfo &Info, uint64_t &Size) {
8707   // Determine the denoted object.
8708   LValue LVal;
8709   {
8710     // The operand of __builtin_object_size is never evaluated for side-effects.
8711     // If there are any, but we can determine the pointed-to object anyway, then
8712     // ignore the side-effects.
8713     SpeculativeEvaluationRAII SpeculativeEval(Info);
8714     IgnoreSideEffectsRAII Fold(Info);
8715 
8716     if (E->isGLValue()) {
8717       // It's possible for us to be given GLValues if we're called via
8718       // Expr::tryEvaluateObjectSize.
8719       APValue RVal;
8720       if (!EvaluateAsRValue(Info, E, RVal))
8721         return false;
8722       LVal.setFrom(Info.Ctx, RVal);
8723     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8724                                 /*InvalidBaseOK=*/true))
8725       return false;
8726   }
8727 
8728   // If we point to before the start of the object, there are no accessible
8729   // bytes.
8730   if (LVal.getLValueOffset().isNegative()) {
8731     Size = 0;
8732     return true;
8733   }
8734 
8735   CharUnits EndOffset;
8736   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8737     return false;
8738 
8739   // If we've fallen outside of the end offset, just pretend there's nothing to
8740   // write to/read from.
8741   if (EndOffset <= LVal.getLValueOffset())
8742     Size = 0;
8743   else
8744     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8745   return true;
8746 }
8747 
8748 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8749   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8750   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8751 }
8752 
8753 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
8754   if (unsigned BuiltinOp = E->getBuiltinCallee())
8755     return VisitBuiltinCallExpr(E, BuiltinOp);
8756 
8757   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8758 }
8759 
8760 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8761                                             unsigned BuiltinOp) {
8762   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
8763   default:
8764     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8765 
8766   case Builtin::BI__builtin_dynamic_object_size:
8767   case Builtin::BI__builtin_object_size: {
8768     // The type was checked when we built the expression.
8769     unsigned Type =
8770         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8771     assert(Type <= 3 && "unexpected type");
8772 
8773     uint64_t Size;
8774     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8775       return Success(Size, E);
8776 
8777     if (E->getArg(0)->HasSideEffects(Info.Ctx))
8778       return Success((Type & 2) ? 0 : -1, E);
8779 
8780     // Expression had no side effects, but we couldn't statically determine the
8781     // size of the referenced object.
8782     switch (Info.EvalMode) {
8783     case EvalInfo::EM_ConstantExpression:
8784     case EvalInfo::EM_PotentialConstantExpression:
8785     case EvalInfo::EM_ConstantFold:
8786     case EvalInfo::EM_EvaluateForOverflow:
8787     case EvalInfo::EM_IgnoreSideEffects:
8788       // Leave it to IR generation.
8789       return Error(E);
8790     case EvalInfo::EM_ConstantExpressionUnevaluated:
8791     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
8792       // Reduce it to a constant now.
8793       return Success((Type & 2) ? 0 : -1, E);
8794     }
8795 
8796     llvm_unreachable("unexpected EvalMode");
8797   }
8798 
8799   case Builtin::BI__builtin_os_log_format_buffer_size: {
8800     analyze_os_log::OSLogBufferLayout Layout;
8801     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8802     return Success(Layout.size().getQuantity(), E);
8803   }
8804 
8805   case Builtin::BI__builtin_bswap16:
8806   case Builtin::BI__builtin_bswap32:
8807   case Builtin::BI__builtin_bswap64: {
8808     APSInt Val;
8809     if (!EvaluateInteger(E->getArg(0), Val, Info))
8810       return false;
8811 
8812     return Success(Val.byteSwap(), E);
8813   }
8814 
8815   case Builtin::BI__builtin_classify_type:
8816     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
8817 
8818   case Builtin::BI__builtin_clrsb:
8819   case Builtin::BI__builtin_clrsbl:
8820   case Builtin::BI__builtin_clrsbll: {
8821     APSInt Val;
8822     if (!EvaluateInteger(E->getArg(0), Val, Info))
8823       return false;
8824 
8825     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8826   }
8827 
8828   case Builtin::BI__builtin_clz:
8829   case Builtin::BI__builtin_clzl:
8830   case Builtin::BI__builtin_clzll:
8831   case Builtin::BI__builtin_clzs: {
8832     APSInt Val;
8833     if (!EvaluateInteger(E->getArg(0), Val, Info))
8834       return false;
8835     if (!Val)
8836       return Error(E);
8837 
8838     return Success(Val.countLeadingZeros(), E);
8839   }
8840 
8841   case Builtin::BI__builtin_constant_p: {
8842     const Expr *Arg = E->getArg(0);
8843     if (EvaluateBuiltinConstantP(Info, Arg))
8844       return Success(true, E);
8845     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
8846       // Outside a constant context, eagerly evaluate to false in the presence
8847       // of side-effects in order to avoid -Wunsequenced false-positives in
8848       // a branch on __builtin_constant_p(expr).
8849       return Success(false, E);
8850     }
8851     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8852     return false;
8853   }
8854 
8855   case Builtin::BI__builtin_is_constant_evaluated:
8856     return Success(Info.InConstantContext, E);
8857 
8858   case Builtin::BI__builtin_ctz:
8859   case Builtin::BI__builtin_ctzl:
8860   case Builtin::BI__builtin_ctzll:
8861   case Builtin::BI__builtin_ctzs: {
8862     APSInt Val;
8863     if (!EvaluateInteger(E->getArg(0), Val, Info))
8864       return false;
8865     if (!Val)
8866       return Error(E);
8867 
8868     return Success(Val.countTrailingZeros(), E);
8869   }
8870 
8871   case Builtin::BI__builtin_eh_return_data_regno: {
8872     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8873     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8874     return Success(Operand, E);
8875   }
8876 
8877   case Builtin::BI__builtin_expect:
8878     return Visit(E->getArg(0));
8879 
8880   case Builtin::BI__builtin_ffs:
8881   case Builtin::BI__builtin_ffsl:
8882   case Builtin::BI__builtin_ffsll: {
8883     APSInt Val;
8884     if (!EvaluateInteger(E->getArg(0), Val, Info))
8885       return false;
8886 
8887     unsigned N = Val.countTrailingZeros();
8888     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8889   }
8890 
8891   case Builtin::BI__builtin_fpclassify: {
8892     APFloat Val(0.0);
8893     if (!EvaluateFloat(E->getArg(5), Val, Info))
8894       return false;
8895     unsigned Arg;
8896     switch (Val.getCategory()) {
8897     case APFloat::fcNaN: Arg = 0; break;
8898     case APFloat::fcInfinity: Arg = 1; break;
8899     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8900     case APFloat::fcZero: Arg = 4; break;
8901     }
8902     return Visit(E->getArg(Arg));
8903   }
8904 
8905   case Builtin::BI__builtin_isinf_sign: {
8906     APFloat Val(0.0);
8907     return EvaluateFloat(E->getArg(0), Val, Info) &&
8908            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8909   }
8910 
8911   case Builtin::BI__builtin_isinf: {
8912     APFloat Val(0.0);
8913     return EvaluateFloat(E->getArg(0), Val, Info) &&
8914            Success(Val.isInfinity() ? 1 : 0, E);
8915   }
8916 
8917   case Builtin::BI__builtin_isfinite: {
8918     APFloat Val(0.0);
8919     return EvaluateFloat(E->getArg(0), Val, Info) &&
8920            Success(Val.isFinite() ? 1 : 0, E);
8921   }
8922 
8923   case Builtin::BI__builtin_isnan: {
8924     APFloat Val(0.0);
8925     return EvaluateFloat(E->getArg(0), Val, Info) &&
8926            Success(Val.isNaN() ? 1 : 0, E);
8927   }
8928 
8929   case Builtin::BI__builtin_isnormal: {
8930     APFloat Val(0.0);
8931     return EvaluateFloat(E->getArg(0), Val, Info) &&
8932            Success(Val.isNormal() ? 1 : 0, E);
8933   }
8934 
8935   case Builtin::BI__builtin_parity:
8936   case Builtin::BI__builtin_parityl:
8937   case Builtin::BI__builtin_parityll: {
8938     APSInt Val;
8939     if (!EvaluateInteger(E->getArg(0), Val, Info))
8940       return false;
8941 
8942     return Success(Val.countPopulation() % 2, E);
8943   }
8944 
8945   case Builtin::BI__builtin_popcount:
8946   case Builtin::BI__builtin_popcountl:
8947   case Builtin::BI__builtin_popcountll: {
8948     APSInt Val;
8949     if (!EvaluateInteger(E->getArg(0), Val, Info))
8950       return false;
8951 
8952     return Success(Val.countPopulation(), E);
8953   }
8954 
8955   case Builtin::BIstrlen:
8956   case Builtin::BIwcslen:
8957     // A call to strlen is not a constant expression.
8958     if (Info.getLangOpts().CPlusPlus11)
8959       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8960         << /*isConstexpr*/0 << /*isConstructor*/0
8961         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8962     else
8963       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8964     LLVM_FALLTHROUGH;
8965   case Builtin::BI__builtin_strlen:
8966   case Builtin::BI__builtin_wcslen: {
8967     // As an extension, we support __builtin_strlen() as a constant expression,
8968     // and support folding strlen() to a constant.
8969     LValue String;
8970     if (!EvaluatePointer(E->getArg(0), String, Info))
8971       return false;
8972 
8973     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8974 
8975     // Fast path: if it's a string literal, search the string value.
8976     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8977             String.getLValueBase().dyn_cast<const Expr *>())) {
8978       // The string literal may have embedded null characters. Find the first
8979       // one and truncate there.
8980       StringRef Str = S->getBytes();
8981       int64_t Off = String.Offset.getQuantity();
8982       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
8983           S->getCharByteWidth() == 1 &&
8984           // FIXME: Add fast-path for wchar_t too.
8985           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
8986         Str = Str.substr(Off);
8987 
8988         StringRef::size_type Pos = Str.find(0);
8989         if (Pos != StringRef::npos)
8990           Str = Str.substr(0, Pos);
8991 
8992         return Success(Str.size(), E);
8993       }
8994 
8995       // Fall through to slow path to issue appropriate diagnostic.
8996     }
8997 
8998     // Slow path: scan the bytes of the string looking for the terminating 0.
8999     for (uint64_t Strlen = 0; /**/; ++Strlen) {
9000       APValue Char;
9001       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9002           !Char.isInt())
9003         return false;
9004       if (!Char.getInt())
9005         return Success(Strlen, E);
9006       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9007         return false;
9008     }
9009   }
9010 
9011   case Builtin::BIstrcmp:
9012   case Builtin::BIwcscmp:
9013   case Builtin::BIstrncmp:
9014   case Builtin::BIwcsncmp:
9015   case Builtin::BImemcmp:
9016   case Builtin::BIbcmp:
9017   case Builtin::BIwmemcmp:
9018     // A call to strlen is not a constant expression.
9019     if (Info.getLangOpts().CPlusPlus11)
9020       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9021         << /*isConstexpr*/0 << /*isConstructor*/0
9022         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9023     else
9024       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9025     LLVM_FALLTHROUGH;
9026   case Builtin::BI__builtin_strcmp:
9027   case Builtin::BI__builtin_wcscmp:
9028   case Builtin::BI__builtin_strncmp:
9029   case Builtin::BI__builtin_wcsncmp:
9030   case Builtin::BI__builtin_memcmp:
9031   case Builtin::BI__builtin_bcmp:
9032   case Builtin::BI__builtin_wmemcmp: {
9033     LValue String1, String2;
9034     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9035         !EvaluatePointer(E->getArg(1), String2, Info))
9036       return false;
9037 
9038     uint64_t MaxLength = uint64_t(-1);
9039     if (BuiltinOp != Builtin::BIstrcmp &&
9040         BuiltinOp != Builtin::BIwcscmp &&
9041         BuiltinOp != Builtin::BI__builtin_strcmp &&
9042         BuiltinOp != Builtin::BI__builtin_wcscmp) {
9043       APSInt N;
9044       if (!EvaluateInteger(E->getArg(2), N, Info))
9045         return false;
9046       MaxLength = N.getExtValue();
9047     }
9048 
9049     // Empty substrings compare equal by definition.
9050     if (MaxLength == 0u)
9051       return Success(0, E);
9052 
9053     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9054         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9055         String1.Designator.Invalid || String2.Designator.Invalid)
9056       return false;
9057 
9058     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9059     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9060 
9061     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
9062                      BuiltinOp == Builtin::BIbcmp ||
9063                      BuiltinOp == Builtin::BI__builtin_memcmp ||
9064                      BuiltinOp == Builtin::BI__builtin_bcmp;
9065 
9066     assert(IsRawByte ||
9067            (Info.Ctx.hasSameUnqualifiedType(
9068                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9069             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9070 
9071     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9072       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9073              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9074              Char1.isInt() && Char2.isInt();
9075     };
9076     const auto &AdvanceElems = [&] {
9077       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9078              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9079     };
9080 
9081     if (IsRawByte) {
9082       uint64_t BytesRemaining = MaxLength;
9083       // Pointers to const void may point to objects of incomplete type.
9084       if (CharTy1->isIncompleteType()) {
9085         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9086         return false;
9087       }
9088       if (CharTy2->isIncompleteType()) {
9089         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9090         return false;
9091       }
9092       uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9093       CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9094       // Give up on comparing between elements with disparate widths.
9095       if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9096         return false;
9097       uint64_t BytesPerElement = CharTy1Size.getQuantity();
9098       assert(BytesRemaining && "BytesRemaining should not be zero: the "
9099                                "following loop considers at least one element");
9100       while (true) {
9101         APValue Char1, Char2;
9102         if (!ReadCurElems(Char1, Char2))
9103           return false;
9104         // We have compatible in-memory widths, but a possible type and
9105         // (for `bool`) internal representation mismatch.
9106         // Assuming two's complement representation, including 0 for `false` and
9107         // 1 for `true`, we can check an appropriate number of elements for
9108         // equality even if they are not byte-sized.
9109         APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9110         APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9111         if (Char1InMem.ne(Char2InMem)) {
9112           // If the elements are byte-sized, then we can produce a three-way
9113           // comparison result in a straightforward manner.
9114           if (BytesPerElement == 1u) {
9115             // memcmp always compares unsigned chars.
9116             return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9117           }
9118           // The result is byte-order sensitive, and we have multibyte elements.
9119           // FIXME: We can compare the remaining bytes in the correct order.
9120           return false;
9121         }
9122         if (!AdvanceElems())
9123           return false;
9124         if (BytesRemaining <= BytesPerElement)
9125           break;
9126         BytesRemaining -= BytesPerElement;
9127       }
9128       // Enough elements are equal to account for the memcmp limit.
9129       return Success(0, E);
9130     }
9131 
9132     bool StopAtNull =
9133         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9134          BuiltinOp != Builtin::BIwmemcmp &&
9135          BuiltinOp != Builtin::BI__builtin_memcmp &&
9136          BuiltinOp != Builtin::BI__builtin_bcmp &&
9137          BuiltinOp != Builtin::BI__builtin_wmemcmp);
9138     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9139                   BuiltinOp == Builtin::BIwcsncmp ||
9140                   BuiltinOp == Builtin::BIwmemcmp ||
9141                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
9142                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9143                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
9144 
9145     for (; MaxLength; --MaxLength) {
9146       APValue Char1, Char2;
9147       if (!ReadCurElems(Char1, Char2))
9148         return false;
9149       if (Char1.getInt() != Char2.getInt()) {
9150         if (IsWide) // wmemcmp compares with wchar_t signedness.
9151           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9152         // memcmp always compares unsigned chars.
9153         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9154       }
9155       if (StopAtNull && !Char1.getInt())
9156         return Success(0, E);
9157       assert(!(StopAtNull && !Char2.getInt()));
9158       if (!AdvanceElems())
9159         return false;
9160     }
9161     // We hit the strncmp / memcmp limit.
9162     return Success(0, E);
9163   }
9164 
9165   case Builtin::BI__atomic_always_lock_free:
9166   case Builtin::BI__atomic_is_lock_free:
9167   case Builtin::BI__c11_atomic_is_lock_free: {
9168     APSInt SizeVal;
9169     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9170       return false;
9171 
9172     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9173     // of two less than the maximum inline atomic width, we know it is
9174     // lock-free.  If the size isn't a power of two, or greater than the
9175     // maximum alignment where we promote atomics, we know it is not lock-free
9176     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
9177     // the answer can only be determined at runtime; for example, 16-byte
9178     // atomics have lock-free implementations on some, but not all,
9179     // x86-64 processors.
9180 
9181     // Check power-of-two.
9182     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
9183     if (Size.isPowerOfTwo()) {
9184       // Check against inlining width.
9185       unsigned InlineWidthBits =
9186           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9187       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9188         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9189             Size == CharUnits::One() ||
9190             E->getArg(1)->isNullPointerConstant(Info.Ctx,
9191                                                 Expr::NPC_NeverValueDependent))
9192           // OK, we will inline appropriately-aligned operations of this size,
9193           // and _Atomic(T) is appropriately-aligned.
9194           return Success(1, E);
9195 
9196         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9197           castAs<PointerType>()->getPointeeType();
9198         if (!PointeeType->isIncompleteType() &&
9199             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9200           // OK, we will inline operations on this object.
9201           return Success(1, E);
9202         }
9203       }
9204     }
9205 
9206     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9207         Success(0, E) : Error(E);
9208   }
9209   case Builtin::BIomp_is_initial_device:
9210     // We can decide statically which value the runtime would return if called.
9211     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
9212   case Builtin::BI__builtin_add_overflow:
9213   case Builtin::BI__builtin_sub_overflow:
9214   case Builtin::BI__builtin_mul_overflow:
9215   case Builtin::BI__builtin_sadd_overflow:
9216   case Builtin::BI__builtin_uadd_overflow:
9217   case Builtin::BI__builtin_uaddl_overflow:
9218   case Builtin::BI__builtin_uaddll_overflow:
9219   case Builtin::BI__builtin_usub_overflow:
9220   case Builtin::BI__builtin_usubl_overflow:
9221   case Builtin::BI__builtin_usubll_overflow:
9222   case Builtin::BI__builtin_umul_overflow:
9223   case Builtin::BI__builtin_umull_overflow:
9224   case Builtin::BI__builtin_umulll_overflow:
9225   case Builtin::BI__builtin_saddl_overflow:
9226   case Builtin::BI__builtin_saddll_overflow:
9227   case Builtin::BI__builtin_ssub_overflow:
9228   case Builtin::BI__builtin_ssubl_overflow:
9229   case Builtin::BI__builtin_ssubll_overflow:
9230   case Builtin::BI__builtin_smul_overflow:
9231   case Builtin::BI__builtin_smull_overflow:
9232   case Builtin::BI__builtin_smulll_overflow: {
9233     LValue ResultLValue;
9234     APSInt LHS, RHS;
9235 
9236     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9237     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9238         !EvaluateInteger(E->getArg(1), RHS, Info) ||
9239         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9240       return false;
9241 
9242     APSInt Result;
9243     bool DidOverflow = false;
9244 
9245     // If the types don't have to match, enlarge all 3 to the largest of them.
9246     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9247         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9248         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9249       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9250                       ResultType->isSignedIntegerOrEnumerationType();
9251       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9252                       ResultType->isSignedIntegerOrEnumerationType();
9253       uint64_t LHSSize = LHS.getBitWidth();
9254       uint64_t RHSSize = RHS.getBitWidth();
9255       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9256       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9257 
9258       // Add an additional bit if the signedness isn't uniformly agreed to. We
9259       // could do this ONLY if there is a signed and an unsigned that both have
9260       // MaxBits, but the code to check that is pretty nasty.  The issue will be
9261       // caught in the shrink-to-result later anyway.
9262       if (IsSigned && !AllSigned)
9263         ++MaxBits;
9264 
9265       LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
9266                    !IsSigned);
9267       RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
9268                    !IsSigned);
9269       Result = APSInt(MaxBits, !IsSigned);
9270     }
9271 
9272     // Find largest int.
9273     switch (BuiltinOp) {
9274     default:
9275       llvm_unreachable("Invalid value for BuiltinOp");
9276     case Builtin::BI__builtin_add_overflow:
9277     case Builtin::BI__builtin_sadd_overflow:
9278     case Builtin::BI__builtin_saddl_overflow:
9279     case Builtin::BI__builtin_saddll_overflow:
9280     case Builtin::BI__builtin_uadd_overflow:
9281     case Builtin::BI__builtin_uaddl_overflow:
9282     case Builtin::BI__builtin_uaddll_overflow:
9283       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9284                               : LHS.uadd_ov(RHS, DidOverflow);
9285       break;
9286     case Builtin::BI__builtin_sub_overflow:
9287     case Builtin::BI__builtin_ssub_overflow:
9288     case Builtin::BI__builtin_ssubl_overflow:
9289     case Builtin::BI__builtin_ssubll_overflow:
9290     case Builtin::BI__builtin_usub_overflow:
9291     case Builtin::BI__builtin_usubl_overflow:
9292     case Builtin::BI__builtin_usubll_overflow:
9293       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9294                               : LHS.usub_ov(RHS, DidOverflow);
9295       break;
9296     case Builtin::BI__builtin_mul_overflow:
9297     case Builtin::BI__builtin_smul_overflow:
9298     case Builtin::BI__builtin_smull_overflow:
9299     case Builtin::BI__builtin_smulll_overflow:
9300     case Builtin::BI__builtin_umul_overflow:
9301     case Builtin::BI__builtin_umull_overflow:
9302     case Builtin::BI__builtin_umulll_overflow:
9303       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
9304                               : LHS.umul_ov(RHS, DidOverflow);
9305       break;
9306     }
9307 
9308     // In the case where multiple sizes are allowed, truncate and see if
9309     // the values are the same.
9310     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9311         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9312         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9313       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
9314       // since it will give us the behavior of a TruncOrSelf in the case where
9315       // its parameter <= its size.  We previously set Result to be at least the
9316       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
9317       // will work exactly like TruncOrSelf.
9318       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
9319       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
9320 
9321       if (!APSInt::isSameValue(Temp, Result))
9322         DidOverflow = true;
9323       Result = Temp;
9324     }
9325 
9326     APValue APV{Result};
9327     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
9328       return false;
9329     return Success(DidOverflow, E);
9330   }
9331   }
9332 }
9333 
9334 /// Determine whether this is a pointer past the end of the complete
9335 /// object referred to by the lvalue.
9336 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
9337                                             const LValue &LV) {
9338   // A null pointer can be viewed as being "past the end" but we don't
9339   // choose to look at it that way here.
9340   if (!LV.getLValueBase())
9341     return false;
9342 
9343   // If the designator is valid and refers to a subobject, we're not pointing
9344   // past the end.
9345   if (!LV.getLValueDesignator().Invalid &&
9346       !LV.getLValueDesignator().isOnePastTheEnd())
9347     return false;
9348 
9349   // A pointer to an incomplete type might be past-the-end if the type's size is
9350   // zero.  We cannot tell because the type is incomplete.
9351   QualType Ty = getType(LV.getLValueBase());
9352   if (Ty->isIncompleteType())
9353     return true;
9354 
9355   // We're a past-the-end pointer if we point to the byte after the object,
9356   // no matter what our type or path is.
9357   auto Size = Ctx.getTypeSizeInChars(Ty);
9358   return LV.getLValueOffset() == Size;
9359 }
9360 
9361 namespace {
9362 
9363 /// Data recursive integer evaluator of certain binary operators.
9364 ///
9365 /// We use a data recursive algorithm for binary operators so that we are able
9366 /// to handle extreme cases of chained binary operators without causing stack
9367 /// overflow.
9368 class DataRecursiveIntBinOpEvaluator {
9369   struct EvalResult {
9370     APValue Val;
9371     bool Failed;
9372 
9373     EvalResult() : Failed(false) { }
9374 
9375     void swap(EvalResult &RHS) {
9376       Val.swap(RHS.Val);
9377       Failed = RHS.Failed;
9378       RHS.Failed = false;
9379     }
9380   };
9381 
9382   struct Job {
9383     const Expr *E;
9384     EvalResult LHSResult; // meaningful only for binary operator expression.
9385     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
9386 
9387     Job() = default;
9388     Job(Job &&) = default;
9389 
9390     void startSpeculativeEval(EvalInfo &Info) {
9391       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
9392     }
9393 
9394   private:
9395     SpeculativeEvaluationRAII SpecEvalRAII;
9396   };
9397 
9398   SmallVector<Job, 16> Queue;
9399 
9400   IntExprEvaluator &IntEval;
9401   EvalInfo &Info;
9402   APValue &FinalResult;
9403 
9404 public:
9405   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
9406     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
9407 
9408   /// True if \param E is a binary operator that we are going to handle
9409   /// data recursively.
9410   /// We handle binary operators that are comma, logical, or that have operands
9411   /// with integral or enumeration type.
9412   static bool shouldEnqueue(const BinaryOperator *E) {
9413     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
9414            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
9415             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9416             E->getRHS()->getType()->isIntegralOrEnumerationType());
9417   }
9418 
9419   bool Traverse(const BinaryOperator *E) {
9420     enqueue(E);
9421     EvalResult PrevResult;
9422     while (!Queue.empty())
9423       process(PrevResult);
9424 
9425     if (PrevResult.Failed) return false;
9426 
9427     FinalResult.swap(PrevResult.Val);
9428     return true;
9429   }
9430 
9431 private:
9432   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9433     return IntEval.Success(Value, E, Result);
9434   }
9435   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
9436     return IntEval.Success(Value, E, Result);
9437   }
9438   bool Error(const Expr *E) {
9439     return IntEval.Error(E);
9440   }
9441   bool Error(const Expr *E, diag::kind D) {
9442     return IntEval.Error(E, D);
9443   }
9444 
9445   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
9446     return Info.CCEDiag(E, D);
9447   }
9448 
9449   // Returns true if visiting the RHS is necessary, false otherwise.
9450   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
9451                          bool &SuppressRHSDiags);
9452 
9453   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9454                   const BinaryOperator *E, APValue &Result);
9455 
9456   void EvaluateExpr(const Expr *E, EvalResult &Result) {
9457     Result.Failed = !Evaluate(Result.Val, Info, E);
9458     if (Result.Failed)
9459       Result.Val = APValue();
9460   }
9461 
9462   void process(EvalResult &Result);
9463 
9464   void enqueue(const Expr *E) {
9465     E = E->IgnoreParens();
9466     Queue.resize(Queue.size()+1);
9467     Queue.back().E = E;
9468     Queue.back().Kind = Job::AnyExprKind;
9469   }
9470 };
9471 
9472 }
9473 
9474 bool DataRecursiveIntBinOpEvaluator::
9475        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
9476                          bool &SuppressRHSDiags) {
9477   if (E->getOpcode() == BO_Comma) {
9478     // Ignore LHS but note if we could not evaluate it.
9479     if (LHSResult.Failed)
9480       return Info.noteSideEffect();
9481     return true;
9482   }
9483 
9484   if (E->isLogicalOp()) {
9485     bool LHSAsBool;
9486     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
9487       // We were able to evaluate the LHS, see if we can get away with not
9488       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
9489       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
9490         Success(LHSAsBool, E, LHSResult.Val);
9491         return false; // Ignore RHS
9492       }
9493     } else {
9494       LHSResult.Failed = true;
9495 
9496       // Since we weren't able to evaluate the left hand side, it
9497       // might have had side effects.
9498       if (!Info.noteSideEffect())
9499         return false;
9500 
9501       // We can't evaluate the LHS; however, sometimes the result
9502       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9503       // Don't ignore RHS and suppress diagnostics from this arm.
9504       SuppressRHSDiags = true;
9505     }
9506 
9507     return true;
9508   }
9509 
9510   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9511          E->getRHS()->getType()->isIntegralOrEnumerationType());
9512 
9513   if (LHSResult.Failed && !Info.noteFailure())
9514     return false; // Ignore RHS;
9515 
9516   return true;
9517 }
9518 
9519 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
9520                                     bool IsSub) {
9521   // Compute the new offset in the appropriate width, wrapping at 64 bits.
9522   // FIXME: When compiling for a 32-bit target, we should use 32-bit
9523   // offsets.
9524   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
9525   CharUnits &Offset = LVal.getLValueOffset();
9526   uint64_t Offset64 = Offset.getQuantity();
9527   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
9528   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
9529                                          : Offset64 + Index64);
9530 }
9531 
9532 bool DataRecursiveIntBinOpEvaluator::
9533        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9534                   const BinaryOperator *E, APValue &Result) {
9535   if (E->getOpcode() == BO_Comma) {
9536     if (RHSResult.Failed)
9537       return false;
9538     Result = RHSResult.Val;
9539     return true;
9540   }
9541 
9542   if (E->isLogicalOp()) {
9543     bool lhsResult, rhsResult;
9544     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
9545     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
9546 
9547     if (LHSIsOK) {
9548       if (RHSIsOK) {
9549         if (E->getOpcode() == BO_LOr)
9550           return Success(lhsResult || rhsResult, E, Result);
9551         else
9552           return Success(lhsResult && rhsResult, E, Result);
9553       }
9554     } else {
9555       if (RHSIsOK) {
9556         // We can't evaluate the LHS; however, sometimes the result
9557         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9558         if (rhsResult == (E->getOpcode() == BO_LOr))
9559           return Success(rhsResult, E, Result);
9560       }
9561     }
9562 
9563     return false;
9564   }
9565 
9566   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9567          E->getRHS()->getType()->isIntegralOrEnumerationType());
9568 
9569   if (LHSResult.Failed || RHSResult.Failed)
9570     return false;
9571 
9572   const APValue &LHSVal = LHSResult.Val;
9573   const APValue &RHSVal = RHSResult.Val;
9574 
9575   // Handle cases like (unsigned long)&a + 4.
9576   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
9577     Result = LHSVal;
9578     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
9579     return true;
9580   }
9581 
9582   // Handle cases like 4 + (unsigned long)&a
9583   if (E->getOpcode() == BO_Add &&
9584       RHSVal.isLValue() && LHSVal.isInt()) {
9585     Result = RHSVal;
9586     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
9587     return true;
9588   }
9589 
9590   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
9591     // Handle (intptr_t)&&A - (intptr_t)&&B.
9592     if (!LHSVal.getLValueOffset().isZero() ||
9593         !RHSVal.getLValueOffset().isZero())
9594       return false;
9595     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
9596     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
9597     if (!LHSExpr || !RHSExpr)
9598       return false;
9599     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9600     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9601     if (!LHSAddrExpr || !RHSAddrExpr)
9602       return false;
9603     // Make sure both labels come from the same function.
9604     if (LHSAddrExpr->getLabel()->getDeclContext() !=
9605         RHSAddrExpr->getLabel()->getDeclContext())
9606       return false;
9607     Result = APValue(LHSAddrExpr, RHSAddrExpr);
9608     return true;
9609   }
9610 
9611   // All the remaining cases expect both operands to be an integer
9612   if (!LHSVal.isInt() || !RHSVal.isInt())
9613     return Error(E);
9614 
9615   // Set up the width and signedness manually, in case it can't be deduced
9616   // from the operation we're performing.
9617   // FIXME: Don't do this in the cases where we can deduce it.
9618   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9619                E->getType()->isUnsignedIntegerOrEnumerationType());
9620   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9621                          RHSVal.getInt(), Value))
9622     return false;
9623   return Success(Value, E, Result);
9624 }
9625 
9626 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
9627   Job &job = Queue.back();
9628 
9629   switch (job.Kind) {
9630     case Job::AnyExprKind: {
9631       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9632         if (shouldEnqueue(Bop)) {
9633           job.Kind = Job::BinOpKind;
9634           enqueue(Bop->getLHS());
9635           return;
9636         }
9637       }
9638 
9639       EvaluateExpr(job.E, Result);
9640       Queue.pop_back();
9641       return;
9642     }
9643 
9644     case Job::BinOpKind: {
9645       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9646       bool SuppressRHSDiags = false;
9647       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
9648         Queue.pop_back();
9649         return;
9650       }
9651       if (SuppressRHSDiags)
9652         job.startSpeculativeEval(Info);
9653       job.LHSResult.swap(Result);
9654       job.Kind = Job::BinOpVisitedLHSKind;
9655       enqueue(Bop->getRHS());
9656       return;
9657     }
9658 
9659     case Job::BinOpVisitedLHSKind: {
9660       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9661       EvalResult RHS;
9662       RHS.swap(Result);
9663       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
9664       Queue.pop_back();
9665       return;
9666     }
9667   }
9668 
9669   llvm_unreachable("Invalid Job::Kind!");
9670 }
9671 
9672 namespace {
9673 /// Used when we determine that we should fail, but can keep evaluating prior to
9674 /// noting that we had a failure.
9675 class DelayedNoteFailureRAII {
9676   EvalInfo &Info;
9677   bool NoteFailure;
9678 
9679 public:
9680   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9681       : Info(Info), NoteFailure(NoteFailure) {}
9682   ~DelayedNoteFailureRAII() {
9683     if (NoteFailure) {
9684       bool ContinueAfterFailure = Info.noteFailure();
9685       (void)ContinueAfterFailure;
9686       assert(ContinueAfterFailure &&
9687              "Shouldn't have kept evaluating on failure.");
9688     }
9689   }
9690 };
9691 }
9692 
9693 template <class SuccessCB, class AfterCB>
9694 static bool
9695 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9696                                  SuccessCB &&Success, AfterCB &&DoAfter) {
9697   assert(E->isComparisonOp() && "expected comparison operator");
9698   assert((E->getOpcode() == BO_Cmp ||
9699           E->getType()->isIntegralOrEnumerationType()) &&
9700          "unsupported binary expression evaluation");
9701   auto Error = [&](const Expr *E) {
9702     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9703     return false;
9704   };
9705 
9706   using CCR = ComparisonCategoryResult;
9707   bool IsRelational = E->isRelationalOp();
9708   bool IsEquality = E->isEqualityOp();
9709   if (E->getOpcode() == BO_Cmp) {
9710     const ComparisonCategoryInfo &CmpInfo =
9711         Info.Ctx.CompCategories.getInfoForType(E->getType());
9712     IsRelational = CmpInfo.isOrdered();
9713     IsEquality = CmpInfo.isEquality();
9714   }
9715 
9716   QualType LHSTy = E->getLHS()->getType();
9717   QualType RHSTy = E->getRHS()->getType();
9718 
9719   if (LHSTy->isIntegralOrEnumerationType() &&
9720       RHSTy->isIntegralOrEnumerationType()) {
9721     APSInt LHS, RHS;
9722     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9723     if (!LHSOK && !Info.noteFailure())
9724       return false;
9725     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9726       return false;
9727     if (LHS < RHS)
9728       return Success(CCR::Less, E);
9729     if (LHS > RHS)
9730       return Success(CCR::Greater, E);
9731     return Success(CCR::Equal, E);
9732   }
9733 
9734   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
9735     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
9736     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
9737 
9738     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
9739     if (!LHSOK && !Info.noteFailure())
9740       return false;
9741     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
9742       return false;
9743     if (LHSFX < RHSFX)
9744       return Success(CCR::Less, E);
9745     if (LHSFX > RHSFX)
9746       return Success(CCR::Greater, E);
9747     return Success(CCR::Equal, E);
9748   }
9749 
9750   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
9751     ComplexValue LHS, RHS;
9752     bool LHSOK;
9753     if (E->isAssignmentOp()) {
9754       LValue LV;
9755       EvaluateLValue(E->getLHS(), LV, Info);
9756       LHSOK = false;
9757     } else if (LHSTy->isRealFloatingType()) {
9758       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9759       if (LHSOK) {
9760         LHS.makeComplexFloat();
9761         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9762       }
9763     } else {
9764       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9765     }
9766     if (!LHSOK && !Info.noteFailure())
9767       return false;
9768 
9769     if (E->getRHS()->getType()->isRealFloatingType()) {
9770       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9771         return false;
9772       RHS.makeComplexFloat();
9773       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9774     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9775       return false;
9776 
9777     if (LHS.isComplexFloat()) {
9778       APFloat::cmpResult CR_r =
9779         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
9780       APFloat::cmpResult CR_i =
9781         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
9782       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9783       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
9784     } else {
9785       assert(IsEquality && "invalid complex comparison");
9786       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9787                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
9788       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
9789     }
9790   }
9791 
9792   if (LHSTy->isRealFloatingType() &&
9793       RHSTy->isRealFloatingType()) {
9794     APFloat RHS(0.0), LHS(0.0);
9795 
9796     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
9797     if (!LHSOK && !Info.noteFailure())
9798       return false;
9799 
9800     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
9801       return false;
9802 
9803     assert(E->isComparisonOp() && "Invalid binary operator!");
9804     auto GetCmpRes = [&]() {
9805       switch (LHS.compare(RHS)) {
9806       case APFloat::cmpEqual:
9807         return CCR::Equal;
9808       case APFloat::cmpLessThan:
9809         return CCR::Less;
9810       case APFloat::cmpGreaterThan:
9811         return CCR::Greater;
9812       case APFloat::cmpUnordered:
9813         return CCR::Unordered;
9814       }
9815       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
9816     };
9817     return Success(GetCmpRes(), E);
9818   }
9819 
9820   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
9821     LValue LHSValue, RHSValue;
9822 
9823     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9824     if (!LHSOK && !Info.noteFailure())
9825       return false;
9826 
9827     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9828       return false;
9829 
9830     // Reject differing bases from the normal codepath; we special-case
9831     // comparisons to null.
9832     if (!HasSameBase(LHSValue, RHSValue)) {
9833       // Inequalities and subtractions between unrelated pointers have
9834       // unspecified or undefined behavior.
9835       if (!IsEquality)
9836         return Error(E);
9837       // A constant address may compare equal to the address of a symbol.
9838       // The one exception is that address of an object cannot compare equal
9839       // to a null pointer constant.
9840       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9841           (!RHSValue.Base && !RHSValue.Offset.isZero()))
9842         return Error(E);
9843       // It's implementation-defined whether distinct literals will have
9844       // distinct addresses. In clang, the result of such a comparison is
9845       // unspecified, so it is not a constant expression. However, we do know
9846       // that the address of a literal will be non-null.
9847       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9848           LHSValue.Base && RHSValue.Base)
9849         return Error(E);
9850       // We can't tell whether weak symbols will end up pointing to the same
9851       // object.
9852       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9853         return Error(E);
9854       // We can't compare the address of the start of one object with the
9855       // past-the-end address of another object, per C++ DR1652.
9856       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9857            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9858           (RHSValue.Base && RHSValue.Offset.isZero() &&
9859            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9860         return Error(E);
9861       // We can't tell whether an object is at the same address as another
9862       // zero sized object.
9863       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9864           (LHSValue.Base && isZeroSized(RHSValue)))
9865         return Error(E);
9866       return Success(CCR::Nonequal, E);
9867     }
9868 
9869     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9870     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9871 
9872     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9873     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9874 
9875     // C++11 [expr.rel]p3:
9876     //   Pointers to void (after pointer conversions) can be compared, with a
9877     //   result defined as follows: If both pointers represent the same
9878     //   address or are both the null pointer value, the result is true if the
9879     //   operator is <= or >= and false otherwise; otherwise the result is
9880     //   unspecified.
9881     // We interpret this as applying to pointers to *cv* void.
9882     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9883       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
9884 
9885     // C++11 [expr.rel]p2:
9886     // - If two pointers point to non-static data members of the same object,
9887     //   or to subobjects or array elements fo such members, recursively, the
9888     //   pointer to the later declared member compares greater provided the
9889     //   two members have the same access control and provided their class is
9890     //   not a union.
9891     //   [...]
9892     // - Otherwise pointer comparisons are unspecified.
9893     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9894       bool WasArrayIndex;
9895       unsigned Mismatch = FindDesignatorMismatch(
9896           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9897       // At the point where the designators diverge, the comparison has a
9898       // specified value if:
9899       //  - we are comparing array indices
9900       //  - we are comparing fields of a union, or fields with the same access
9901       // Otherwise, the result is unspecified and thus the comparison is not a
9902       // constant expression.
9903       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9904           Mismatch < RHSDesignator.Entries.size()) {
9905         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9906         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9907         if (!LF && !RF)
9908           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9909         else if (!LF)
9910           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9911               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9912               << RF->getParent() << RF;
9913         else if (!RF)
9914           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9915               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9916               << LF->getParent() << LF;
9917         else if (!LF->getParent()->isUnion() &&
9918                  LF->getAccess() != RF->getAccess())
9919           Info.CCEDiag(E,
9920                        diag::note_constexpr_pointer_comparison_differing_access)
9921               << LF << LF->getAccess() << RF << RF->getAccess()
9922               << LF->getParent();
9923       }
9924     }
9925 
9926     // The comparison here must be unsigned, and performed with the same
9927     // width as the pointer.
9928     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9929     uint64_t CompareLHS = LHSOffset.getQuantity();
9930     uint64_t CompareRHS = RHSOffset.getQuantity();
9931     assert(PtrSize <= 64 && "Unexpected pointer width");
9932     uint64_t Mask = ~0ULL >> (64 - PtrSize);
9933     CompareLHS &= Mask;
9934     CompareRHS &= Mask;
9935 
9936     // If there is a base and this is a relational operator, we can only
9937     // compare pointers within the object in question; otherwise, the result
9938     // depends on where the object is located in memory.
9939     if (!LHSValue.Base.isNull() && IsRelational) {
9940       QualType BaseTy = getType(LHSValue.Base);
9941       if (BaseTy->isIncompleteType())
9942         return Error(E);
9943       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9944       uint64_t OffsetLimit = Size.getQuantity();
9945       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9946         return Error(E);
9947     }
9948 
9949     if (CompareLHS < CompareRHS)
9950       return Success(CCR::Less, E);
9951     if (CompareLHS > CompareRHS)
9952       return Success(CCR::Greater, E);
9953     return Success(CCR::Equal, E);
9954   }
9955 
9956   if (LHSTy->isMemberPointerType()) {
9957     assert(IsEquality && "unexpected member pointer operation");
9958     assert(RHSTy->isMemberPointerType() && "invalid comparison");
9959 
9960     MemberPtr LHSValue, RHSValue;
9961 
9962     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
9963     if (!LHSOK && !Info.noteFailure())
9964       return false;
9965 
9966     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9967       return false;
9968 
9969     // C++11 [expr.eq]p2:
9970     //   If both operands are null, they compare equal. Otherwise if only one is
9971     //   null, they compare unequal.
9972     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9973       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
9974       return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9975     }
9976 
9977     //   Otherwise if either is a pointer to a virtual member function, the
9978     //   result is unspecified.
9979     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9980       if (MD->isVirtual())
9981         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9982     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9983       if (MD->isVirtual())
9984         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9985 
9986     //   Otherwise they compare equal if and only if they would refer to the
9987     //   same member of the same most derived object or the same subobject if
9988     //   they were dereferenced with a hypothetical object of the associated
9989     //   class type.
9990     bool Equal = LHSValue == RHSValue;
9991     return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9992   }
9993 
9994   if (LHSTy->isNullPtrType()) {
9995     assert(E->isComparisonOp() && "unexpected nullptr operation");
9996     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9997     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9998     // are compared, the result is true of the operator is <=, >= or ==, and
9999     // false otherwise.
10000     return Success(CCR::Equal, E);
10001   }
10002 
10003   return DoAfter();
10004 }
10005 
10006 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10007   if (!CheckLiteralType(Info, E))
10008     return false;
10009 
10010   auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10011                        const BinaryOperator *E) {
10012     // Evaluation succeeded. Lookup the information for the comparison category
10013     // type and fetch the VarDecl for the result.
10014     const ComparisonCategoryInfo &CmpInfo =
10015         Info.Ctx.CompCategories.getInfoForType(E->getType());
10016     const VarDecl *VD =
10017         CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10018     // Check and evaluate the result as a constant expression.
10019     LValue LV;
10020     LV.set(VD);
10021     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10022       return false;
10023     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10024   };
10025   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10026     return ExprEvaluatorBaseTy::VisitBinCmp(E);
10027   });
10028 }
10029 
10030 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10031   // We don't call noteFailure immediately because the assignment happens after
10032   // we evaluate LHS and RHS.
10033   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10034     return Error(E);
10035 
10036   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10037   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10038     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10039 
10040   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10041           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
10042          "DataRecursiveIntBinOpEvaluator should have handled integral types");
10043 
10044   if (E->isComparisonOp()) {
10045     // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10046     // comparisons and then translating the result.
10047     auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10048                          const BinaryOperator *E) {
10049       using CCR = ComparisonCategoryResult;
10050       bool IsEqual   = ResKind == CCR::Equal,
10051            IsLess    = ResKind == CCR::Less,
10052            IsGreater = ResKind == CCR::Greater;
10053       auto Op = E->getOpcode();
10054       switch (Op) {
10055       default:
10056         llvm_unreachable("unsupported binary operator");
10057       case BO_EQ:
10058       case BO_NE:
10059         return Success(IsEqual == (Op == BO_EQ), E);
10060       case BO_LT: return Success(IsLess, E);
10061       case BO_GT: return Success(IsGreater, E);
10062       case BO_LE: return Success(IsEqual || IsLess, E);
10063       case BO_GE: return Success(IsEqual || IsGreater, E);
10064       }
10065     };
10066     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10067       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10068     });
10069   }
10070 
10071   QualType LHSTy = E->getLHS()->getType();
10072   QualType RHSTy = E->getRHS()->getType();
10073 
10074   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10075       E->getOpcode() == BO_Sub) {
10076     LValue LHSValue, RHSValue;
10077 
10078     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10079     if (!LHSOK && !Info.noteFailure())
10080       return false;
10081 
10082     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10083       return false;
10084 
10085     // Reject differing bases from the normal codepath; we special-case
10086     // comparisons to null.
10087     if (!HasSameBase(LHSValue, RHSValue)) {
10088       // Handle &&A - &&B.
10089       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10090         return Error(E);
10091       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10092       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10093       if (!LHSExpr || !RHSExpr)
10094         return Error(E);
10095       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10096       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10097       if (!LHSAddrExpr || !RHSAddrExpr)
10098         return Error(E);
10099       // Make sure both labels come from the same function.
10100       if (LHSAddrExpr->getLabel()->getDeclContext() !=
10101           RHSAddrExpr->getLabel()->getDeclContext())
10102         return Error(E);
10103       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10104     }
10105     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10106     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10107 
10108     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10109     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10110 
10111     // C++11 [expr.add]p6:
10112     //   Unless both pointers point to elements of the same array object, or
10113     //   one past the last element of the array object, the behavior is
10114     //   undefined.
10115     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10116         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10117                                 RHSDesignator))
10118       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10119 
10120     QualType Type = E->getLHS()->getType();
10121     QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10122 
10123     CharUnits ElementSize;
10124     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10125       return false;
10126 
10127     // As an extension, a type may have zero size (empty struct or union in
10128     // C, array of zero length). Pointer subtraction in such cases has
10129     // undefined behavior, so is not constant.
10130     if (ElementSize.isZero()) {
10131       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10132           << ElementType;
10133       return false;
10134     }
10135 
10136     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10137     // and produce incorrect results when it overflows. Such behavior
10138     // appears to be non-conforming, but is common, so perhaps we should
10139     // assume the standard intended for such cases to be undefined behavior
10140     // and check for them.
10141 
10142     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10143     // overflow in the final conversion to ptrdiff_t.
10144     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10145     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10146     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10147                     false);
10148     APSInt TrueResult = (LHS - RHS) / ElemSize;
10149     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10150 
10151     if (Result.extend(65) != TrueResult &&
10152         !HandleOverflow(Info, E, TrueResult, E->getType()))
10153       return false;
10154     return Success(Result, E);
10155   }
10156 
10157   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10158 }
10159 
10160 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10161 /// a result as the expression's type.
10162 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10163                                     const UnaryExprOrTypeTraitExpr *E) {
10164   switch(E->getKind()) {
10165   case UETT_PreferredAlignOf:
10166   case UETT_AlignOf: {
10167     if (E->isArgumentType())
10168       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10169                      E);
10170     else
10171       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10172                      E);
10173   }
10174 
10175   case UETT_VecStep: {
10176     QualType Ty = E->getTypeOfArgument();
10177 
10178     if (Ty->isVectorType()) {
10179       unsigned n = Ty->castAs<VectorType>()->getNumElements();
10180 
10181       // The vec_step built-in functions that take a 3-component
10182       // vector return 4. (OpenCL 1.1 spec 6.11.12)
10183       if (n == 3)
10184         n = 4;
10185 
10186       return Success(n, E);
10187     } else
10188       return Success(1, E);
10189   }
10190 
10191   case UETT_SizeOf: {
10192     QualType SrcTy = E->getTypeOfArgument();
10193     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10194     //   the result is the size of the referenced type."
10195     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10196       SrcTy = Ref->getPointeeType();
10197 
10198     CharUnits Sizeof;
10199     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
10200       return false;
10201     return Success(Sizeof, E);
10202   }
10203   case UETT_OpenMPRequiredSimdAlign:
10204     assert(E->isArgumentType());
10205     return Success(
10206         Info.Ctx.toCharUnitsFromBits(
10207                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10208             .getQuantity(),
10209         E);
10210   }
10211 
10212   llvm_unreachable("unknown expr/type trait");
10213 }
10214 
10215 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
10216   CharUnits Result;
10217   unsigned n = OOE->getNumComponents();
10218   if (n == 0)
10219     return Error(OOE);
10220   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
10221   for (unsigned i = 0; i != n; ++i) {
10222     OffsetOfNode ON = OOE->getComponent(i);
10223     switch (ON.getKind()) {
10224     case OffsetOfNode::Array: {
10225       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
10226       APSInt IdxResult;
10227       if (!EvaluateInteger(Idx, IdxResult, Info))
10228         return false;
10229       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10230       if (!AT)
10231         return Error(OOE);
10232       CurrentType = AT->getElementType();
10233       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10234       Result += IdxResult.getSExtValue() * ElementSize;
10235       break;
10236     }
10237 
10238     case OffsetOfNode::Field: {
10239       FieldDecl *MemberDecl = ON.getField();
10240       const RecordType *RT = CurrentType->getAs<RecordType>();
10241       if (!RT)
10242         return Error(OOE);
10243       RecordDecl *RD = RT->getDecl();
10244       if (RD->isInvalidDecl()) return false;
10245       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10246       unsigned i = MemberDecl->getFieldIndex();
10247       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
10248       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
10249       CurrentType = MemberDecl->getType().getNonReferenceType();
10250       break;
10251     }
10252 
10253     case OffsetOfNode::Identifier:
10254       llvm_unreachable("dependent __builtin_offsetof");
10255 
10256     case OffsetOfNode::Base: {
10257       CXXBaseSpecifier *BaseSpec = ON.getBase();
10258       if (BaseSpec->isVirtual())
10259         return Error(OOE);
10260 
10261       // Find the layout of the class whose base we are looking into.
10262       const RecordType *RT = CurrentType->getAs<RecordType>();
10263       if (!RT)
10264         return Error(OOE);
10265       RecordDecl *RD = RT->getDecl();
10266       if (RD->isInvalidDecl()) return false;
10267       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10268 
10269       // Find the base class itself.
10270       CurrentType = BaseSpec->getType();
10271       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10272       if (!BaseRT)
10273         return Error(OOE);
10274 
10275       // Add the offset to the base.
10276       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
10277       break;
10278     }
10279     }
10280   }
10281   return Success(Result, OOE);
10282 }
10283 
10284 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10285   switch (E->getOpcode()) {
10286   default:
10287     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10288     // See C99 6.6p3.
10289     return Error(E);
10290   case UO_Extension:
10291     // FIXME: Should extension allow i-c-e extension expressions in its scope?
10292     // If so, we could clear the diagnostic ID.
10293     return Visit(E->getSubExpr());
10294   case UO_Plus:
10295     // The result is just the value.
10296     return Visit(E->getSubExpr());
10297   case UO_Minus: {
10298     if (!Visit(E->getSubExpr()))
10299       return false;
10300     if (!Result.isInt()) return Error(E);
10301     const APSInt &Value = Result.getInt();
10302     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
10303         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
10304                         E->getType()))
10305       return false;
10306     return Success(-Value, E);
10307   }
10308   case UO_Not: {
10309     if (!Visit(E->getSubExpr()))
10310       return false;
10311     if (!Result.isInt()) return Error(E);
10312     return Success(~Result.getInt(), E);
10313   }
10314   case UO_LNot: {
10315     bool bres;
10316     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10317       return false;
10318     return Success(!bres, E);
10319   }
10320   }
10321 }
10322 
10323 /// HandleCast - This is used to evaluate implicit or explicit casts where the
10324 /// result type is integer.
10325 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
10326   const Expr *SubExpr = E->getSubExpr();
10327   QualType DestType = E->getType();
10328   QualType SrcType = SubExpr->getType();
10329 
10330   switch (E->getCastKind()) {
10331   case CK_BaseToDerived:
10332   case CK_DerivedToBase:
10333   case CK_UncheckedDerivedToBase:
10334   case CK_Dynamic:
10335   case CK_ToUnion:
10336   case CK_ArrayToPointerDecay:
10337   case CK_FunctionToPointerDecay:
10338   case CK_NullToPointer:
10339   case CK_NullToMemberPointer:
10340   case CK_BaseToDerivedMemberPointer:
10341   case CK_DerivedToBaseMemberPointer:
10342   case CK_ReinterpretMemberPointer:
10343   case CK_ConstructorConversion:
10344   case CK_IntegralToPointer:
10345   case CK_ToVoid:
10346   case CK_VectorSplat:
10347   case CK_IntegralToFloating:
10348   case CK_FloatingCast:
10349   case CK_CPointerToObjCPointerCast:
10350   case CK_BlockPointerToObjCPointerCast:
10351   case CK_AnyPointerToBlockPointerCast:
10352   case CK_ObjCObjectLValueCast:
10353   case CK_FloatingRealToComplex:
10354   case CK_FloatingComplexToReal:
10355   case CK_FloatingComplexCast:
10356   case CK_FloatingComplexToIntegralComplex:
10357   case CK_IntegralRealToComplex:
10358   case CK_IntegralComplexCast:
10359   case CK_IntegralComplexToFloatingComplex:
10360   case CK_BuiltinFnToFnPtr:
10361   case CK_ZeroToOCLOpaqueType:
10362   case CK_NonAtomicToAtomic:
10363   case CK_AddressSpaceConversion:
10364   case CK_IntToOCLSampler:
10365   case CK_FixedPointCast:
10366   case CK_IntegralToFixedPoint:
10367     llvm_unreachable("invalid cast kind for integral value");
10368 
10369   case CK_BitCast:
10370   case CK_Dependent:
10371   case CK_LValueBitCast:
10372   case CK_ARCProduceObject:
10373   case CK_ARCConsumeObject:
10374   case CK_ARCReclaimReturnedObject:
10375   case CK_ARCExtendBlockObject:
10376   case CK_CopyAndAutoreleaseBlockObject:
10377     return Error(E);
10378 
10379   case CK_UserDefinedConversion:
10380   case CK_LValueToRValue:
10381   case CK_AtomicToNonAtomic:
10382   case CK_NoOp:
10383     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10384 
10385   case CK_MemberPointerToBoolean:
10386   case CK_PointerToBoolean:
10387   case CK_IntegralToBoolean:
10388   case CK_FloatingToBoolean:
10389   case CK_BooleanToSignedIntegral:
10390   case CK_FloatingComplexToBoolean:
10391   case CK_IntegralComplexToBoolean: {
10392     bool BoolResult;
10393     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
10394       return false;
10395     uint64_t IntResult = BoolResult;
10396     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
10397       IntResult = (uint64_t)-1;
10398     return Success(IntResult, E);
10399   }
10400 
10401   case CK_FixedPointToIntegral: {
10402     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
10403     if (!EvaluateFixedPoint(SubExpr, Src, Info))
10404       return false;
10405     bool Overflowed;
10406     llvm::APSInt Result = Src.convertToInt(
10407         Info.Ctx.getIntWidth(DestType),
10408         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
10409     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10410       return false;
10411     return Success(Result, E);
10412   }
10413 
10414   case CK_FixedPointToBoolean: {
10415     // Unsigned padding does not affect this.
10416     APValue Val;
10417     if (!Evaluate(Val, Info, SubExpr))
10418       return false;
10419     return Success(Val.getFixedPoint().getBoolValue(), E);
10420   }
10421 
10422   case CK_IntegralCast: {
10423     if (!Visit(SubExpr))
10424       return false;
10425 
10426     if (!Result.isInt()) {
10427       // Allow casts of address-of-label differences if they are no-ops
10428       // or narrowing.  (The narrowing case isn't actually guaranteed to
10429       // be constant-evaluatable except in some narrow cases which are hard
10430       // to detect here.  We let it through on the assumption the user knows
10431       // what they are doing.)
10432       if (Result.isAddrLabelDiff())
10433         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
10434       // Only allow casts of lvalues if they are lossless.
10435       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
10436     }
10437 
10438     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
10439                                       Result.getInt()), E);
10440   }
10441 
10442   case CK_PointerToIntegral: {
10443     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
10444 
10445     LValue LV;
10446     if (!EvaluatePointer(SubExpr, LV, Info))
10447       return false;
10448 
10449     if (LV.getLValueBase()) {
10450       // Only allow based lvalue casts if they are lossless.
10451       // FIXME: Allow a larger integer size than the pointer size, and allow
10452       // narrowing back down to pointer width in subsequent integral casts.
10453       // FIXME: Check integer type's active bits, not its type size.
10454       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
10455         return Error(E);
10456 
10457       LV.Designator.setInvalid();
10458       LV.moveInto(Result);
10459       return true;
10460     }
10461 
10462     APSInt AsInt;
10463     APValue V;
10464     LV.moveInto(V);
10465     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
10466       llvm_unreachable("Can't cast this!");
10467 
10468     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
10469   }
10470 
10471   case CK_IntegralComplexToReal: {
10472     ComplexValue C;
10473     if (!EvaluateComplex(SubExpr, C, Info))
10474       return false;
10475     return Success(C.getComplexIntReal(), E);
10476   }
10477 
10478   case CK_FloatingToIntegral: {
10479     APFloat F(0.0);
10480     if (!EvaluateFloat(SubExpr, F, Info))
10481       return false;
10482 
10483     APSInt Value;
10484     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
10485       return false;
10486     return Success(Value, E);
10487   }
10488   }
10489 
10490   llvm_unreachable("unknown cast resulting in integral value");
10491 }
10492 
10493 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10494   if (E->getSubExpr()->getType()->isAnyComplexType()) {
10495     ComplexValue LV;
10496     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10497       return false;
10498     if (!LV.isComplexInt())
10499       return Error(E);
10500     return Success(LV.getComplexIntReal(), E);
10501   }
10502 
10503   return Visit(E->getSubExpr());
10504 }
10505 
10506 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10507   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
10508     ComplexValue LV;
10509     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10510       return false;
10511     if (!LV.isComplexInt())
10512       return Error(E);
10513     return Success(LV.getComplexIntImag(), E);
10514   }
10515 
10516   VisitIgnoredValue(E->getSubExpr());
10517   return Success(0, E);
10518 }
10519 
10520 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
10521   return Success(E->getPackLength(), E);
10522 }
10523 
10524 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
10525   return Success(E->getValue(), E);
10526 }
10527 
10528 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10529   switch (E->getOpcode()) {
10530     default:
10531       // Invalid unary operators
10532       return Error(E);
10533     case UO_Plus:
10534       // The result is just the value.
10535       return Visit(E->getSubExpr());
10536     case UO_Minus: {
10537       if (!Visit(E->getSubExpr())) return false;
10538       if (!Result.isFixedPoint())
10539         return Error(E);
10540       bool Overflowed;
10541       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
10542       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
10543         return false;
10544       return Success(Negated, E);
10545     }
10546     case UO_LNot: {
10547       bool bres;
10548       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10549         return false;
10550       return Success(!bres, E);
10551     }
10552   }
10553 }
10554 
10555 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
10556   const Expr *SubExpr = E->getSubExpr();
10557   QualType DestType = E->getType();
10558   assert(DestType->isFixedPointType() &&
10559          "Expected destination type to be a fixed point type");
10560   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
10561 
10562   switch (E->getCastKind()) {
10563   case CK_FixedPointCast: {
10564     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
10565     if (!EvaluateFixedPoint(SubExpr, Src, Info))
10566       return false;
10567     bool Overflowed;
10568     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
10569     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10570       return false;
10571     return Success(Result, E);
10572   }
10573   case CK_IntegralToFixedPoint: {
10574     APSInt Src;
10575     if (!EvaluateInteger(SubExpr, Src, Info))
10576       return false;
10577 
10578     bool Overflowed;
10579     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
10580         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
10581 
10582     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
10583       return false;
10584 
10585     return Success(IntResult, E);
10586   }
10587   case CK_NoOp:
10588   case CK_LValueToRValue:
10589     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10590   default:
10591     return Error(E);
10592   }
10593 }
10594 
10595 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10596   const Expr *LHS = E->getLHS();
10597   const Expr *RHS = E->getRHS();
10598   FixedPointSemantics ResultFXSema =
10599       Info.Ctx.getFixedPointSemantics(E->getType());
10600 
10601   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
10602   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
10603     return false;
10604   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
10605   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
10606     return false;
10607 
10608   switch (E->getOpcode()) {
10609   case BO_Add: {
10610     bool AddOverflow, ConversionOverflow;
10611     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
10612                               .convert(ResultFXSema, &ConversionOverflow);
10613     if ((AddOverflow || ConversionOverflow) &&
10614         !HandleOverflow(Info, E, Result, E->getType()))
10615       return false;
10616     return Success(Result, E);
10617   }
10618   default:
10619     return false;
10620   }
10621   llvm_unreachable("Should've exited before this");
10622 }
10623 
10624 //===----------------------------------------------------------------------===//
10625 // Float Evaluation
10626 //===----------------------------------------------------------------------===//
10627 
10628 namespace {
10629 class FloatExprEvaluator
10630   : public ExprEvaluatorBase<FloatExprEvaluator> {
10631   APFloat &Result;
10632 public:
10633   FloatExprEvaluator(EvalInfo &info, APFloat &result)
10634     : ExprEvaluatorBaseTy(info), Result(result) {}
10635 
10636   bool Success(const APValue &V, const Expr *e) {
10637     Result = V.getFloat();
10638     return true;
10639   }
10640 
10641   bool ZeroInitialization(const Expr *E) {
10642     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
10643     return true;
10644   }
10645 
10646   bool VisitCallExpr(const CallExpr *E);
10647 
10648   bool VisitUnaryOperator(const UnaryOperator *E);
10649   bool VisitBinaryOperator(const BinaryOperator *E);
10650   bool VisitFloatingLiteral(const FloatingLiteral *E);
10651   bool VisitCastExpr(const CastExpr *E);
10652 
10653   bool VisitUnaryReal(const UnaryOperator *E);
10654   bool VisitUnaryImag(const UnaryOperator *E);
10655 
10656   // FIXME: Missing: array subscript of vector, member of vector
10657 };
10658 } // end anonymous namespace
10659 
10660 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
10661   assert(E->isRValue() && E->getType()->isRealFloatingType());
10662   return FloatExprEvaluator(Info, Result).Visit(E);
10663 }
10664 
10665 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
10666                                   QualType ResultTy,
10667                                   const Expr *Arg,
10668                                   bool SNaN,
10669                                   llvm::APFloat &Result) {
10670   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
10671   if (!S) return false;
10672 
10673   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
10674 
10675   llvm::APInt fill;
10676 
10677   // Treat empty strings as if they were zero.
10678   if (S->getString().empty())
10679     fill = llvm::APInt(32, 0);
10680   else if (S->getString().getAsInteger(0, fill))
10681     return false;
10682 
10683   if (Context.getTargetInfo().isNan2008()) {
10684     if (SNaN)
10685       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10686     else
10687       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10688   } else {
10689     // Prior to IEEE 754-2008, architectures were allowed to choose whether
10690     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
10691     // a different encoding to what became a standard in 2008, and for pre-
10692     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
10693     // sNaN. This is now known as "legacy NaN" encoding.
10694     if (SNaN)
10695       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10696     else
10697       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10698   }
10699 
10700   return true;
10701 }
10702 
10703 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
10704   switch (E->getBuiltinCallee()) {
10705   default:
10706     return ExprEvaluatorBaseTy::VisitCallExpr(E);
10707 
10708   case Builtin::BI__builtin_huge_val:
10709   case Builtin::BI__builtin_huge_valf:
10710   case Builtin::BI__builtin_huge_vall:
10711   case Builtin::BI__builtin_huge_valf128:
10712   case Builtin::BI__builtin_inf:
10713   case Builtin::BI__builtin_inff:
10714   case Builtin::BI__builtin_infl:
10715   case Builtin::BI__builtin_inff128: {
10716     const llvm::fltSemantics &Sem =
10717       Info.Ctx.getFloatTypeSemantics(E->getType());
10718     Result = llvm::APFloat::getInf(Sem);
10719     return true;
10720   }
10721 
10722   case Builtin::BI__builtin_nans:
10723   case Builtin::BI__builtin_nansf:
10724   case Builtin::BI__builtin_nansl:
10725   case Builtin::BI__builtin_nansf128:
10726     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10727                                true, Result))
10728       return Error(E);
10729     return true;
10730 
10731   case Builtin::BI__builtin_nan:
10732   case Builtin::BI__builtin_nanf:
10733   case Builtin::BI__builtin_nanl:
10734   case Builtin::BI__builtin_nanf128:
10735     // If this is __builtin_nan() turn this into a nan, otherwise we
10736     // can't constant fold it.
10737     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10738                                false, Result))
10739       return Error(E);
10740     return true;
10741 
10742   case Builtin::BI__builtin_fabs:
10743   case Builtin::BI__builtin_fabsf:
10744   case Builtin::BI__builtin_fabsl:
10745   case Builtin::BI__builtin_fabsf128:
10746     if (!EvaluateFloat(E->getArg(0), Result, Info))
10747       return false;
10748 
10749     if (Result.isNegative())
10750       Result.changeSign();
10751     return true;
10752 
10753   // FIXME: Builtin::BI__builtin_powi
10754   // FIXME: Builtin::BI__builtin_powif
10755   // FIXME: Builtin::BI__builtin_powil
10756 
10757   case Builtin::BI__builtin_copysign:
10758   case Builtin::BI__builtin_copysignf:
10759   case Builtin::BI__builtin_copysignl:
10760   case Builtin::BI__builtin_copysignf128: {
10761     APFloat RHS(0.);
10762     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10763         !EvaluateFloat(E->getArg(1), RHS, Info))
10764       return false;
10765     Result.copySign(RHS);
10766     return true;
10767   }
10768   }
10769 }
10770 
10771 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10772   if (E->getSubExpr()->getType()->isAnyComplexType()) {
10773     ComplexValue CV;
10774     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10775       return false;
10776     Result = CV.FloatReal;
10777     return true;
10778   }
10779 
10780   return Visit(E->getSubExpr());
10781 }
10782 
10783 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10784   if (E->getSubExpr()->getType()->isAnyComplexType()) {
10785     ComplexValue CV;
10786     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10787       return false;
10788     Result = CV.FloatImag;
10789     return true;
10790   }
10791 
10792   VisitIgnoredValue(E->getSubExpr());
10793   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
10794   Result = llvm::APFloat::getZero(Sem);
10795   return true;
10796 }
10797 
10798 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10799   switch (E->getOpcode()) {
10800   default: return Error(E);
10801   case UO_Plus:
10802     return EvaluateFloat(E->getSubExpr(), Result, Info);
10803   case UO_Minus:
10804     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
10805       return false;
10806     Result.changeSign();
10807     return true;
10808   }
10809 }
10810 
10811 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10812   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10813     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10814 
10815   APFloat RHS(0.0);
10816   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
10817   if (!LHSOK && !Info.noteFailure())
10818     return false;
10819   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
10820          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
10821 }
10822 
10823 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
10824   Result = E->getValue();
10825   return true;
10826 }
10827 
10828 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
10829   const Expr* SubExpr = E->getSubExpr();
10830 
10831   switch (E->getCastKind()) {
10832   default:
10833     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10834 
10835   case CK_IntegralToFloating: {
10836     APSInt IntResult;
10837     return EvaluateInteger(SubExpr, IntResult, Info) &&
10838            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10839                                 E->getType(), Result);
10840   }
10841 
10842   case CK_FloatingCast: {
10843     if (!Visit(SubExpr))
10844       return false;
10845     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10846                                   Result);
10847   }
10848 
10849   case CK_FloatingComplexToReal: {
10850     ComplexValue V;
10851     if (!EvaluateComplex(SubExpr, V, Info))
10852       return false;
10853     Result = V.getComplexFloatReal();
10854     return true;
10855   }
10856   }
10857 }
10858 
10859 //===----------------------------------------------------------------------===//
10860 // Complex Evaluation (for float and integer)
10861 //===----------------------------------------------------------------------===//
10862 
10863 namespace {
10864 class ComplexExprEvaluator
10865   : public ExprEvaluatorBase<ComplexExprEvaluator> {
10866   ComplexValue &Result;
10867 
10868 public:
10869   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
10870     : ExprEvaluatorBaseTy(info), Result(Result) {}
10871 
10872   bool Success(const APValue &V, const Expr *e) {
10873     Result.setFrom(V);
10874     return true;
10875   }
10876 
10877   bool ZeroInitialization(const Expr *E);
10878 
10879   //===--------------------------------------------------------------------===//
10880   //                            Visitor Methods
10881   //===--------------------------------------------------------------------===//
10882 
10883   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
10884   bool VisitCastExpr(const CastExpr *E);
10885   bool VisitBinaryOperator(const BinaryOperator *E);
10886   bool VisitUnaryOperator(const UnaryOperator *E);
10887   bool VisitInitListExpr(const InitListExpr *E);
10888 };
10889 } // end anonymous namespace
10890 
10891 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10892                             EvalInfo &Info) {
10893   assert(E->isRValue() && E->getType()->isAnyComplexType());
10894   return ComplexExprEvaluator(Info, Result).Visit(E);
10895 }
10896 
10897 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
10898   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
10899   if (ElemTy->isRealFloatingType()) {
10900     Result.makeComplexFloat();
10901     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10902     Result.FloatReal = Zero;
10903     Result.FloatImag = Zero;
10904   } else {
10905     Result.makeComplexInt();
10906     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10907     Result.IntReal = Zero;
10908     Result.IntImag = Zero;
10909   }
10910   return true;
10911 }
10912 
10913 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10914   const Expr* SubExpr = E->getSubExpr();
10915 
10916   if (SubExpr->getType()->isRealFloatingType()) {
10917     Result.makeComplexFloat();
10918     APFloat &Imag = Result.FloatImag;
10919     if (!EvaluateFloat(SubExpr, Imag, Info))
10920       return false;
10921 
10922     Result.FloatReal = APFloat(Imag.getSemantics());
10923     return true;
10924   } else {
10925     assert(SubExpr->getType()->isIntegerType() &&
10926            "Unexpected imaginary literal.");
10927 
10928     Result.makeComplexInt();
10929     APSInt &Imag = Result.IntImag;
10930     if (!EvaluateInteger(SubExpr, Imag, Info))
10931       return false;
10932 
10933     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10934     return true;
10935   }
10936 }
10937 
10938 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
10939 
10940   switch (E->getCastKind()) {
10941   case CK_BitCast:
10942   case CK_BaseToDerived:
10943   case CK_DerivedToBase:
10944   case CK_UncheckedDerivedToBase:
10945   case CK_Dynamic:
10946   case CK_ToUnion:
10947   case CK_ArrayToPointerDecay:
10948   case CK_FunctionToPointerDecay:
10949   case CK_NullToPointer:
10950   case CK_NullToMemberPointer:
10951   case CK_BaseToDerivedMemberPointer:
10952   case CK_DerivedToBaseMemberPointer:
10953   case CK_MemberPointerToBoolean:
10954   case CK_ReinterpretMemberPointer:
10955   case CK_ConstructorConversion:
10956   case CK_IntegralToPointer:
10957   case CK_PointerToIntegral:
10958   case CK_PointerToBoolean:
10959   case CK_ToVoid:
10960   case CK_VectorSplat:
10961   case CK_IntegralCast:
10962   case CK_BooleanToSignedIntegral:
10963   case CK_IntegralToBoolean:
10964   case CK_IntegralToFloating:
10965   case CK_FloatingToIntegral:
10966   case CK_FloatingToBoolean:
10967   case CK_FloatingCast:
10968   case CK_CPointerToObjCPointerCast:
10969   case CK_BlockPointerToObjCPointerCast:
10970   case CK_AnyPointerToBlockPointerCast:
10971   case CK_ObjCObjectLValueCast:
10972   case CK_FloatingComplexToReal:
10973   case CK_FloatingComplexToBoolean:
10974   case CK_IntegralComplexToReal:
10975   case CK_IntegralComplexToBoolean:
10976   case CK_ARCProduceObject:
10977   case CK_ARCConsumeObject:
10978   case CK_ARCReclaimReturnedObject:
10979   case CK_ARCExtendBlockObject:
10980   case CK_CopyAndAutoreleaseBlockObject:
10981   case CK_BuiltinFnToFnPtr:
10982   case CK_ZeroToOCLOpaqueType:
10983   case CK_NonAtomicToAtomic:
10984   case CK_AddressSpaceConversion:
10985   case CK_IntToOCLSampler:
10986   case CK_FixedPointCast:
10987   case CK_FixedPointToBoolean:
10988   case CK_FixedPointToIntegral:
10989   case CK_IntegralToFixedPoint:
10990     llvm_unreachable("invalid cast kind for complex value");
10991 
10992   case CK_LValueToRValue:
10993   case CK_AtomicToNonAtomic:
10994   case CK_NoOp:
10995     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10996 
10997   case CK_Dependent:
10998   case CK_LValueBitCast:
10999   case CK_UserDefinedConversion:
11000     return Error(E);
11001 
11002   case CK_FloatingRealToComplex: {
11003     APFloat &Real = Result.FloatReal;
11004     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
11005       return false;
11006 
11007     Result.makeComplexFloat();
11008     Result.FloatImag = APFloat(Real.getSemantics());
11009     return true;
11010   }
11011 
11012   case CK_FloatingComplexCast: {
11013     if (!Visit(E->getSubExpr()))
11014       return false;
11015 
11016     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11017     QualType From
11018       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11019 
11020     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11021            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
11022   }
11023 
11024   case CK_FloatingComplexToIntegralComplex: {
11025     if (!Visit(E->getSubExpr()))
11026       return false;
11027 
11028     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11029     QualType From
11030       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11031     Result.makeComplexInt();
11032     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11033                                 To, Result.IntReal) &&
11034            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11035                                 To, Result.IntImag);
11036   }
11037 
11038   case CK_IntegralRealToComplex: {
11039     APSInt &Real = Result.IntReal;
11040     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11041       return false;
11042 
11043     Result.makeComplexInt();
11044     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11045     return true;
11046   }
11047 
11048   case CK_IntegralComplexCast: {
11049     if (!Visit(E->getSubExpr()))
11050       return false;
11051 
11052     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11053     QualType From
11054       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11055 
11056     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11057     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
11058     return true;
11059   }
11060 
11061   case CK_IntegralComplexToFloatingComplex: {
11062     if (!Visit(E->getSubExpr()))
11063       return false;
11064 
11065     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
11066     QualType From
11067       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
11068     Result.makeComplexFloat();
11069     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11070                                 To, Result.FloatReal) &&
11071            HandleIntToFloatCast(Info, E, From, Result.IntImag,
11072                                 To, Result.FloatImag);
11073   }
11074   }
11075 
11076   llvm_unreachable("unknown cast resulting in complex value");
11077 }
11078 
11079 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11080   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11081     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11082 
11083   // Track whether the LHS or RHS is real at the type system level. When this is
11084   // the case we can simplify our evaluation strategy.
11085   bool LHSReal = false, RHSReal = false;
11086 
11087   bool LHSOK;
11088   if (E->getLHS()->getType()->isRealFloatingType()) {
11089     LHSReal = true;
11090     APFloat &Real = Result.FloatReal;
11091     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11092     if (LHSOK) {
11093       Result.makeComplexFloat();
11094       Result.FloatImag = APFloat(Real.getSemantics());
11095     }
11096   } else {
11097     LHSOK = Visit(E->getLHS());
11098   }
11099   if (!LHSOK && !Info.noteFailure())
11100     return false;
11101 
11102   ComplexValue RHS;
11103   if (E->getRHS()->getType()->isRealFloatingType()) {
11104     RHSReal = true;
11105     APFloat &Real = RHS.FloatReal;
11106     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11107       return false;
11108     RHS.makeComplexFloat();
11109     RHS.FloatImag = APFloat(Real.getSemantics());
11110   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11111     return false;
11112 
11113   assert(!(LHSReal && RHSReal) &&
11114          "Cannot have both operands of a complex operation be real.");
11115   switch (E->getOpcode()) {
11116   default: return Error(E);
11117   case BO_Add:
11118     if (Result.isComplexFloat()) {
11119       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11120                                        APFloat::rmNearestTiesToEven);
11121       if (LHSReal)
11122         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11123       else if (!RHSReal)
11124         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11125                                          APFloat::rmNearestTiesToEven);
11126     } else {
11127       Result.getComplexIntReal() += RHS.getComplexIntReal();
11128       Result.getComplexIntImag() += RHS.getComplexIntImag();
11129     }
11130     break;
11131   case BO_Sub:
11132     if (Result.isComplexFloat()) {
11133       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11134                                             APFloat::rmNearestTiesToEven);
11135       if (LHSReal) {
11136         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11137         Result.getComplexFloatImag().changeSign();
11138       } else if (!RHSReal) {
11139         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11140                                               APFloat::rmNearestTiesToEven);
11141       }
11142     } else {
11143       Result.getComplexIntReal() -= RHS.getComplexIntReal();
11144       Result.getComplexIntImag() -= RHS.getComplexIntImag();
11145     }
11146     break;
11147   case BO_Mul:
11148     if (Result.isComplexFloat()) {
11149       // This is an implementation of complex multiplication according to the
11150       // constraints laid out in C11 Annex G. The implementation uses the
11151       // following naming scheme:
11152       //   (a + ib) * (c + id)
11153       ComplexValue LHS = Result;
11154       APFloat &A = LHS.getComplexFloatReal();
11155       APFloat &B = LHS.getComplexFloatImag();
11156       APFloat &C = RHS.getComplexFloatReal();
11157       APFloat &D = RHS.getComplexFloatImag();
11158       APFloat &ResR = Result.getComplexFloatReal();
11159       APFloat &ResI = Result.getComplexFloatImag();
11160       if (LHSReal) {
11161         assert(!RHSReal && "Cannot have two real operands for a complex op!");
11162         ResR = A * C;
11163         ResI = A * D;
11164       } else if (RHSReal) {
11165         ResR = C * A;
11166         ResI = C * B;
11167       } else {
11168         // In the fully general case, we need to handle NaNs and infinities
11169         // robustly.
11170         APFloat AC = A * C;
11171         APFloat BD = B * D;
11172         APFloat AD = A * D;
11173         APFloat BC = B * C;
11174         ResR = AC - BD;
11175         ResI = AD + BC;
11176         if (ResR.isNaN() && ResI.isNaN()) {
11177           bool Recalc = false;
11178           if (A.isInfinity() || B.isInfinity()) {
11179             A = APFloat::copySign(
11180                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11181             B = APFloat::copySign(
11182                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11183             if (C.isNaN())
11184               C = APFloat::copySign(APFloat(C.getSemantics()), C);
11185             if (D.isNaN())
11186               D = APFloat::copySign(APFloat(D.getSemantics()), D);
11187             Recalc = true;
11188           }
11189           if (C.isInfinity() || D.isInfinity()) {
11190             C = APFloat::copySign(
11191                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11192             D = APFloat::copySign(
11193                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11194             if (A.isNaN())
11195               A = APFloat::copySign(APFloat(A.getSemantics()), A);
11196             if (B.isNaN())
11197               B = APFloat::copySign(APFloat(B.getSemantics()), B);
11198             Recalc = true;
11199           }
11200           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11201                           AD.isInfinity() || BC.isInfinity())) {
11202             if (A.isNaN())
11203               A = APFloat::copySign(APFloat(A.getSemantics()), A);
11204             if (B.isNaN())
11205               B = APFloat::copySign(APFloat(B.getSemantics()), B);
11206             if (C.isNaN())
11207               C = APFloat::copySign(APFloat(C.getSemantics()), C);
11208             if (D.isNaN())
11209               D = APFloat::copySign(APFloat(D.getSemantics()), D);
11210             Recalc = true;
11211           }
11212           if (Recalc) {
11213             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11214             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11215           }
11216         }
11217       }
11218     } else {
11219       ComplexValue LHS = Result;
11220       Result.getComplexIntReal() =
11221         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11222          LHS.getComplexIntImag() * RHS.getComplexIntImag());
11223       Result.getComplexIntImag() =
11224         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11225          LHS.getComplexIntImag() * RHS.getComplexIntReal());
11226     }
11227     break;
11228   case BO_Div:
11229     if (Result.isComplexFloat()) {
11230       // This is an implementation of complex division according to the
11231       // constraints laid out in C11 Annex G. The implementation uses the
11232       // following naming scheme:
11233       //   (a + ib) / (c + id)
11234       ComplexValue LHS = Result;
11235       APFloat &A = LHS.getComplexFloatReal();
11236       APFloat &B = LHS.getComplexFloatImag();
11237       APFloat &C = RHS.getComplexFloatReal();
11238       APFloat &D = RHS.getComplexFloatImag();
11239       APFloat &ResR = Result.getComplexFloatReal();
11240       APFloat &ResI = Result.getComplexFloatImag();
11241       if (RHSReal) {
11242         ResR = A / C;
11243         ResI = B / C;
11244       } else {
11245         if (LHSReal) {
11246           // No real optimizations we can do here, stub out with zero.
11247           B = APFloat::getZero(A.getSemantics());
11248         }
11249         int DenomLogB = 0;
11250         APFloat MaxCD = maxnum(abs(C), abs(D));
11251         if (MaxCD.isFinite()) {
11252           DenomLogB = ilogb(MaxCD);
11253           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11254           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
11255         }
11256         APFloat Denom = C * C + D * D;
11257         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11258                       APFloat::rmNearestTiesToEven);
11259         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11260                       APFloat::rmNearestTiesToEven);
11261         if (ResR.isNaN() && ResI.isNaN()) {
11262           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11263             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11264             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11265           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11266                      D.isFinite()) {
11267             A = APFloat::copySign(
11268                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11269             B = APFloat::copySign(
11270                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11271             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11272             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11273           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11274             C = APFloat::copySign(
11275                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11276             D = APFloat::copySign(
11277                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11278             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11279             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11280           }
11281         }
11282       }
11283     } else {
11284       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11285         return Error(E, diag::note_expr_divide_by_zero);
11286 
11287       ComplexValue LHS = Result;
11288       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11289         RHS.getComplexIntImag() * RHS.getComplexIntImag();
11290       Result.getComplexIntReal() =
11291         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11292          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11293       Result.getComplexIntImag() =
11294         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11295          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11296     }
11297     break;
11298   }
11299 
11300   return true;
11301 }
11302 
11303 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11304   // Get the operand value into 'Result'.
11305   if (!Visit(E->getSubExpr()))
11306     return false;
11307 
11308   switch (E->getOpcode()) {
11309   default:
11310     return Error(E);
11311   case UO_Extension:
11312     return true;
11313   case UO_Plus:
11314     // The result is always just the subexpr.
11315     return true;
11316   case UO_Minus:
11317     if (Result.isComplexFloat()) {
11318       Result.getComplexFloatReal().changeSign();
11319       Result.getComplexFloatImag().changeSign();
11320     }
11321     else {
11322       Result.getComplexIntReal() = -Result.getComplexIntReal();
11323       Result.getComplexIntImag() = -Result.getComplexIntImag();
11324     }
11325     return true;
11326   case UO_Not:
11327     if (Result.isComplexFloat())
11328       Result.getComplexFloatImag().changeSign();
11329     else
11330       Result.getComplexIntImag() = -Result.getComplexIntImag();
11331     return true;
11332   }
11333 }
11334 
11335 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11336   if (E->getNumInits() == 2) {
11337     if (E->getType()->isComplexType()) {
11338       Result.makeComplexFloat();
11339       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
11340         return false;
11341       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
11342         return false;
11343     } else {
11344       Result.makeComplexInt();
11345       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
11346         return false;
11347       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
11348         return false;
11349     }
11350     return true;
11351   }
11352   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
11353 }
11354 
11355 //===----------------------------------------------------------------------===//
11356 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
11357 // implicit conversion.
11358 //===----------------------------------------------------------------------===//
11359 
11360 namespace {
11361 class AtomicExprEvaluator :
11362     public ExprEvaluatorBase<AtomicExprEvaluator> {
11363   const LValue *This;
11364   APValue &Result;
11365 public:
11366   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
11367       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11368 
11369   bool Success(const APValue &V, const Expr *E) {
11370     Result = V;
11371     return true;
11372   }
11373 
11374   bool ZeroInitialization(const Expr *E) {
11375     ImplicitValueInitExpr VIE(
11376         E->getType()->castAs<AtomicType>()->getValueType());
11377     // For atomic-qualified class (and array) types in C++, initialize the
11378     // _Atomic-wrapped subobject directly, in-place.
11379     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
11380                 : Evaluate(Result, Info, &VIE);
11381   }
11382 
11383   bool VisitCastExpr(const CastExpr *E) {
11384     switch (E->getCastKind()) {
11385     default:
11386       return ExprEvaluatorBaseTy::VisitCastExpr(E);
11387     case CK_NonAtomicToAtomic:
11388       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
11389                   : Evaluate(Result, Info, E->getSubExpr());
11390     }
11391   }
11392 };
11393 } // end anonymous namespace
11394 
11395 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
11396                            EvalInfo &Info) {
11397   assert(E->isRValue() && E->getType()->isAtomicType());
11398   return AtomicExprEvaluator(Info, This, Result).Visit(E);
11399 }
11400 
11401 //===----------------------------------------------------------------------===//
11402 // Void expression evaluation, primarily for a cast to void on the LHS of a
11403 // comma operator
11404 //===----------------------------------------------------------------------===//
11405 
11406 namespace {
11407 class VoidExprEvaluator
11408   : public ExprEvaluatorBase<VoidExprEvaluator> {
11409 public:
11410   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
11411 
11412   bool Success(const APValue &V, const Expr *e) { return true; }
11413 
11414   bool ZeroInitialization(const Expr *E) { return true; }
11415 
11416   bool VisitCastExpr(const CastExpr *E) {
11417     switch (E->getCastKind()) {
11418     default:
11419       return ExprEvaluatorBaseTy::VisitCastExpr(E);
11420     case CK_ToVoid:
11421       VisitIgnoredValue(E->getSubExpr());
11422       return true;
11423     }
11424   }
11425 
11426   bool VisitCallExpr(const CallExpr *E) {
11427     switch (E->getBuiltinCallee()) {
11428     default:
11429       return ExprEvaluatorBaseTy::VisitCallExpr(E);
11430     case Builtin::BI__assume:
11431     case Builtin::BI__builtin_assume:
11432       // The argument is not evaluated!
11433       return true;
11434     }
11435   }
11436 };
11437 } // end anonymous namespace
11438 
11439 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
11440   assert(E->isRValue() && E->getType()->isVoidType());
11441   return VoidExprEvaluator(Info).Visit(E);
11442 }
11443 
11444 //===----------------------------------------------------------------------===//
11445 // Top level Expr::EvaluateAsRValue method.
11446 //===----------------------------------------------------------------------===//
11447 
11448 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
11449   // In C, function designators are not lvalues, but we evaluate them as if they
11450   // are.
11451   QualType T = E->getType();
11452   if (E->isGLValue() || T->isFunctionType()) {
11453     LValue LV;
11454     if (!EvaluateLValue(E, LV, Info))
11455       return false;
11456     LV.moveInto(Result);
11457   } else if (T->isVectorType()) {
11458     if (!EvaluateVector(E, Result, Info))
11459       return false;
11460   } else if (T->isIntegralOrEnumerationType()) {
11461     if (!IntExprEvaluator(Info, Result).Visit(E))
11462       return false;
11463   } else if (T->hasPointerRepresentation()) {
11464     LValue LV;
11465     if (!EvaluatePointer(E, LV, Info))
11466       return false;
11467     LV.moveInto(Result);
11468   } else if (T->isRealFloatingType()) {
11469     llvm::APFloat F(0.0);
11470     if (!EvaluateFloat(E, F, Info))
11471       return false;
11472     Result = APValue(F);
11473   } else if (T->isAnyComplexType()) {
11474     ComplexValue C;
11475     if (!EvaluateComplex(E, C, Info))
11476       return false;
11477     C.moveInto(Result);
11478   } else if (T->isFixedPointType()) {
11479     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
11480   } else if (T->isMemberPointerType()) {
11481     MemberPtr P;
11482     if (!EvaluateMemberPointer(E, P, Info))
11483       return false;
11484     P.moveInto(Result);
11485     return true;
11486   } else if (T->isArrayType()) {
11487     LValue LV;
11488     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
11489     if (!EvaluateArray(E, LV, Value, Info))
11490       return false;
11491     Result = Value;
11492   } else if (T->isRecordType()) {
11493     LValue LV;
11494     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
11495     if (!EvaluateRecord(E, LV, Value, Info))
11496       return false;
11497     Result = Value;
11498   } else if (T->isVoidType()) {
11499     if (!Info.getLangOpts().CPlusPlus11)
11500       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
11501         << E->getType();
11502     if (!EvaluateVoid(E, Info))
11503       return false;
11504   } else if (T->isAtomicType()) {
11505     QualType Unqual = T.getAtomicUnqualifiedType();
11506     if (Unqual->isArrayType() || Unqual->isRecordType()) {
11507       LValue LV;
11508       APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
11509       if (!EvaluateAtomic(E, &LV, Value, Info))
11510         return false;
11511     } else {
11512       if (!EvaluateAtomic(E, nullptr, Result, Info))
11513         return false;
11514     }
11515   } else if (Info.getLangOpts().CPlusPlus11) {
11516     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
11517     return false;
11518   } else {
11519     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11520     return false;
11521   }
11522 
11523   return true;
11524 }
11525 
11526 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
11527 /// cases, the in-place evaluation is essential, since later initializers for
11528 /// an object can indirectly refer to subobjects which were initialized earlier.
11529 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
11530                             const Expr *E, bool AllowNonLiteralTypes) {
11531   assert(!E->isValueDependent());
11532 
11533   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
11534     return false;
11535 
11536   if (E->isRValue()) {
11537     // Evaluate arrays and record types in-place, so that later initializers can
11538     // refer to earlier-initialized members of the object.
11539     QualType T = E->getType();
11540     if (T->isArrayType())
11541       return EvaluateArray(E, This, Result, Info);
11542     else if (T->isRecordType())
11543       return EvaluateRecord(E, This, Result, Info);
11544     else if (T->isAtomicType()) {
11545       QualType Unqual = T.getAtomicUnqualifiedType();
11546       if (Unqual->isArrayType() || Unqual->isRecordType())
11547         return EvaluateAtomic(E, &This, Result, Info);
11548     }
11549   }
11550 
11551   // For any other type, in-place evaluation is unimportant.
11552   return Evaluate(Result, Info, E);
11553 }
11554 
11555 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
11556 /// lvalue-to-rvalue cast if it is an lvalue.
11557 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
11558   if (E->getType().isNull())
11559     return false;
11560 
11561   if (!CheckLiteralType(Info, E))
11562     return false;
11563 
11564   if (!::Evaluate(Result, Info, E))
11565     return false;
11566 
11567   if (E->isGLValue()) {
11568     LValue LV;
11569     LV.setFrom(Info.Ctx, Result);
11570     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
11571       return false;
11572   }
11573 
11574   // Check this core constant expression is a constant expression.
11575   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
11576 }
11577 
11578 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
11579                                  const ASTContext &Ctx, bool &IsConst) {
11580   // Fast-path evaluations of integer literals, since we sometimes see files
11581   // containing vast quantities of these.
11582   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
11583     Result.Val = APValue(APSInt(L->getValue(),
11584                                 L->getType()->isUnsignedIntegerType()));
11585     IsConst = true;
11586     return true;
11587   }
11588 
11589   // This case should be rare, but we need to check it before we check on
11590   // the type below.
11591   if (Exp->getType().isNull()) {
11592     IsConst = false;
11593     return true;
11594   }
11595 
11596   // FIXME: Evaluating values of large array and record types can cause
11597   // performance problems. Only do so in C++11 for now.
11598   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
11599                           Exp->getType()->isRecordType()) &&
11600       !Ctx.getLangOpts().CPlusPlus11) {
11601     IsConst = false;
11602     return true;
11603   }
11604   return false;
11605 }
11606 
11607 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
11608                                       Expr::SideEffectsKind SEK) {
11609   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
11610          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
11611 }
11612 
11613 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
11614                              const ASTContext &Ctx, EvalInfo &Info) {
11615   bool IsConst;
11616   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
11617     return IsConst;
11618 
11619   return EvaluateAsRValue(Info, E, Result.Val);
11620 }
11621 
11622 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
11623                           const ASTContext &Ctx,
11624                           Expr::SideEffectsKind AllowSideEffects,
11625                           EvalInfo &Info) {
11626   if (!E->getType()->isIntegralOrEnumerationType())
11627     return false;
11628 
11629   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
11630       !ExprResult.Val.isInt() ||
11631       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11632     return false;
11633 
11634   return true;
11635 }
11636 
11637 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
11638                                  const ASTContext &Ctx,
11639                                  Expr::SideEffectsKind AllowSideEffects,
11640                                  EvalInfo &Info) {
11641   if (!E->getType()->isFixedPointType())
11642     return false;
11643 
11644   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
11645     return false;
11646 
11647   if (!ExprResult.Val.isFixedPoint() ||
11648       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11649     return false;
11650 
11651   return true;
11652 }
11653 
11654 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
11655 /// any crazy technique (that has nothing to do with language standards) that
11656 /// we want to.  If this function returns true, it returns the folded constant
11657 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
11658 /// will be applied to the result.
11659 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
11660                             bool InConstantContext) const {
11661   assert(!isValueDependent() &&
11662          "Expression evaluator can't be called on a dependent expression.");
11663   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11664   Info.InConstantContext = InConstantContext;
11665   return ::EvaluateAsRValue(this, Result, Ctx, Info);
11666 }
11667 
11668 bool Expr::EvaluateAsBooleanCondition(bool &Result,
11669                                       const ASTContext &Ctx) const {
11670   assert(!isValueDependent() &&
11671          "Expression evaluator can't be called on a dependent expression.");
11672   EvalResult Scratch;
11673   return EvaluateAsRValue(Scratch, Ctx) &&
11674          HandleConversionToBool(Scratch.Val, Result);
11675 }
11676 
11677 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
11678                          SideEffectsKind AllowSideEffects) const {
11679   assert(!isValueDependent() &&
11680          "Expression evaluator can't be called on a dependent expression.");
11681   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11682   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
11683 }
11684 
11685 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
11686                                 SideEffectsKind AllowSideEffects) const {
11687   assert(!isValueDependent() &&
11688          "Expression evaluator can't be called on a dependent expression.");
11689   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11690   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
11691 }
11692 
11693 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
11694                            SideEffectsKind AllowSideEffects) const {
11695   assert(!isValueDependent() &&
11696          "Expression evaluator can't be called on a dependent expression.");
11697 
11698   if (!getType()->isRealFloatingType())
11699     return false;
11700 
11701   EvalResult ExprResult;
11702   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
11703       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11704     return false;
11705 
11706   Result = ExprResult.Val.getFloat();
11707   return true;
11708 }
11709 
11710 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
11711   assert(!isValueDependent() &&
11712          "Expression evaluator can't be called on a dependent expression.");
11713 
11714   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
11715 
11716   LValue LV;
11717   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
11718       !CheckLValueConstantExpression(Info, getExprLoc(),
11719                                      Ctx.getLValueReferenceType(getType()), LV,
11720                                      Expr::EvaluateForCodeGen))
11721     return false;
11722 
11723   LV.moveInto(Result.Val);
11724   return true;
11725 }
11726 
11727 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
11728                                   const ASTContext &Ctx) const {
11729   assert(!isValueDependent() &&
11730          "Expression evaluator can't be called on a dependent expression.");
11731 
11732   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
11733   EvalInfo Info(Ctx, Result, EM);
11734   Info.InConstantContext = true;
11735 
11736   if (!::Evaluate(Result.Val, Info, this))
11737     return false;
11738 
11739   return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
11740                                  Usage);
11741 }
11742 
11743 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
11744                                  const VarDecl *VD,
11745                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
11746   assert(!isValueDependent() &&
11747          "Expression evaluator can't be called on a dependent expression.");
11748 
11749   // FIXME: Evaluating initializers for large array and record types can cause
11750   // performance problems. Only do so in C++11 for now.
11751   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
11752       !Ctx.getLangOpts().CPlusPlus11)
11753     return false;
11754 
11755   Expr::EvalStatus EStatus;
11756   EStatus.Diag = &Notes;
11757 
11758   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11759                                       ? EvalInfo::EM_ConstantExpression
11760                                       : EvalInfo::EM_ConstantFold);
11761   InitInfo.setEvaluatingDecl(VD, Value);
11762   InitInfo.InConstantContext = true;
11763 
11764   LValue LVal;
11765   LVal.set(VD);
11766 
11767   // C++11 [basic.start.init]p2:
11768   //  Variables with static storage duration or thread storage duration shall be
11769   //  zero-initialized before any other initialization takes place.
11770   // This behavior is not present in C.
11771   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
11772       !VD->getType()->isReferenceType()) {
11773     ImplicitValueInitExpr VIE(VD->getType());
11774     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
11775                          /*AllowNonLiteralTypes=*/true))
11776       return false;
11777   }
11778 
11779   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
11780                        /*AllowNonLiteralTypes=*/true) ||
11781       EStatus.HasSideEffects)
11782     return false;
11783 
11784   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
11785                                  Value);
11786 }
11787 
11788 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
11789 /// constant folded, but discard the result.
11790 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
11791   assert(!isValueDependent() &&
11792          "Expression evaluator can't be called on a dependent expression.");
11793 
11794   EvalResult Result;
11795   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
11796          !hasUnacceptableSideEffect(Result, SEK);
11797 }
11798 
11799 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
11800                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
11801   assert(!isValueDependent() &&
11802          "Expression evaluator can't be called on a dependent expression.");
11803 
11804   EvalResult EVResult;
11805   EVResult.Diag = Diag;
11806   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
11807   Info.InConstantContext = true;
11808 
11809   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
11810   (void)Result;
11811   assert(Result && "Could not evaluate expression");
11812   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
11813 
11814   return EVResult.Val.getInt();
11815 }
11816 
11817 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
11818     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
11819   assert(!isValueDependent() &&
11820          "Expression evaluator can't be called on a dependent expression.");
11821 
11822   EvalResult EVResult;
11823   EVResult.Diag = Diag;
11824   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11825   Info.InConstantContext = true;
11826 
11827   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
11828   (void)Result;
11829   assert(Result && "Could not evaluate expression");
11830   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
11831 
11832   return EVResult.Val.getInt();
11833 }
11834 
11835 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
11836   assert(!isValueDependent() &&
11837          "Expression evaluator can't be called on a dependent expression.");
11838 
11839   bool IsConst;
11840   EvalResult EVResult;
11841   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
11842     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11843     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
11844   }
11845 }
11846 
11847 bool Expr::EvalResult::isGlobalLValue() const {
11848   assert(Val.isLValue());
11849   return IsGlobalLValue(Val.getLValueBase());
11850 }
11851 
11852 
11853 /// isIntegerConstantExpr - this recursive routine will test if an expression is
11854 /// an integer constant expression.
11855 
11856 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
11857 /// comma, etc
11858 
11859 // CheckICE - This function does the fundamental ICE checking: the returned
11860 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
11861 // and a (possibly null) SourceLocation indicating the location of the problem.
11862 //
11863 // Note that to reduce code duplication, this helper does no evaluation
11864 // itself; the caller checks whether the expression is evaluatable, and
11865 // in the rare cases where CheckICE actually cares about the evaluated
11866 // value, it calls into Evaluate.
11867 
11868 namespace {
11869 
11870 enum ICEKind {
11871   /// This expression is an ICE.
11872   IK_ICE,
11873   /// This expression is not an ICE, but if it isn't evaluated, it's
11874   /// a legal subexpression for an ICE. This return value is used to handle
11875   /// the comma operator in C99 mode, and non-constant subexpressions.
11876   IK_ICEIfUnevaluated,
11877   /// This expression is not an ICE, and is not a legal subexpression for one.
11878   IK_NotICE
11879 };
11880 
11881 struct ICEDiag {
11882   ICEKind Kind;
11883   SourceLocation Loc;
11884 
11885   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
11886 };
11887 
11888 }
11889 
11890 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11891 
11892 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
11893 
11894 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
11895   Expr::EvalResult EVResult;
11896   Expr::EvalStatus Status;
11897   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11898 
11899   Info.InConstantContext = true;
11900   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
11901       !EVResult.Val.isInt())
11902     return ICEDiag(IK_NotICE, E->getBeginLoc());
11903 
11904   return NoDiag();
11905 }
11906 
11907 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
11908   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
11909   if (!E->getType()->isIntegralOrEnumerationType())
11910     return ICEDiag(IK_NotICE, E->getBeginLoc());
11911 
11912   switch (E->getStmtClass()) {
11913 #define ABSTRACT_STMT(Node)
11914 #define STMT(Node, Base) case Expr::Node##Class:
11915 #define EXPR(Node, Base)
11916 #include "clang/AST/StmtNodes.inc"
11917   case Expr::PredefinedExprClass:
11918   case Expr::FloatingLiteralClass:
11919   case Expr::ImaginaryLiteralClass:
11920   case Expr::StringLiteralClass:
11921   case Expr::ArraySubscriptExprClass:
11922   case Expr::OMPArraySectionExprClass:
11923   case Expr::MemberExprClass:
11924   case Expr::CompoundAssignOperatorClass:
11925   case Expr::CompoundLiteralExprClass:
11926   case Expr::ExtVectorElementExprClass:
11927   case Expr::DesignatedInitExprClass:
11928   case Expr::ArrayInitLoopExprClass:
11929   case Expr::ArrayInitIndexExprClass:
11930   case Expr::NoInitExprClass:
11931   case Expr::DesignatedInitUpdateExprClass:
11932   case Expr::ImplicitValueInitExprClass:
11933   case Expr::ParenListExprClass:
11934   case Expr::VAArgExprClass:
11935   case Expr::AddrLabelExprClass:
11936   case Expr::StmtExprClass:
11937   case Expr::CXXMemberCallExprClass:
11938   case Expr::CUDAKernelCallExprClass:
11939   case Expr::CXXDynamicCastExprClass:
11940   case Expr::CXXTypeidExprClass:
11941   case Expr::CXXUuidofExprClass:
11942   case Expr::MSPropertyRefExprClass:
11943   case Expr::MSPropertySubscriptExprClass:
11944   case Expr::CXXNullPtrLiteralExprClass:
11945   case Expr::UserDefinedLiteralClass:
11946   case Expr::CXXThisExprClass:
11947   case Expr::CXXThrowExprClass:
11948   case Expr::CXXNewExprClass:
11949   case Expr::CXXDeleteExprClass:
11950   case Expr::CXXPseudoDestructorExprClass:
11951   case Expr::UnresolvedLookupExprClass:
11952   case Expr::TypoExprClass:
11953   case Expr::DependentScopeDeclRefExprClass:
11954   case Expr::CXXConstructExprClass:
11955   case Expr::CXXInheritedCtorInitExprClass:
11956   case Expr::CXXStdInitializerListExprClass:
11957   case Expr::CXXBindTemporaryExprClass:
11958   case Expr::ExprWithCleanupsClass:
11959   case Expr::CXXTemporaryObjectExprClass:
11960   case Expr::CXXUnresolvedConstructExprClass:
11961   case Expr::CXXDependentScopeMemberExprClass:
11962   case Expr::UnresolvedMemberExprClass:
11963   case Expr::ObjCStringLiteralClass:
11964   case Expr::ObjCBoxedExprClass:
11965   case Expr::ObjCArrayLiteralClass:
11966   case Expr::ObjCDictionaryLiteralClass:
11967   case Expr::ObjCEncodeExprClass:
11968   case Expr::ObjCMessageExprClass:
11969   case Expr::ObjCSelectorExprClass:
11970   case Expr::ObjCProtocolExprClass:
11971   case Expr::ObjCIvarRefExprClass:
11972   case Expr::ObjCPropertyRefExprClass:
11973   case Expr::ObjCSubscriptRefExprClass:
11974   case Expr::ObjCIsaExprClass:
11975   case Expr::ObjCAvailabilityCheckExprClass:
11976   case Expr::ShuffleVectorExprClass:
11977   case Expr::ConvertVectorExprClass:
11978   case Expr::BlockExprClass:
11979   case Expr::NoStmtClass:
11980   case Expr::OpaqueValueExprClass:
11981   case Expr::PackExpansionExprClass:
11982   case Expr::SubstNonTypeTemplateParmPackExprClass:
11983   case Expr::FunctionParmPackExprClass:
11984   case Expr::AsTypeExprClass:
11985   case Expr::ObjCIndirectCopyRestoreExprClass:
11986   case Expr::MaterializeTemporaryExprClass:
11987   case Expr::PseudoObjectExprClass:
11988   case Expr::AtomicExprClass:
11989   case Expr::LambdaExprClass:
11990   case Expr::CXXFoldExprClass:
11991   case Expr::CoawaitExprClass:
11992   case Expr::DependentCoawaitExprClass:
11993   case Expr::CoyieldExprClass:
11994     return ICEDiag(IK_NotICE, E->getBeginLoc());
11995 
11996   case Expr::InitListExprClass: {
11997     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11998     // form "T x = { a };" is equivalent to "T x = a;".
11999     // Unless we're initializing a reference, T is a scalar as it is known to be
12000     // of integral or enumeration type.
12001     if (E->isRValue())
12002       if (cast<InitListExpr>(E)->getNumInits() == 1)
12003         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
12004     return ICEDiag(IK_NotICE, E->getBeginLoc());
12005   }
12006 
12007   case Expr::SizeOfPackExprClass:
12008   case Expr::GNUNullExprClass:
12009   case Expr::SourceLocExprClass:
12010     return NoDiag();
12011 
12012   case Expr::SubstNonTypeTemplateParmExprClass:
12013     return
12014       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12015 
12016   case Expr::ConstantExprClass:
12017     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12018 
12019   case Expr::ParenExprClass:
12020     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
12021   case Expr::GenericSelectionExprClass:
12022     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
12023   case Expr::IntegerLiteralClass:
12024   case Expr::FixedPointLiteralClass:
12025   case Expr::CharacterLiteralClass:
12026   case Expr::ObjCBoolLiteralExprClass:
12027   case Expr::CXXBoolLiteralExprClass:
12028   case Expr::CXXScalarValueInitExprClass:
12029   case Expr::TypeTraitExprClass:
12030   case Expr::ArrayTypeTraitExprClass:
12031   case Expr::ExpressionTraitExprClass:
12032   case Expr::CXXNoexceptExprClass:
12033     return NoDiag();
12034   case Expr::CallExprClass:
12035   case Expr::CXXOperatorCallExprClass: {
12036     // C99 6.6/3 allows function calls within unevaluated subexpressions of
12037     // constant expressions, but they can never be ICEs because an ICE cannot
12038     // contain an operand of (pointer to) function type.
12039     const CallExpr *CE = cast<CallExpr>(E);
12040     if (CE->getBuiltinCallee())
12041       return CheckEvalInICE(E, Ctx);
12042     return ICEDiag(IK_NotICE, E->getBeginLoc());
12043   }
12044   case Expr::DeclRefExprClass: {
12045     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12046       return NoDiag();
12047     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
12048     if (Ctx.getLangOpts().CPlusPlus &&
12049         D && IsConstNonVolatile(D->getType())) {
12050       // Parameter variables are never constants.  Without this check,
12051       // getAnyInitializer() can find a default argument, which leads
12052       // to chaos.
12053       if (isa<ParmVarDecl>(D))
12054         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12055 
12056       // C++ 7.1.5.1p2
12057       //   A variable of non-volatile const-qualified integral or enumeration
12058       //   type initialized by an ICE can be used in ICEs.
12059       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
12060         if (!Dcl->getType()->isIntegralOrEnumerationType())
12061           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12062 
12063         const VarDecl *VD;
12064         // Look for a declaration of this variable that has an initializer, and
12065         // check whether it is an ICE.
12066         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12067           return NoDiag();
12068         else
12069           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12070       }
12071     }
12072     return ICEDiag(IK_NotICE, E->getBeginLoc());
12073   }
12074   case Expr::UnaryOperatorClass: {
12075     const UnaryOperator *Exp = cast<UnaryOperator>(E);
12076     switch (Exp->getOpcode()) {
12077     case UO_PostInc:
12078     case UO_PostDec:
12079     case UO_PreInc:
12080     case UO_PreDec:
12081     case UO_AddrOf:
12082     case UO_Deref:
12083     case UO_Coawait:
12084       // C99 6.6/3 allows increment and decrement within unevaluated
12085       // subexpressions of constant expressions, but they can never be ICEs
12086       // because an ICE cannot contain an lvalue operand.
12087       return ICEDiag(IK_NotICE, E->getBeginLoc());
12088     case UO_Extension:
12089     case UO_LNot:
12090     case UO_Plus:
12091     case UO_Minus:
12092     case UO_Not:
12093     case UO_Real:
12094     case UO_Imag:
12095       return CheckICE(Exp->getSubExpr(), Ctx);
12096     }
12097     llvm_unreachable("invalid unary operator class");
12098   }
12099   case Expr::OffsetOfExprClass: {
12100     // Note that per C99, offsetof must be an ICE. And AFAIK, using
12101     // EvaluateAsRValue matches the proposed gcc behavior for cases like
12102     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
12103     // compliance: we should warn earlier for offsetof expressions with
12104     // array subscripts that aren't ICEs, and if the array subscripts
12105     // are ICEs, the value of the offsetof must be an integer constant.
12106     return CheckEvalInICE(E, Ctx);
12107   }
12108   case Expr::UnaryExprOrTypeTraitExprClass: {
12109     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12110     if ((Exp->getKind() ==  UETT_SizeOf) &&
12111         Exp->getTypeOfArgument()->isVariableArrayType())
12112       return ICEDiag(IK_NotICE, E->getBeginLoc());
12113     return NoDiag();
12114   }
12115   case Expr::BinaryOperatorClass: {
12116     const BinaryOperator *Exp = cast<BinaryOperator>(E);
12117     switch (Exp->getOpcode()) {
12118     case BO_PtrMemD:
12119     case BO_PtrMemI:
12120     case BO_Assign:
12121     case BO_MulAssign:
12122     case BO_DivAssign:
12123     case BO_RemAssign:
12124     case BO_AddAssign:
12125     case BO_SubAssign:
12126     case BO_ShlAssign:
12127     case BO_ShrAssign:
12128     case BO_AndAssign:
12129     case BO_XorAssign:
12130     case BO_OrAssign:
12131       // C99 6.6/3 allows assignments within unevaluated subexpressions of
12132       // constant expressions, but they can never be ICEs because an ICE cannot
12133       // contain an lvalue operand.
12134       return ICEDiag(IK_NotICE, E->getBeginLoc());
12135 
12136     case BO_Mul:
12137     case BO_Div:
12138     case BO_Rem:
12139     case BO_Add:
12140     case BO_Sub:
12141     case BO_Shl:
12142     case BO_Shr:
12143     case BO_LT:
12144     case BO_GT:
12145     case BO_LE:
12146     case BO_GE:
12147     case BO_EQ:
12148     case BO_NE:
12149     case BO_And:
12150     case BO_Xor:
12151     case BO_Or:
12152     case BO_Comma:
12153     case BO_Cmp: {
12154       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12155       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12156       if (Exp->getOpcode() == BO_Div ||
12157           Exp->getOpcode() == BO_Rem) {
12158         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
12159         // we don't evaluate one.
12160         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
12161           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
12162           if (REval == 0)
12163             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12164           if (REval.isSigned() && REval.isAllOnesValue()) {
12165             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
12166             if (LEval.isMinSignedValue())
12167               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12168           }
12169         }
12170       }
12171       if (Exp->getOpcode() == BO_Comma) {
12172         if (Ctx.getLangOpts().C99) {
12173           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12174           // if it isn't evaluated.
12175           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
12176             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12177         } else {
12178           // In both C89 and C++, commas in ICEs are illegal.
12179           return ICEDiag(IK_NotICE, E->getBeginLoc());
12180         }
12181       }
12182       return Worst(LHSResult, RHSResult);
12183     }
12184     case BO_LAnd:
12185     case BO_LOr: {
12186       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12187       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12188       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
12189         // Rare case where the RHS has a comma "side-effect"; we need
12190         // to actually check the condition to see whether the side
12191         // with the comma is evaluated.
12192         if ((Exp->getOpcode() == BO_LAnd) !=
12193             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
12194           return RHSResult;
12195         return NoDiag();
12196       }
12197 
12198       return Worst(LHSResult, RHSResult);
12199     }
12200     }
12201     llvm_unreachable("invalid binary operator kind");
12202   }
12203   case Expr::ImplicitCastExprClass:
12204   case Expr::CStyleCastExprClass:
12205   case Expr::CXXFunctionalCastExprClass:
12206   case Expr::CXXStaticCastExprClass:
12207   case Expr::CXXReinterpretCastExprClass:
12208   case Expr::CXXConstCastExprClass:
12209   case Expr::ObjCBridgedCastExprClass: {
12210     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
12211     if (isa<ExplicitCastExpr>(E)) {
12212       if (const FloatingLiteral *FL
12213             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12214         unsigned DestWidth = Ctx.getIntWidth(E->getType());
12215         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12216         APSInt IgnoredVal(DestWidth, !DestSigned);
12217         bool Ignored;
12218         // If the value does not fit in the destination type, the behavior is
12219         // undefined, so we are not required to treat it as a constant
12220         // expression.
12221         if (FL->getValue().convertToInteger(IgnoredVal,
12222                                             llvm::APFloat::rmTowardZero,
12223                                             &Ignored) & APFloat::opInvalidOp)
12224           return ICEDiag(IK_NotICE, E->getBeginLoc());
12225         return NoDiag();
12226       }
12227     }
12228     switch (cast<CastExpr>(E)->getCastKind()) {
12229     case CK_LValueToRValue:
12230     case CK_AtomicToNonAtomic:
12231     case CK_NonAtomicToAtomic:
12232     case CK_NoOp:
12233     case CK_IntegralToBoolean:
12234     case CK_IntegralCast:
12235       return CheckICE(SubExpr, Ctx);
12236     default:
12237       return ICEDiag(IK_NotICE, E->getBeginLoc());
12238     }
12239   }
12240   case Expr::BinaryConditionalOperatorClass: {
12241     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12242     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
12243     if (CommonResult.Kind == IK_NotICE) return CommonResult;
12244     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12245     if (FalseResult.Kind == IK_NotICE) return FalseResult;
12246     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12247     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
12248         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
12249     return FalseResult;
12250   }
12251   case Expr::ConditionalOperatorClass: {
12252     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12253     // If the condition (ignoring parens) is a __builtin_constant_p call,
12254     // then only the true side is actually considered in an integer constant
12255     // expression, and it is fully evaluated.  This is an important GNU
12256     // extension.  See GCC PR38377 for discussion.
12257     if (const CallExpr *CallCE
12258         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
12259       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
12260         return CheckEvalInICE(E, Ctx);
12261     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
12262     if (CondResult.Kind == IK_NotICE)
12263       return CondResult;
12264 
12265     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12266     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12267 
12268     if (TrueResult.Kind == IK_NotICE)
12269       return TrueResult;
12270     if (FalseResult.Kind == IK_NotICE)
12271       return FalseResult;
12272     if (CondResult.Kind == IK_ICEIfUnevaluated)
12273       return CondResult;
12274     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
12275       return NoDiag();
12276     // Rare case where the diagnostics depend on which side is evaluated
12277     // Note that if we get here, CondResult is 0, and at least one of
12278     // TrueResult and FalseResult is non-zero.
12279     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
12280       return FalseResult;
12281     return TrueResult;
12282   }
12283   case Expr::CXXDefaultArgExprClass:
12284     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
12285   case Expr::CXXDefaultInitExprClass:
12286     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
12287   case Expr::ChooseExprClass: {
12288     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
12289   }
12290   }
12291 
12292   llvm_unreachable("Invalid StmtClass!");
12293 }
12294 
12295 /// Evaluate an expression as a C++11 integral constant expression.
12296 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
12297                                                     const Expr *E,
12298                                                     llvm::APSInt *Value,
12299                                                     SourceLocation *Loc) {
12300   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12301     if (Loc) *Loc = E->getExprLoc();
12302     return false;
12303   }
12304 
12305   APValue Result;
12306   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
12307     return false;
12308 
12309   if (!Result.isInt()) {
12310     if (Loc) *Loc = E->getExprLoc();
12311     return false;
12312   }
12313 
12314   if (Value) *Value = Result.getInt();
12315   return true;
12316 }
12317 
12318 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
12319                                  SourceLocation *Loc) const {
12320   assert(!isValueDependent() &&
12321          "Expression evaluator can't be called on a dependent expression.");
12322 
12323   if (Ctx.getLangOpts().CPlusPlus11)
12324     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
12325 
12326   ICEDiag D = CheckICE(this, Ctx);
12327   if (D.Kind != IK_ICE) {
12328     if (Loc) *Loc = D.Loc;
12329     return false;
12330   }
12331   return true;
12332 }
12333 
12334 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
12335                                  SourceLocation *Loc, bool isEvaluated) const {
12336   assert(!isValueDependent() &&
12337          "Expression evaluator can't be called on a dependent expression.");
12338 
12339   if (Ctx.getLangOpts().CPlusPlus11)
12340     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
12341 
12342   if (!isIntegerConstantExpr(Ctx, Loc))
12343     return false;
12344 
12345   // The only possible side-effects here are due to UB discovered in the
12346   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
12347   // required to treat the expression as an ICE, so we produce the folded
12348   // value.
12349   EvalResult ExprResult;
12350   Expr::EvalStatus Status;
12351   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
12352   Info.InConstantContext = true;
12353 
12354   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
12355     llvm_unreachable("ICE cannot be evaluated!");
12356 
12357   Value = ExprResult.Val.getInt();
12358   return true;
12359 }
12360 
12361 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
12362   assert(!isValueDependent() &&
12363          "Expression evaluator can't be called on a dependent expression.");
12364 
12365   return CheckICE(this, Ctx).Kind == IK_ICE;
12366 }
12367 
12368 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
12369                                SourceLocation *Loc) const {
12370   assert(!isValueDependent() &&
12371          "Expression evaluator can't be called on a dependent expression.");
12372 
12373   // We support this checking in C++98 mode in order to diagnose compatibility
12374   // issues.
12375   assert(Ctx.getLangOpts().CPlusPlus);
12376 
12377   // Build evaluation settings.
12378   Expr::EvalStatus Status;
12379   SmallVector<PartialDiagnosticAt, 8> Diags;
12380   Status.Diag = &Diags;
12381   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12382 
12383   APValue Scratch;
12384   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
12385 
12386   if (!Diags.empty()) {
12387     IsConstExpr = false;
12388     if (Loc) *Loc = Diags[0].first;
12389   } else if (!IsConstExpr) {
12390     // FIXME: This shouldn't happen.
12391     if (Loc) *Loc = getExprLoc();
12392   }
12393 
12394   return IsConstExpr;
12395 }
12396 
12397 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
12398                                     const FunctionDecl *Callee,
12399                                     ArrayRef<const Expr*> Args,
12400                                     const Expr *This) const {
12401   assert(!isValueDependent() &&
12402          "Expression evaluator can't be called on a dependent expression.");
12403 
12404   Expr::EvalStatus Status;
12405   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
12406   Info.InConstantContext = true;
12407 
12408   LValue ThisVal;
12409   const LValue *ThisPtr = nullptr;
12410   if (This) {
12411 #ifndef NDEBUG
12412     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
12413     assert(MD && "Don't provide `this` for non-methods.");
12414     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
12415 #endif
12416     if (EvaluateObjectArgument(Info, This, ThisVal))
12417       ThisPtr = &ThisVal;
12418     if (Info.EvalStatus.HasSideEffects)
12419       return false;
12420   }
12421 
12422   ArgVector ArgValues(Args.size());
12423   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
12424        I != E; ++I) {
12425     if ((*I)->isValueDependent() ||
12426         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
12427       // If evaluation fails, throw away the argument entirely.
12428       ArgValues[I - Args.begin()] = APValue();
12429     if (Info.EvalStatus.HasSideEffects)
12430       return false;
12431   }
12432 
12433   // Build fake call to Callee.
12434   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
12435                        ArgValues.data());
12436   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
12437 }
12438 
12439 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
12440                                    SmallVectorImpl<
12441                                      PartialDiagnosticAt> &Diags) {
12442   // FIXME: It would be useful to check constexpr function templates, but at the
12443   // moment the constant expression evaluator cannot cope with the non-rigorous
12444   // ASTs which we build for dependent expressions.
12445   if (FD->isDependentContext())
12446     return true;
12447 
12448   Expr::EvalStatus Status;
12449   Status.Diag = &Diags;
12450 
12451   EvalInfo Info(FD->getASTContext(), Status,
12452                 EvalInfo::EM_PotentialConstantExpression);
12453   Info.InConstantContext = true;
12454 
12455   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
12456   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
12457 
12458   // Fabricate an arbitrary expression on the stack and pretend that it
12459   // is a temporary being used as the 'this' pointer.
12460   LValue This;
12461   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
12462   This.set({&VIE, Info.CurrentCall->Index});
12463 
12464   ArrayRef<const Expr*> Args;
12465 
12466   APValue Scratch;
12467   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
12468     // Evaluate the call as a constant initializer, to allow the construction
12469     // of objects of non-literal types.
12470     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
12471     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
12472   } else {
12473     SourceLocation Loc = FD->getLocation();
12474     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
12475                        Args, FD->getBody(), Info, Scratch, nullptr);
12476   }
12477 
12478   return Diags.empty();
12479 }
12480 
12481 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
12482                                               const FunctionDecl *FD,
12483                                               SmallVectorImpl<
12484                                                 PartialDiagnosticAt> &Diags) {
12485   assert(!E->isValueDependent() &&
12486          "Expression evaluator can't be called on a dependent expression.");
12487 
12488   Expr::EvalStatus Status;
12489   Status.Diag = &Diags;
12490 
12491   EvalInfo Info(FD->getASTContext(), Status,
12492                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
12493   Info.InConstantContext = true;
12494 
12495   // Fabricate a call stack frame to give the arguments a plausible cover story.
12496   ArrayRef<const Expr*> Args;
12497   ArgVector ArgValues(0);
12498   bool Success = EvaluateArgs(Args, ArgValues, Info);
12499   (void)Success;
12500   assert(Success &&
12501          "Failed to set up arguments for potential constant evaluation");
12502   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
12503 
12504   APValue ResultScratch;
12505   Evaluate(ResultScratch, Info, E);
12506   return Diags.empty();
12507 }
12508 
12509 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
12510                                  unsigned Type) const {
12511   if (!getType()->isPointerType())
12512     return false;
12513 
12514   Expr::EvalStatus Status;
12515   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
12516   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
12517 }
12518